1、好处:解耦
2、Spring的事件机制默认是同步方式
3、@Async可以使用到类级别,也可以到方法级别
开启异步支持 @EnableAsync
@Configuration
@EnableAsync
public class AppCommonConfig implements AsyncConfigurer{
@Override
public Executor getAsyncExecutor() {
//TODO: 这里可以实现自己的线程池
return null;
}
@Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
return null;
}
}
事件消费者
@Component
@Async
public class EventConsumer implements ApplicationListener {
@Override
public void onApplicationEvent(ApplicationEvent event) {
logger.info("接收到事件:" + event.getClass().getSimpleName());
if (event instanceof OrderEvent) {
OrderEvent orderEvent = (OrderEvent) event;
//TODO 后续逻辑
}
}
}
事件生产者
public class XxxService implements ApplicationEventPublisherAware {
//事件发布者
protected ApplicationEventPublisher applicationEventPublisher;
@Override
public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
this.applicationEventPublisher = applicationEventPublisher;
}
public void method11(){
OrderEvent orderEvent = new OrderEvent(this, "data");
applicationEventPublisher.publishEvent(orderEvent);
}
}
事件对象
public class OrderEvent extends ApplicationEvent {
private Object data;
public OrderEvent(Object source, Object data) {
super(source);
this.data = data;
}
public Object getData() {
return data;
}
}
方式二:开启异步支持不实现AsyncConfigurer
@Configuration
@EnableAsync
public class AppCommonConfig {
@Bean(name = "asyncExecutor")
public Executor asyncExecutor()
{
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(3);
executor.setMaxPoolSize(3);
executor.setQueueCapacity(100);
executor.setThreadNamePrefix("AsynchThread-");
executor.initialize();
return executor;
}
}
事件消费者
@Component
@Async("asyncExecutor") //线程池的bean名称
public class EventConsumer implements ApplicationListener {
@Override
public void onApplicationEvent(ApplicationEvent event) {
logger.info("接收到事件:" + event.getClass().getSimpleName());
if (event instanceof OrderEvent) {
OrderEvent orderEvent = (OrderEvent) event;
//TODO 后续逻辑
}
}
}