使用

  1. @RequestMapping("test")
  2. public void result() {
  3. applicationContext.publishEvent(new TesstEvent(this));
  4. }
  5. @EventListener
  6. public void handx(XXe xXe) throws InterruptedException {
  7. sleep(5000);
  8. System.out.println("good");
  9. }

非常简单的使用SpringBoot的Listener,但是它却不是异步的(默认是当前线程执行), 如果需要异步需要额外引入一个线程池.

设置线程池

  1. @Override
  2. public void afterPropertiesSet() throws Exception {
  3. SimpleApplicationEventMulticaster applicationEventMulticaster =
  4. (SimpleApplicationEventMulticaster) applicationContext.getBean("applicationEventMulticaster");
  5. ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
  6. executor.setCorePoolSize(5);
  7. executor.setMaxPoolSize(5);
  8. executor.setQueueCapacity(1000);
  9. executor.setThreadNamePrefix("listener-thread-");
  10. executor.initialize();
  11. applicationEventMulticaster.setTaskExecutor(executor);
  12. }

这样就可以使用异步的Listener了.