20191102 常见异步的手段

 

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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值