Guava库——EventBus(事件总线)

Guava在guava-libraries中为我们提供了事件总线EventBus库,它是事件发布订阅模式的实现,让我们能在领域驱动设计(DDD)中以事件的弱引用本质对我们的模块和领域边界很好的解耦设计。 

订阅

关于订阅的使用,Guava采用侵入性较弱的注解方式进行订阅。只要在方法上增加@Subscribe,方法参数增加所要传递的对象即可。

发布

EventBus的发布也比较简单,Guava支持同步和异步的方式进行事件总线的发布。分别为EventBus和AsyncEventBus。

应用如下:

public class EventBusTest {
    // 定义异步事件总线的线程池
    private ExecutorService service = new ThreadPoolExecutor(
            5, 5,
            0L, TimeUnit.MILLISECONDS,
            new LinkedBlockingQueue<>(),
            new ThreadFactoryBuilder().setNameFormat("GlobalException-%d").setDaemon(true).build());
    // 创建事件传递对象
    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    @Builder
    private static class Person {
        private String name;
        private int age;
        private char gender;
    }
    // 测试同步事件
    @Test
    public void testEventBus() {
        final EventBus eventBus = new EventBus();

        eventBus.register(new Object() {

            @Subscribe
            public void lister(Integer integer) {
                System.out.println("监听获得数据:" + integer);
            }
        });

        eventBus.post(1);
    }
    // 创建成员方法,并增加订阅注解
    @Subscribe
    public void execute(Person person) {
        System.out.println(person);
    }
    // 测试异步事件
    @Test
    public void testAsyncEventBus() {
        AsyncEventBus asyncEventBus = new AsyncEventBus(executorService);

        asyncEventBus.register(this);
                  asyncEventBus.post(Person.builder().name("tianlixin").age(26).gender('男').build());
    }
    
}

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值