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