//一、使用线程池
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);
}
}