上一篇添加了基础的时间监听机制
异步实现事件的监听:
注意上面的ApplicationListener 中的监听机制为同步执行,即若发布两个事件,则必须等待前一个事件完成才能继续执行下一个事件,这里可以通过
spring的异步机制来实现:spring3.0版本开始支持@Async注解来实现异步调用。
新建一个线程配置类,此处两点必须@EnableAsync注解和spring内置线程池ThreadPoolTaskExecutor:
@Configuration @EnableAsync public class ListenerAsyncConfiguration implements AsyncConfigurer { /** * 获取异步线程池执行对象 * @return */ @Override public Executor getAsyncExecutor() { //使用Spring内置线程池任务对象 ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor(); //设置线程池参数 taskExecutor.setCorePoolSize(5);//核心池大小 taskExecutor.setMaxPoolSize(10);//最大线程数 taskExecutor.setQueueCapacity(25);//队列程度 taskExecutor.setKeepAliveSeconds(100);//空闲时间 taskExecutor.setThreadNamePrefix("Thread_Test");//线程前缀名称 taskExecutor.initialize(); return taskExecutor; } @Override public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() { return null; } }
监听器中添加@Async注解:
@Component public class UserRegisterEventListener implements ApplicationListener<UserRegisterEvent> { @Override @Async public void onApplicationEvent(UserRegisterEvent userRegisterEvent) { try { Thread.sleep(1000);//静静的沉睡3秒钟 }catch (Exception e) { e.printStackTrace(); } System.out.println(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(LocalDateTime.now())); System.out.println(String.format("接口模式给用户[%S]发送邮件成功",userRegisterEvent.getUserName())); } }