實(shí)現(xiàn):異步監(jiān)聽兩個(gè)事件,update事件和delete事件
上代碼:
刪除事件定義:
public class DeleteEvent extends ApplicationEvent {
private String eventId;
public DeleteEvent(Object source) {
super(source);
}
public DeleteEvent(Object source, Clock clock) {
super(source, clock);
}
public String getEventId() {
return eventId;
}
public void setEventId(String eventId) {
this.eventId = eventId;
}
}
更新事件定義:
public class UpdateEvent extends ApplicationEvent {
private String eventId;
public UpdateEvent(Object source) {
super(source);
}
public UpdateEvent(Object source, Clock clock) {
super(source, clock);
}
public String getEventId() {
return eventId;
}
public void setEventId(String eventId) {
this.eventId = eventId;
}
}
自定義事件多波器,實(shí)現(xiàn)異步處理:
@Component
public class ListenerConfig {
//異步執(zhí)行的關(guān)鍵,如果不配置Multicaster,則是同步執(zhí)行
//ApplicationEvent默認(rèn)是同步執(zhí)行
@Bean
public SimpleApplicationEventMulticaster applicationEventMulticaster() {
SimpleApplicationEventMulticaster simpleApplicationEventMulticaster = new SimpleApplicationEventMulticaster();
BlockingQueue<Runnable> blockingQueue = new LinkedBlockingDeque<>(1000);
//根據(jù)實(shí)際需要調(diào)整線程數(shù)
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(5, 20, 1, TimeUnit.SECONDS, blockingQueue);
simpleApplicationEventMulticaster.setTaskExecutor(threadPoolExecutor);
return simpleApplicationEventMulticaster;
}
@Bean
public ApplicationListener<UpdateEvent> updateListener(){
return updateEvent -> {
System.out.println("收到更新事件"+updateEvent);
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("輸出更新事件id:"+updateEvent.getEventId());
};
}
@Bean
public ApplicationListener<DeleteEvent> deleteListener(){
return deleteEvent -> {
System.out.println("收到刪除事件"+deleteEvent);
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("輸出刪除事件id:"+deleteEvent.getEventId());
};
}
}
測試:
方式一:
@Autowired
private ApplicationEventPublisher eventPublisher;
@Test
public void tset(){
System.out.println("事件測試開始。。。。");
UpdateEvent update = new UpdateEvent("update");
update.setEventId("update-1");
eventPublisher.publishEvent(update);
DeleteEvent deleteEvent = new DeleteEvent("delete");
deleteEvent.setEventId("delete-1");
eventPublisher.publishEvent(deleteEvent);
System.out.println("事件測試結(jié)束。。。。。");
}
方式二:
@Test
public void tset(){
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(ListenerConfig.class);
System.out.println("事件測試開始。。。。");
UpdateEvent update = new UpdateEvent("update");
update.setEventId("update-1");
applicationContext.publishEvent(update);
DeleteEvent deleteEvent = new DeleteEvent("delete");
deleteEvent.setEventId("delete-1");
applicationContext.publishEvent(deleteEvent);
applicationContext.close();
System.out.println("事件測試結(jié)束。。。。。");
}
結(jié)果輸出:

image.png