EventBus 不是通用的消息系统,也不是用来做进程间的通信的,而是在进程内,用于解耦两段直接调用的业务逻辑;

1、代码结构

  • event:eventbus中流转的事件(消息),包结构按照业务模块在细分(比如应用部署模块就是deployment);
  • subscriber:消费者,和event 是一一对应的,一个event 对应一个消费者,包结构按照业务模块在细分(比如应用部署模块就是deployment);
  • poster:生产者,这边把生产者单独出来是为了收敛入口,这样可以方便的知道有哪些地方在生产消息,按照业务模块分为不同的类(因为生产消息的功能比较单薄);

2、代码实现

在applicationContext.xml 中定义好EventBus

asyncEventBus
<bean id="taskExecutor" class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor" lazy-init="true">
    <property name="corePoolSize" value="10"/>
    <property name="maxPoolSize" value="50"/>
    <property name="queueCapacity" value="10000"/>
    <property name="keepAliveSeconds" value="300"/>
    <property name="rejectedExecutionHandler">
        <bean class="java.util.concurrent.ThreadPoolExecutor$CallerRunsPolicy"/>
    </property>
</bean>
<bean id="asyncEventBus" class="com.google.common.eventbus.AsyncEventBus">
    <constructor-arg name="executor" ref="taskExecutor"/>
</bean>

2.1、标准化subscriber

所有的subscriber都要实现 BaseSubscriber这个 interface

BaseSubscriber
public interface BaseSubscriber<E> {
 
    /**
     * event 处理逻辑入口
     **/
    void subscribe(E event);
}

所有的subscriber在类上加上EventBusRegister 这个annotation

EventBusRegister
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface EventBusRegister {
}

实现EventBusAdapter用于自动注册subscriber

EventBusAdapter
@Component
public class EventBusAdapter implements ApplicationContextAware, InitializingBean {
    @Autowired
    private AsyncEventBus asyncEventBus;
 
    private ApplicationContext applicationContext;
 
    @Override
    public void afterPropertiesSet() throws Exception {
        this.applicationContext.getBeansWithAnnotation(EventBusRegister.class).forEach((name, bean) -> {
            asyncEventBus.register(bean);
        });
    }
 
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}

举个例子

BuildUpdateSubscriber
@Component
@EventBusRegister
public class BuildUpdateSubscriber implements BaseSubscriber<BuildUpdateEvent> {
    @Autowired
    private BuildService buildService;
 
    @Subscribe
    @Override
    public void subscribe(BuildUpdateEvent event) {
        switch (event.getEventType()) {
            case BUILD_CONNECTED:
                List<BuildVo> buildVos = (List<BuildVo>) event.getData();
                buildService.addBuildVosAndTriggerConnectEvent(buildVos);
                break;
            case BUILD_ADD:
                BuildVo addedBuildVo = (BuildVo) event.getData();
                buildService.addBuildVoAndTriggerClientEvent(addedBuildVo);
                break;
            case BUILD_MODIFY:
                BuildVo modifiedBuildVo = (BuildVo) event.getData();
                buildService.modifyBuildVoAndTriggerEvent(modifiedBuildVo);
                break;
            case BUILD_DELETE:
                BuildVo deletedBuildVo = (BuildVo) event.getData();
                buildService.deleteBuildVoAndTriggerClientEvent(deletedBuildVo);
                break;
            default:
                // ignore
                break;
        }
    }
}

3、代码实现改进

前面通过规范代码的包结构、加了一些trick使得我们可以方便的使用eventbus解耦我们的业务逻辑,但是有时候我们需要的bean被注册 的前后做一些业务逻辑,所以我们在bean 被注册到eventbus前后加了两个hook:AfterRegisterProcessor、BeforeRegisterProcessor;实现这两个interface并且实现对于的方法,会在bean 被注册前后被调用

bean 注册到eventbus前的hook

BeforeRegisterProcessor
public interface BeforeRegisterProcessor {
    void beforeRegister();
}

bean 注册到eventbus后的hook

AfterRegisterProcessor
public interface AfterRegisterProcessor {
    void afterRegister();
}

实现:保证在 client.watch 之前,注册已经完成,这样watch产生的消息就能够保证被成功消费

GlueService
@Service
public class GlueService implements AfterRegisterProcessor {
    @Autowired
    private PodListener podListener;
 
    @Autowired
    private RouteListener routerListener;
 
    @Autowired
    private BuildListener buildListener;
 
    @Autowired
    private DeploymentListener deploymentListener;
 
    @Autowired
    private OpenShiftClient openShiftClient;
 
    @Override
    public void afterRegister() {
        IClient client = openShiftClient.getClient();
        podWatch = client.watch(podListener, ResourceKind.POD);
        routeWatch = client.watch(routerListener, ResourceKind.ROUTE);
        buildWatch = client.watch(buildListener, ResourceKind.BUILD);
        deploymentWatch = client.watch(deploymentListener, ResourceKind.REPLICATION_CONTROLLER);
    }
}

Guava EventBus集成spring的更多相关文章

  1. guava cache与spring集成

    缓存的背景 缓存,在我们日常开发中是必不可少的一种解决性能问题的方法.简单的说,cache 就是为了提升系统性能而开辟的一块内存空间.在cpu进行计算的时候, 首先是读取寄存器,然后内存,再是硬盘.由 ...

  2. EventBus VS Spring Event

    EventBus VS Spring Event 本地异步处理,采用事件机制 可以使 代码解耦,更易读.事件机制实现模式是 观察者模式(或发布订阅模式),主要分为三部分:发布者.监听者.事件. Gua ...

  3. MyBatis6:MyBatis集成Spring事物管理(下篇)

    前言 前一篇文章<MyBatis5:MyBatis集成Spring事物管理(上篇)>复习了MyBatis的基本使用以及使用Spring管理MyBatis的事物的做法,本文的目的是在这个的基 ...

  4. Guava - EventBus(事件总线)

    Guava在guava-libraries中为我们提供了事件总线EventBus库,它是事件发布订阅模式的实现,让我们能在领域驱动设计(DDD)中以事件的弱引用本质对我们的模块和领域边界很好的解耦设计 ...

  5. CXF集成Spring实现webservice的发布与请求

    CXF集成Spring实现webservice的发布(服务端) 目录结构: 主要代码: package com.cxf.spring.pojo; public class User { int id ...

  6. Dubbo集成Spring与Zookeeper实例

    >>Dubbo最佳实践 使用Dubbo结合Zookeeper和Spring,是使用比较广泛的一种组合,下面参考官方文档,做个简单的示例,一步步搭建一个使用dubbo结合Zookeeper和 ...

  7. Thymeleaf 集成spring

    Thymeleaf 集成spring 如需先了解Thymeleaf的单独使用,请参考<Thymeleaf模板引擎使用>一文. 依赖的jar包 Thymeleaf 已经集成了spring的3 ...

  8. 06_在web项目中集成Spring

    在web项目中集成Spring 一.使用Servlet进行集成测试 1.直接在Servlet 加载Spring 配置文件 ApplicationContext applicationContext = ...

  9. Hibernate 检索查询的几种方式(HQL,QBC,本地SQL,集成Spring等)

    1.非集成Spring hibernate的检索方式,主要有以下五种. 1.导航对象图检索方式.(根据已经加载的对象,导航到其他对象.) 2.OID检索方式.(按照对象的OID来检索对象.) 3.HQ ...

随机推荐

  1. SPOJ_QTREE系列题解

    QTREE4 #pragma comment(linker, "/STACK:102400000,102400000") //#include<bits/stdc++.h&g ...

  2. Idea JAVA項目的导入JAR包和导出jar包

    一.IDea项目中导入jar包 打开菜单project structure,然后选择modules/dependencies下选择右侧的+,选择jar包目录中的jar文件,导入 二.导出jar包 菜单 ...

  3. 数据库SQL调优的几种方式(转)

    原文地址:https://blog.csdn.net/u010520146/article/details/81161762 在项目中,SQL的调优对项目的性能来讲至关重要,所有掌握常见的SQL调优方 ...

  4. vue 项目配置 element 出错

    解决方法: 把main.js文件中的 import 'element-ui/lib/theme-default/index.css' 改为 import 'element-ui/lib/theme-c ...

  5. ORA-06550/PLS-00103

    原因是单引号‘是需要加转义字符的(即‘—>“)

  6. FPGA前仿真后仿真

    前仿真 后仿真 时序(综合后)仿真 时序仿真将时延考虑进去,包括综合后产生的(与.或.非)门时延,还有布局布线产生的时延. 综合(Synthesize),就是将HDL语言设计输入翻译成由与.或.非门和 ...

  7. cesium默认全屏按钮自定义

    cesium默认全屏按钮自定义 1  隐藏默认的svg 2  修改它默认的按钮边框,背景 3   修改它点击时的样式 代码如下: .cesium-viewer-fullscreenContainer ...

  8. Django 自定义模型管理器(Manager)及方法

    转载自:https://www.cnblogs.com/sui776265233/p/11571418.html 1.自定义管理器(Manager) 在语句Book.objects.all()中,ob ...

  9. LNMP一键安装包+Thinkphp搭建基于pathinfo模式的路由

    LNMP一键安装包是一个用Linux Shell编写的可以为CentOS/RadHat/Fedora.Debian/Ubuntu/Raspbian/Deepin VPS或独立主机安装LNMP(Ngin ...

  10. Java面试宝典(2)Java基础部分

    31.String s = "Hello";s = s + " world!";这两行代码执行后,原始的String对象中的内容到底变了没有? 没有.因为Str ...