Guava中EventBus,事件发布订阅使用

本文介绍如何使用Guava的EventBus实现事件监听与发布机制。包括引入依赖、创建监听器、配置EventBus、发布事件及异步处理等步骤。

它默认是同步的,依次调用Listener。

1.引入依赖

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

2.创建EventBus的Listener

package com.example.demo;

import com.google.common.eventbus.Subscribe;

/**
 * TODO
 *
 * @author 
 * @version 1.0.0
 * @since 2021/06/11 16:35
 */
public class EventListener {

  @Subscribe
  public void processEvent(String message) {
    System.out.println("message:" + message);
  }
}

3.创建EventBus并注册Listener

package com.example.demo;

import com.google.common.eventbus.EventBus;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * TODO
 *
 * @author
 * @version 1.0.0
 * @since 2021/06/11 16:23
 */
@Configuration
public class EventBusConfiguration {

  @Bean
  public EventBus eventBus() {
    EventBus eventBus = new EventBus("myEventBus");
    // 注册listener
    eventBus.register(new EventListener());
    return eventBus;
  }

}

4.发布事件

此处写了一个controller来测试发送消息

package com.example.demo;

import com.google.common.eventbus.EventBus;
import org.springframework.stereotype.Controller;

/**
 * TODO
 *
 * @author 
 * @version 1.0.0
 * @since 2021/03/11 15:58
 */
@Controller
public class TestController implements API{

  @Override
  public String test() {
    EventBus bean = SpringUtil.getBean(EventBus.class);
    bean.post("123");
    return "123";
  }
}

 最终效果

 

5.使用异步的EventBus

// 使用AsyncEventBus,构造函数里的参数为一个线程池
AsyncEventBus asyncEventBus = new AsyncEventBus(Executors.newSingleThreadExecutor());

6.扩展

我们写的listener的processEvent方法参数是String,所以如果在发布事件的时候,发布一个其他类型的,他是不会收到的。

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值