使用
@RequestMapping("test")
public void result() {
applicationContext.publishEvent(new TesstEvent(this));
}
@EventListener
public void handx(XXe xXe) throws InterruptedException {
sleep(5000);
System.out.println("good");
}
非常简单的使用SpringBoot的Listener,但是它却不是异步的(默认是当前线程执行), 如果需要异步需要额外引入一个线程池.
设置线程池
@Override
public void afterPropertiesSet() throws Exception {
SimpleApplicationEventMulticaster applicationEventMulticaster =
(SimpleApplicationEventMulticaster) applicationContext.getBean("applicationEventMulticaster");
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(5);
executor.setMaxPoolSize(5);
executor.setQueueCapacity(1000);
executor.setThreadNamePrefix("listener-thread-");
executor.initialize();
applicationEventMulticaster.setTaskExecutor(executor);
}
这样就可以使用异步的Listener了.