Is It possible to support sync and async Application Events in Spring[5]

随声附和 提交于 2021-01-29 07:12:51

问题


<bean id="applicationEventMulticaster"
        class="com.test.listener.CustomApplicationEventMulticaster">
        <property name="taskExecutor" >
            <bean class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">
                <property name="maxPoolSize" value="10"/>
                <property name="corePoolSize" value="10"/>
                <property name="waitForTasksToCompleteOnShutdown" value="true"/>
                <property name="awaitTerminationSeconds" value="200"/>
            </bean>
        </property>
    </bean>


public class CustomApplicationEventMulticaster extends SimpleApplicationEventMulticaster {
    
    @Override
    public void multicastEvent(final ApplicationEvent event, ResolvableType eventType) {
        
            boolean async = (event instanceof AbstractApplicationEvent) ? ((AbstractApplicationEvent) event).isAsyncEvent()
                    : true;
            final SecurityContext sc = SecurityContextHolder.getContext();
            ResolvableType defaultEventType = ResolvableType.forInstance(event);
            for (final ApplicationListener listener : getApplicationListeners(event, defaultEventType)) {
                Executor executor = getTaskExecutor();
                if (async && executor != null) {
                    executor.execute(() -> {
                            try {
                                SecurityContextHolder.setContext(sc);
                                listener.onApplicationEvent(event);
                            } finally {
                                SecurityContextHolder.clearContext();
                            }
                    });
                } else {
                    listener.onApplicationEvent(event);
                }
            }
        
    }

}

In Application, I am trying to trigger sync and async event.

It is this fine to do?


回答1:


executor.execute(() -> {
                            try {
                                SecurityContext emptyContext = SecurityContextHolder.createEmptyContext();
                                emptyContext.setAuthentication(sc.getAuthentication());
                                listener.onApplicationEvent(event);
                            } finally {
                                SecurityContextHolder.clearContext();
                            }
                        });


来源:https://stackoverflow.com/questions/62917851/is-it-possible-to-support-sync-and-async-application-events-in-spring5

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!