---
name: guava-eventbus
title: 单机环境下优雅地使用事件驱动进行代码解耦
date: 2024-03-29 07:48:47
tags:
categories:
---
[TOC]
虽然现在的各种应用都是集群部署,单机部署的应用越来越少了,但是不可否认的是,市场上还是存在许多单机应用的。本文要介绍的是 Guava 中的 EventBus 的使用。
EventBus 处理的事情类似观察者模式,基于事件驱动,观察者们监听自己感兴趣的特定事件,进行相应的处理。
本文想要介绍的内容是,在 Spring 环境中优雅地使用 Guava 包中的 EventBus,对我们的代码进行一定程度的解耦。当然,本文不介绍 EventBus 的原理,我所说的优雅也只是我觉得优雅,也许读者有更漂亮的代码,欢迎在评论区留言。
## Step 0:添加 Guava 依赖
```xml
com.google.guava
guava
22.0
```
作为 java 程序员,如果你还没有使用过 Google Guava,请从现在开始将它加到你的每一个项目中。
## Step 1:定义一个注解用于标记 listener
```java
/**
* 用于标记 listener
*/
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface EventBusListener {
}
```
## Step 2:定义注册中心
```java
package com.javadoop.eventbus;
import java.util.List;
import java.util.concurrent.Executors;
import javax.annotation.PostConstruct;
import org.springframework.stereotype.Component;
import com.google.common.eventbus.AsyncEventBus;
import com.google.common.eventbus.EventBus;
import com.hongjiev.javadoop.util.SpringContextUtils;
@Component
public class EventBusCenter {
// 管理同步事件
private EventBus syncEventBus = new EventBus();
// 管理异步事件
private AsyncEventBus asyncEventBus = new AsyncEventBus(Executors.newCachedThreadPool());
public void postSync(Object event) {
syncEventBus.post(event);
}
public void postAsync(Object event) {
asyncEventBus.post(event);
}
@PostConstruct
public void init() {
// 获取所有带有 @EventBusListener 的 bean,将他们注册为监听者
List