guava中eventbus用法

​ google的event 事件机制可以用于解耦,类似于spring的事件机制,可以同步也可以异步。

  1. 定时事件(类型随意,guava 调度的时候会根据对应的类型调对应的handler)
package google.event;

import lombok.AllArgsConstructor;
import lombok.Data;

@Data
@AllArgsConstructor
public class Event1 {

    private String name;

    private String tag;
}


----
package google.event;

import lombok.AllArgsConstructor;
import lombok.Data;

@Data
@AllArgsConstructor
public class Event2 {

    private String name;

    private String tag;
}
  
  1. 定义事件处理器

处理器1:

package google.event;

import com.google.common.eventbus.Subscribe;
import org.example.PrintUtils;

public class Event1Handler {

    @Subscribe
    public void handleEvent(Event1 event) {
        PrintUtils.printWithTime("Event1Handler ~~~~");
        PrintUtils.printWithTime(event.toString());
    }
}

处理器2:

package google.event;

import com.google.common.eventbus.Subscribe;
import org.example.PrintUtils;

public class Event2Handler {

    @Subscribe
    public void handleEvent(Event2 event) {
        PrintUtils.printWithTime("Event2Handler ~~~~");
        PrintUtils.printWithTime(event.toString());
    }
}
  1. 测试类:

异步测试,同步消息总线发消息和接收消息都是main 线程

package google.event;

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

import java.util.concurrent.Executors;

public class Client {

    public static void main(String[] args) {
        // 同步
//        EventBus eventBus = new EventBus();
        // 异步,需要传入自己的线程池
        EventBus eventBus = new AsyncEventBus(Executors.newFixedThreadPool(1));

        Event1Handler event1Handler = new Event1Handler();
        Event2Handler event2Handler = new Event2Handler();
        eventBus.register(event1Handler);
        eventBus.register(event2Handler);

        eventBus.post(new Event1("Event1", "Event1"));
        eventBus.post(new Event2("Event2", "Event2"));
    }
}

结果:

pool-1-thread-1	16:30:01	Event1Handler ~~~~
pool-1-thread-1	16:30:02	Event1(name=Event1, tag=Event1)
pool-1-thread-1	16:30:02	Event2Handler ~~~~
pool-1-thread-1	16:30:02	Event2(name=Event2, tag=Event2)

posted @ 2024-02-21 17:55  QiaoZhi  阅读(77)  评论(0编辑  收藏  举报