EventBus事件总线

事件总线是guava开发的轻量级的消息发布订阅模式框架,非常适合在单体应用中进行使用

相比MQ它更加轻量,易用,但一般只用于进程内部的通信,不能像MQ一样用于分布式系统的服务与服务之间的通信。

下面是简单使用

引入依赖

<dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>32.1.3-jre</version>
</dependency>

首先创建EventBus对象,这个用于我们的事件发送

EventBus eventBus = new EventBus();
//或者异步
AsyncEventBus asyncEventBus = new AsyncEventBus(Executors.newCachedThreadPool());

然后我们需要自己创建消费端,并且建立对应参数类型消费方法,这里使用@Subscribe注解来进行绑定

@Slf4j
public class EventBusSubscriber{

    @Subscribe
    public void integerSubscriber(Integer integer){
        System.out.println("integer类型的订阅者收到的订阅消息 = " + integer);
    }

    @Subscribe
    public void stringSubscriber(String str){
        System.out.println("String类型的订阅者收到的订阅消息str = " + str);
    }

    @Subscribe
    public void deadEventSubscriber(DeadEvent deadEvent){
        log.error("接收到了没有对应类型的消息{}",deadEvent);
    }
}

可以尝试使用post方法进行消息发布

public class Test {

    static class Person{
        private String name;
        private Integer age;
        private String idCard;
    }
    public static void main(String[] args) {
        EventBus eventBus = new EventBus();
        //或者异步
        AsyncEventBus asyncEventBus = new AsyncEventBus(Executors.newCachedThreadPool());

        eventBus.register(new EventBusSubscriber());

        eventBus.post(1);
        eventBus.post("hello world");
        eventBus.post(new Person());

    }

}

查看控制台并验证

integer类型的订阅者收到的订阅消息 = 1
String类型的订阅者收到的订阅消息str = hello world
23:43:50.465 [main] ERROR com.example.activitydemo.test.EventBusSubscriber - 接收到了没有对应类型的消息DeadEvent{source=EventBus{default}, event=com.example.activitydemo.test.Test$Person@4fb61f4a}


进程已结束,退出代码0

代码执行无误,这里最后一个方法的DeadEvent是用于描述无法被消费端处理的消息,称为死信消息,都归于这中类型可以进行统一异常处理

  • 3
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在 Nuxt2 中使用 eventBus 事件总线,可以通过以下步骤实现: 1. 创建一个 eventBus.js 文件 在项目的根目录中,创建一个 eventBus.js 文件,代码如下: ```javascript import Vue from 'vue'; export const eventBus = new Vue(); ``` 这里使用了 Vue 的实例来创建 eventBus,并且将它导出,这样就可以在项目中的任何地方使用它了。 2. 在需要使用 eventBus 的组件中引入 eventBus 在需要使用 eventBus 的组件中,可以使用以下代码来引入 eventBus: ```javascript import {eventBus} from '@/eventBus.js'; ``` 这里的 @ 表示项目的根目录,如果 eventBus.js 文件不在根目录中,那么需要改成相应的路径。 3. 使用 eventBus 发送事件 在需要发送事件的地方,可以使用以下代码来发送事件: ```javascript eventBus.$emit('eventName', data); ``` 这里的 eventName 是事件的名称,data 是传递的数据。 4. 使用 eventBus 监听事件 在需要监听事件的地方,可以使用以下代码来监听事件: ```javascript eventBus.$on('eventName', (data) => { // 处理事件 }); ``` 这里的 eventName 是事件的名称,data 是传递的数据。事件触发后,会执行回调函数中的代码。 总结: 以上就是在 Nuxt2 中使用 eventBus 事件总线的方法,通过使用 eventBus,可以在组件之间方便地进行通信。需要注意的是,eventBus 的使用需要谨慎,过多的使用可能会导致代码的可读性和维护性降低。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值