google guava的消息总线:EventBus,Java

Posted zhangphil

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了google guava的消息总线:EventBus,Java相关的知识,希望对你有一定的参考价值。

google guava的消息总线:EventBus,Java

pom.xml添加引用:

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

import com.google.common.eventbus.EventBus;
import com.google.common.eventbus.Subscribe;

public class MainClass 
    public static void main(String[] args) 
        AppEventListener appEventListener = new AppEventListener();

        EventBus eventBus = new EventBus();
        //支持异步操作
        //EventBus eventBus = new AsyncEventBus(Executors.newCachedThreadPool());
        eventBus.register(appEventListener);

        eventBus.post("1 zhang");
    

    @Subscribe
    private void receiver(String msg) 
        System.out.println(getClass().getName() + " 收到 " + msg);
    

import com.google.common.eventbus.EventBus;
import com.google.common.eventbus.Subscribe;

public class AppEventListener 
    private EventBus eventBus;

    public AppEventListener() 
        MainClass mainClass = new MainClass();
        eventBus = new EventBus();
        eventBus.register(mainClass);
    

    @Subscribe
    private void receiver(String msg) 
        System.out.println(getClass().getName() + " 收到 " + msg);

        eventBus.post("2 phil");
    

输出:

test.AppEventListener 收到 1 zhang
test.MainClass 收到 2 phil

com.google.guava的maven仓库地址:

https://mvnrepository.com/artifact/com.google.guava/guavahttps://mvnrepository.com/artifact/com.google.guava/guava

以上是关于google guava的消息总线:EventBus,Java的主要内容,如果未能解决你的问题,请参考以下文章

消息总线重构之EventBus

Google Guava EventBus(事件总线)

guava中EventBus(事件总线)源码分析与使用

消息总线重构之EventBus

消息总线重构之EventBus

重复造轮子之LiveDataBus与PageEventBus