spring boot

spring event发布及监听实例

2017-09-29  本文已影响84人  go4it

本文主要介绍下如何在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

上一篇下一篇

猜你喜欢

热点阅读