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. [jzoj5840]Miner 题解(欧拉路)

    首先考虑第一问.每个联通块的情况是相对独立的,所以可以分别求每个联通块的答案.无向图中存在欧拉路的条件是奇点数为0或2,那么合法方案肯定是tp到一个奇点,通过一条欧拉路到另一个奇点,再tp到另一个奇点 ...

  2. 向上转型---父类引用指向子类对象 A a = New B()的使用

    一.向上转型 向上转型是JAVA中的一种调用方式,是多态的一种表现.向上转型并非是将B自动向上转型为A的对象,相反它是从另一种角度去理解向上两字的:它是对A的对象的方法的扩充,即A的对象可访问B从A中 ...

  3. Oracle中使用REGEXP_SUBSTR,regexp_replace,wm_concat函数

    REGEXP_SUBSTR函数格式如下: function REGEXP_SUBSTR(String, pattern, position, occurrence, modifier)__srcstr ...

  4. Apache 2.4.12 64位+Tomcat-8.0.32-windows-x64负载集群方案

    上次搞了Apache 2.2的集群方案,但是现在自己的机器和客户的服务器一般都是64位的,而且tomcat已经到8了.重新做Apache 2.4.12 64位+Tomcat-8.0.32-window ...

  5. Eclipse快捷键 之 代码追踪

    在使用Java编写复杂一些的程序时,你会不会常常对一层层的继承关系和一次次方法的调用感到迷惘呢?幸亏我们有了Eclipse这么好的IDE可以帮我们理清头绪--这就要使用Eclipse强大的代码追踪功能 ...

  6. springMvc注册时图形验证码完整代码与详细步骤``````后续更新注册时对密码进行加密

      第一使用 画图软件制作图片 ,文件名就是验证码    ------用户的实体类 import java.util.Date; public class Member {    private in ...

  7. 实用maven笔记四-打包&其他

    通过使用maven的生命周期和丰富多样的插件,可以方便的将项目代码编译打包为自己需要的构件. maven默认项目主代码位置src/main/java目录,测试代码位置src/test/java目录.主 ...

  8. 一张图搞清楚Java异常机制

    下面是Java异常类的组织结构,红色区域的异常类表示是程序需要显示捕捉或者抛出的. Throwable Throwable是Java异常的顶级类,所有的异常都继承于这个类. Error,Excepti ...

  9. Emacs 25.1 error solved: url-http-create-request: Multibyte text in HTTP request

    Emacs 25.1 error solved: url-http-create-request: Multibyte text in HTTP request */--> code {colo ...

  10. python学习之路,2018.8.9

    python学习之路,2018.8.9, 学习是一个长期坚持的过程,加油吧,少年!