Disruptor+Spring的Event解耦業務

  1. Disruptor: 開源的併發框架,能夠在無鎖的情況下實現網絡的Queue併發操作,其他更多詳情介紹
  2. 本common包封裝的DisruptorSpring的Event事件組合,實現業務在JVM內解耦。
  3. 引入disruptor pom依賴:
       <disruptor.version>3.4.2</disruptor.version>
       <!-- disruptor -->
        <dependency>
            <groupId>com.lmax</groupId>
            <artifactId>disruptor</artifactId>
            <version>${disruptor.version}</version>
        </dependency>
    
  4. 啓動disruptor:
    // spring容器初始化時,啓動disruptor
    @Component
    public class ConfigInit implements InitializingBean
    {
        @Autowired
        private DisruptorProducer disruptorProducer;
    
        @Override
        public void afterPropertiesSet()
        {
            disruptorProducer.doStart();
        }
    }
    
  5. 生產者調用:

    DisruptorProducer.send(BasisData data)方法
     // 數據數據定義
     public ServiceData extends BasisData{
        // field
        // setter and getter
     }
     
     // 注入DisruptorProducer
     @Autowired
     private DisruptorProducer disruptorProducer;
     
     @Test
     public void testSend(){
          ServiceData data = new ServiceData();
          // 設置事件類型,可預定義在EventEnum枚舉類中,一個String類型
          data.setEvent(EventEnum.LOG_EVENT.getEvent());
          // 發送數據
          disruptorProducer.send(data);
     }
    
    
  6. 業務消費者:

    實現org.springframework.context.ApplicationListener<ServiceEvent>onApplicationEvent(ServiceEvent serviceEvent)方法
     // event消費者實現
     @Component
     public class LogEventEvent implements ApplicationListener<ServiceEvent>{
         
         // 可以使用spring的異步實現@Async註解,需要配合啓動類中添加 @EnableAsync註解 開啓異步的支持
         @Async
         @Override
         public void onApplicationEvent(ServiceEvent event)
         {
             // 這個event事件名稱要跟發送的時候事件名稱一樣的
             if (EventEnum.LOG_EVENT.getEvent().equals(event.getEvent()))
             {
                 ServiceData serviceData = (ServiceData) event.getSource();
                 // 進一步業務邏輯處理 todo
             }
         }
     }
    

源代碼:gitHub地址

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章