2

本文主要介绍下如何在spring中进行发布时间以及接收事件

定义事件

public class DemoEvent extends ApplicationEvent {
    private String message;

    public DemoEvent(Object source, String message) {
        super(source);
        this.message = message;
    }
    public String getMessage() {
        return message;
    }
}

发布事件

    @Autowired
    private ApplicationEventPublisher applicationEventPublisher;

    @GetMapping("/send-event")
    public Object sendEvent(@RequestParam String msg){
        DemoEvent demoEvent = new DemoEvent(this,msg);
        applicationEventPublisher.publishEvent(demoEvent);
        LOGGER.info("finish publish event");
        return "success";
    }

这里在mvc中发布,仅仅是为了演示。

接收事件(默认同步)

@Component
public class DemoEventListener implements ApplicationListener<DemoEvent>{

    private static final Logger LOGGER = LoggerFactory.getLogger(DemoEventListener.class);

    @Override
    public void onApplicationEvent(DemoEvent demoEvent) {
        LOGGER.info("receive event:{}",demoEvent.getMessage());
    }
}

这里是同步接收

异步处理事件

@Configuration
public class AsyncEventConfig {

    @Bean(name = "applicationEventMulticaster")
    public ApplicationEventMulticaster simpleApplicationEventMulticaster() {
        SimpleApplicationEventMulticaster eventMulticaster
                = new SimpleApplicationEventMulticaster();

        eventMulticaster.setTaskExecutor(new SimpleAsyncTaskExecutor());
        return eventMulticaster;
    }
}

加上这个配置就ok了,不然要注意,这里自己new的task executor,要优雅关闭的话,需要自己shutdown

SimpleApplicationEventMulticaster

spring-context-4.3.11.RELEASE-sources.jar!/org/springframework/context/event/SimpleApplicationEventMulticaster.java

    @Override
    public void multicastEvent(ApplicationEvent event) {
        multicastEvent(event, resolveDefaultEventType(event));
    }

    @Override
    public void multicastEvent(final ApplicationEvent event, ResolvableType eventType) {
        ResolvableType type = (eventType != null ? eventType : resolveDefaultEventType(event));
        for (final ApplicationListener<?> listener : getApplicationListeners(event, type)) {
            Executor executor = getTaskExecutor();
            if (executor != null) {
                executor.execute(new Runnable() {
                    @Override
                    public void run() {
                        invokeListener(listener, event);
                    }
                });
            }
            else {
                invokeListener(listener, event);
            }
        }
    }

    private ResolvableType resolveDefaultEventType(ApplicationEvent event) {
        return ResolvableType.forInstance(event);
    }

可以看到,使用applicationEventMulticaster的时候,如果有线程池,则用线程池异步执行;否则则知直接调用listener的执行方法同步执行。

doc


codecraft
11.9k 声望2k 粉丝

当一个代码的工匠回首往事时,不因虚度年华而悔恨,也不因碌碌无为而羞愧,这样,当他老的时候,可以很自豪告诉世人,我曾经将代码注入生命去打造互联网的浪潮之巅,那是个很疯狂的时代,我在一波波的浪潮上留下...