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. react — script引入 和 脚手架使用的区别

    1.React 入门实例教程 :http://www.ruanyifeng.com/blog/2015/03/react.html ( 阮一峰的博客)  或   https://segmentfaul ...

  2. ListView 分页显示(转载+修改)上

    实习工作中,分配到了一个给已经上线的android成品增加需求的任务,其中一项是给每个信息显示增加分页显示的功能(ListView的显示),于是上网查资料,看到了: 原地址:http://www.cn ...

  3. Kubernetes 技能图谱skill-map

    # Kubernetes 技能图谱 ## Container basics (容器技术基础)* Kernel* Cgroups* Userspace runtime* Image* Registry ...

  4. js实现复选框全选/全不选/反选

    js实现复选框全选/全不选/反选 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "h ...

  5. linux与Windows下的heap

    Windows提供Heap相关的API,可以创建多个Heap. 但是Linux下只有一个意义上的Heap,就是Data Segment,由brk/sbrk系统调用来调整其大小. 参考:http://m ...

  6. [POI2010]OWC-Sheep

    题目 不难猜到或者发现的性质,如果连了一条对角线划分出了奇数个点,那么这条对角线肯定不合法:因为划分成三角形就不可能有对角线相交,于是划分成奇数的那一边怎么样也不可能划分成全是偶数 于是我们需要对每一 ...

  7. 嵌套循环结合修改IFS环境变量遍历文件数据中IFS的修改一致性

    以下这个脚本使用了两个不同的IFS值来解析数据.第一个IFS值解析出/etc/passwd文件中的单独的行.内部for循环接着将IFS值改为冒号,云溪你从/etc/passwd的行中解析出单独的值. ...

  8. linux 下新建文件自动加锁的解决办法

    导致文件夹里面无法保存别的文件 sudo chmod 777 -R 文件或目录

  9. LeetCode Array Easy 167. Two Sum II - Input array is sorted

    Description Given an array of integers that is already sorted in ascending order, find two numbers s ...

  10. stat - 打印信息节点(inode)内容

    SYNOPSIS(总览) stat filename [filenames ... ] DESCRIPTION(描述) stat 打印出一个信息节点的内容,它们显示为对人可读的格式的stat(2). ...