Disruptor+Spring的Event解耦业务

迷南。 2022-10-03 00:59 358阅读 0赞
  1. Disruptor: 开源的并发框架,能够在无锁的情况下实现网络的Queue并发操作,其他更多详情介绍
  2. 本common包封装的DisruptorSpring的Event事件组合,实现业务在JVM内解耦。

  3. 引入disruptor pom依赖:

  1. <disruptor.version>3.4.2</disruptor.version>
  2. <!-- disruptor -->
  3. <dependency>
  4. <groupId>com.lmax</groupId>
  5. <artifactId>disruptor</artifactId>
  6. <version>${disruptor.version}</version>
  7. </dependency>
  1. 启动disruptor:
  1. // spring容器初始化时,启动disruptor
  2. @Component
  3. public class ConfigInit implements InitializingBean
  4. {
  5. @Autowired
  6. private DisruptorProducer disruptorProducer;
  7. @Override
  8. public void afterPropertiesSet()
  9. {
  10. disruptorProducer.doStart();
  11. }
  12. }
  1. 生产者调用:

    DisruptorProducer.send(BasisData data)方法

  1. // 数据数据定义
  2. public ServiceData extends BasisData{
  3. // field
  4. // setter and getter
  5. }
  6. // 注入DisruptorProducer
  7. @Autowired
  8. private DisruptorProducer disruptorProducer;
  9. @Test
  10. public void testSend(){
  11. ServiceData data = new ServiceData();
  12. // 设置事件类型,可预定义在EventEnum枚举类中,一个String类型
  13. data.setEvent(EventEnum.LOG_EVENT.getEvent());
  14. // 发送数据
  15. disruptorProducer.send(data);
  16. }
  1. 业务消费者:

    实现org.springframework.context.ApplicationListener<ServiceEvent>onApplicationEvent(ServiceEvent serviceEvent)方法

  1. // event消费者实现
  2. @Component
  3. public class LogEventEvent implements ApplicationListener<ServiceEvent>{
  4. // 可以使用spring的异步实现@Async注解,需要配合启动类中添加 @EnableAsync注解 开启异步的支持
  5. @Async
  6. @Override
  7. public void onApplicationEvent(ServiceEvent event)
  8. {
  9. // 这个event事件名称要跟发送的时候事件名称一样的
  10. if (EventEnum.LOG_EVENT.getEvent().equals(event.getEvent()))
  11. {
  12. ServiceData serviceData = (ServiceData) event.getSource();
  13. // 进一步业务逻辑处理 todo
  14. }
  15. }
  16. }

严重警告:ringBufferSize的值设定需要保持理性的数量,环形队列是等着被替换而不是被回收,设置太大会撑爆你设定的JVM内存,最终导致OLD占满,接下来就是无限循环的FGC
源代码:gitHub地址

发表评论

表情:
评论列表 (有 0 条评论,358人围观)

还没有评论,来说两句吧...

相关阅读

    相关 订单业务

    如何解耦(按照什么标准解耦)? eg: 有一支付成功的订单,已经发货,用户取消订单? 这个场景从业务设计上讲如何解耦? 可能涉及的业务:订单业务、物流业务、支付业务(暂时只