How to configure Async and Sync Event publishers using spring

前端 未结 4 920
北恋
北恋 2021-01-17 13:25

I am trying to implement an event framework using spring events.I came to know that the default behavior of spring event framework is sync. But during spring context initial

4条回答
  •  情歌与酒
    2021-01-17 14:15

    I just had to work this out for myself. By default events are sent asynchronously except if you implement a marker interface, in my case I called it SynchronousEvent. You'll need an 'executor' in your config too (I omitted mine as it's quite customised).

    @EnableAsync
    @SpringBootConfiguration
    public class BigFishConfig {
    
        @Autowired AsyncTaskExecutor executor;
    
        @Bean
        public ApplicationEventMulticaster applicationEventMulticaster() {
            log.debug("creating multicaster");
            return new SimpleApplicationEventMulticaster() {
                @Override
                public void multicastEvent(final ApplicationEvent event, @Nullable ResolvableType eventType) {
                    ResolvableType type = eventType != null ? eventType : ResolvableType.forInstance(event);
                    if (event instanceof PayloadApplicationEvent 
                            && ((PayloadApplicationEvent) event).getPayload() instanceof SynchronousEvent) 
                        getApplicationListeners(event, type).forEach(l -> invokeListener(l, event));
                    else 
                        getApplicationListeners(event, type).forEach(l -> executor.execute(() -> invokeListener(l, event)));
                }
            };
        }
    ...
    

提交回复
热议问题