//一、使用線程池
ExecutorService executorService= Executors.newFixedThreadPool(5);
executorService.submit(new Runnable() {
@Override
public void run() {
System.out.println("子線程處理");
}
});
//二、使用消息隊列。mq
//消息發送與消息接受
//三、定時任務@Scheduled
//<dependency>
// <groupId>org.quartz-scheduler</groupId>
// <artifactId>quartz</artifactId>
// <version>2.3.0</version>
//</dependency>
//四、guava的AsyncEventBus
EventBus是Guava框架對觀察者模式的一種實現,使用EventBus可以很簡潔的實現事件註冊監聽和消費。Guava框架裏面提供了兩種相關的實現,一種是單線程同步事件消費,另外一直是多線程異步事件消費。後者在對象設計上是前者的子類。
定義一個實體類用來裝載事件內容;
Guava的事件總線EventBus庫是事件發佈訂閱模式的實現,讓我們能在領域驅動設計(DDD)中以事件的弱引用本質對我們的模塊和領域邊界很好的解耦設計。
使用Guava的eventbus完成異步事件
創建事件監聽:把當前類註冊爲監聽器。收到消息後的狀態@Subscribe。
調用異步事件,發佈消息。
/**
* Created on 2019/12/2 18:15
* author:crs
* Description:EventBeanConfiguration
*/
@Configuration
public class EventBeanConfiguration {
@Bean
public AsyncEventBus asyncEventBus(){
return new AsyncEventBus(Executors.newFixedThreadPool(100));
}
}
@Component
public class Event {
@Autowired
private AsyncEventBus asyncEventBus;
//註冊這個監聽器
@PostConstruct
public void register() {
asyncEventBus.register(this);
}
/**
* 打印收到的消息
* @param event
*/
@Subscribe
public void sub(NoticeSmsEvent event) {
System.out.println(event.toString());
}
}
/**
* Created on 2019/12/2 17:58
* author:crs
* Description:測試異步模式
*/
@SpringBootTest
@RunWith(SpringRunner.class)
public class TestEvent {
@Autowired
private AsyncEventBus asyncEventBus;
@Test
public void testEvent() {
//EventBus event = new EventBus();
NoticeSmsEvent noticeSmsEvent = new NoticeSmsEvent(1L, "13024112588", "短信內容");
asyncEventBus.post(noticeSmsEvent);
}
}