异步监听代码实现:
public class AsyncApplicationEventMulticaster extends AbstractApplicationEventMulticaster { private TaskExecutor taskExecutor = new SimpleAsyncTaskExecutor(); public void setTaskExecutor(TaskExecutor taskExecutor) { this.taskExecutor = (taskExecutor != null ? taskExecutor : new SimpleAsyncTaskExecutor()); } protected TaskExecutor getTaskExecutor() { return this.taskExecutor; } @SuppressWarnings("unchecked") public void multicastEvent(final ApplicationEvent event) { for (Iterator<ApplicationListener> it = getApplicationListeners().iterator(); it.hasNext();) { final ApplicationListener listener = it.next(); getTaskExecutor().execute(new Runnable() { public void run() { listener.onApplicationEvent(event); } }); } } }
将实现的异步监听器加入到Spring容器中:
@Bean(name = "applicationEventMulticaster") public ApplicationEventMulticaster simpleApplicationEventMulticaster() { SimpleApplicationEventMulticaster eventMulticaster = new SimpleApplicationEventMulticaster(); //ThreadPoolTaskExecutor eventMulticaster.setTaskExecutor(new SimpleAsyncTaskExecutor()); return eventMulticaster; }
记得多播器的beanName要取名为:applicationEventMulticaster。
End!
标签:异步,监听,TaskExecutor,监听器,taskExecutor,new,public From: https://www.cnblogs.com/zhf123/p/17113097.html