简介
事件总线。
有助于深入理解代码的功能和实现细节。
可以了解代码背后的逻辑、算法、数据结构和设计模式等方面,从而更好地理解代码的作用和功能。
可以学习到业界的最佳实践和设计模式。
这有助于提高自己的编程水平,使你能够编写更高质量、可扩展性和可维护性的代码。
代码结构
包:
com.google.common.eventbus
类:
文件 | 类型 | 描述 |
---|---|---|
AllowConcurrentEvents | 注解 | |
AsyncEventBus | 类 | 异步事件总线 |
DeadEvent | 类 | 无订阅事件 |
Dispatcher | 抽象类 | 分发器,有三种:PerThreadQueuedDispatcher LegacyAsyncDispatcher ImmediateDispatcher |
EventBus | 类 | 同步事件总线 |
Subscribe | 注解 | 事件订阅注解 |
Subscriber | 类 | 订阅者 |
SubscriberExceptionContext | 类 | 订阅异常上下文 |
SubscriberExceptionHandler | 接口 | 订阅异常处理器 |
SubscriberRegistry | 类 | 单个事件总线的订阅者的注册 |
设计模式
观察者模式
发布订阅模式
核心类
分发器
1、PerThreadQueuedDispatcher
同步分发器
执行器
MoreExecutors.directExecutor()
2、LegacyAsyncDispatcher
异步分发器
执行器
自定义线程池
EventBus
SpringBoot集成
@Component
@Slf4j
public class RegisterEventOnApplicationRunner implements ApplicationRunner {
@Autowired
private AsyncEventBus localEventBus;
@Override
public void run(ApplicationArguments args) {
// 获取一个包下的,带有@Subscribe的所有方法
Reflections reflections = new Reflections("com.xxx", new MethodAnnotationsScanner());
Set<Method> methods = reflections.getMethodsAnnotatedWith(Subscribe.class);
if (null != methods ) {
// 遍历并注入
for(Method method : methods) {
try {
localEventBus.register(SpringUtil.getBean(method.getDeclaringClass()));
}catch (Exception e ) {
log.warn(e.getMessage(),e);
}
}
}
}
}