diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index aabc353..10132b1 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -3,14 +3,35 @@ name: CI on: workflow_dispatch: push: - branches: [2.3.x, 2.7.x, 3.0.x, 3.1.x, 3.2.x, 3.3.x, 3.4.x, 3.5.x, 4.0.x, 4.1.x] + branches: ['test/*', 2.3.x, 2.7.x, 3.0.x, 3.1.x, 3.2.x, 3.3.x, 3.4.x, 3.5.x, 4.0.x, 4.1.x] pull_request: - branches: [2.3.x, 2.7.x, 3.0.x, 3.1.x, 3.2.x, 3.3.x, 3.4.x, 3.5.x, 4.0.x, 4.1.x] + branches: ['test/*', 2.3.x, 2.7.x, 3.0.x, 3.1.x, 3.2.x, 3.3.x, 3.4.x, 3.5.x, 4.0.x, 4.1.x] permissions: contents: read jobs: - build: + build-boot-2: + if: github.base_ref == '2.7.x' || startsWith(github.base_ref, 'test/') || github.ref_name == '2.7.x' || startsWith(github.ref_name, 'test/') + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: '8' + cache: maven + - uses: actions/checkout@v4 + with: + repository: easy-4-java/disruptor-extension + ref: e9f81a75c8b4c8316dde4e4f852a092bffe59179 + path: disruptor-extension-source + - name: Build matching extension snapshot + working-directory: disruptor-extension-source + run: mvn -B clean install + - name: Verify starter + run: mvn -B clean verify + build-other: + if: github.base_ref != '2.7.x' && !startsWith(github.base_ref, 'test/') && github.ref_name != '2.7.x' && !startsWith(github.ref_name, 'test/') uses: easy-4-java/.github/.github/workflows/maven-starter-ci.yml@main secrets: inherit diff --git a/README.zh-CN.md b/README.zh-CN.md index f40bde5..1ddcaf9 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -94,6 +94,8 @@ Starter 自动装配以下 Bean: ## 6. 快速开始 +需要按事件路由到单个责任链处理器时,参见 [2.7.x 一对一匹配示例](docs/handler-chain.md)。 + ### 6.1 引入依赖 在 `pom.xml` 中添加上述依赖。 diff --git a/docs/handler-chain.md b/docs/handler-chain.md new file mode 100644 index 0000000..6f24f52 --- /dev/null +++ b/docs/handler-chain.md @@ -0,0 +1,29 @@ +# Disruptor 责任链的一对一匹配(2.7.x) + +`DisruptorEvent` 使用 `namespace/topic/tag` 生成路由;`namespace` 为空时,路由以 `/topic/tag` 开头。每条路由可以只指定一个 Spring Bean 名称,因此一个事件只进入对应的处理器。配置前缀是 `spring.disruptor`。 + +```yaml +spring: + disruptor: + enabled: true + handler-definitions: + - order: 0 + definition-map: + /orders/created: createdHandler + /orders/cancelled: cancelledHandler +``` + +```java +@Component("createdHandler") +@EventRule("/orders/created") +public class CreatedHandler implements DisruptorHandler { + @Override + public void doHandler(DisruptorEvent event, HandlerChain chain) { + // 处理订单创建事件 + } +} +``` + +发布事件时,设置 `topic=orders`、`tag=created`,其路由即 `/orders/created`。`cancelledHandler` 不会处理该事件。两个处理器的定义与上例相同,只需替换 Bean 名称、`@EventRule` 路由和业务逻辑。若设置了 `namespace`,路由规则也必须包含对应的命名空间前缀。 + +`DisruptorComponentTests.oneToOneRouteCallsOnlyItsConfiguredHandler` 使用真实分发器验证两条路由分别只调用各自的处理器。多个处理器串联时,`definition-map` 的值用逗号分隔 Bean 名称,例如 `createdHandler,auditHandler`,并由处理器按责任链协议继续调用 `chain.doHandler(event)`。 diff --git a/pom.xml b/pom.xml index 0bab8f8..4b7b7cf 100644 --- a/pom.xml +++ b/pom.xml @@ -178,7 +178,8 @@ **/*Test.java - **/*_Test.java + **/*_Test.java + **/*Tests.java **/TestBean.java diff --git a/src/main/java/com/lmax/disruptor/spring/boot/DisruptorAutoConfiguration.java b/src/main/java/com/lmax/disruptor/spring/boot/DisruptorAutoConfiguration.java index 43168d4..62ae23e 100644 --- a/src/main/java/com/lmax/disruptor/spring/boot/DisruptorAutoConfiguration.java +++ b/src/main/java/com/lmax/disruptor/spring/boot/DisruptorAutoConfiguration.java @@ -2,6 +2,7 @@ import java.util.ArrayList; import java.util.Collections; +import java.util.Comparator; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; @@ -23,9 +24,9 @@ import org.springframework.context.ApplicationListener; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import org.springframework.core.OrderComparator; import org.springframework.util.CollectionUtils; import org.springframework.util.ObjectUtils; +import org.springframework.util.StringUtils; import com.lmax.disruptor.EventFactory; import com.lmax.disruptor.EventTranslatorOneArg; @@ -53,7 +54,6 @@ import com.lmax.disruptor.event.translator.DisruptorEventThreeArgTranslator; import com.lmax.disruptor.event.translator.DisruptorEventTwoArgTranslator; import com.lmax.disruptor.hooks.DisruptorShutdownHook; -import com.lmax.disruptor.util.StringUtils; import com.lmax.disruptor.util.WaitStrategys; import com.lmax.disruptor.DisruptorTemplate; @@ -160,7 +160,7 @@ public List disruptorEventHandlers(DisruptorProperties } } // 进行排序 - Collections.sort(disruptorEventHandlers, new OrderComparator()); + disruptorEventHandlers.sort(Comparator.comparingInt(DisruptorEventDispatcher::getOrder)); return disruptorEventHandlers; } @@ -171,7 +171,7 @@ public List disruptorEventHandlers(DisruptorProperties protected DisruptorEventDispatcher createDisruptorEventHandler(EventHandlerDefinition handlerDefinition, Map> eventHandlers) { - if (StringUtils.isNotEmpty(handlerDefinition.getDefinitions())) { + if (StringUtils.hasLength(handlerDefinition.getDefinitions())) { handlerChainDefinitionMap.putAll(this.parseHandlerChainDefinitions(handlerDefinition.getDefinitions())); } else if (!CollectionUtils.isEmpty(handlerDefinition.getDefinitionMap())) { handlerChainDefinitionMap.putAll(handlerDefinition.getDefinitionMap()); @@ -264,7 +264,7 @@ public Disruptor disruptor( if (!ObjectUtils.isEmpty(disruptorEventHandlers)) { // 进行排序 - Collections.sort(disruptorEventHandlers, new OrderComparator()); + disruptorEventHandlers.sort(Comparator.comparingInt(DisruptorEventDispatcher::getOrder)); // 使用disruptor创建消费者组 EventHandlerGroup handlerGroup = null; diff --git a/src/main/java/com/lmax/disruptor/spring/boot/context/DisruptorEventAwareProcessor.java b/src/main/java/com/lmax/disruptor/spring/boot/context/DisruptorEventAwareProcessor.java index 07c6fc5..e90a9b5 100644 --- a/src/main/java/com/lmax/disruptor/spring/boot/context/DisruptorEventAwareProcessor.java +++ b/src/main/java/com/lmax/disruptor/spring/boot/context/DisruptorEventAwareProcessor.java @@ -20,7 +20,6 @@ import java.security.PrivilegedAction; import org.springframework.beans.BeansException; -import org.springframework.beans.factory.Aware; import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.config.BeanPostProcessor; import org.springframework.beans.factory.config.ConfigurableBeanFactory; @@ -95,12 +94,9 @@ public Object run() { } protected void invokeAwareInterfaces(Object bean) { - if (bean instanceof Aware) { - //扩展 DisruptorEventPublisherAware - if (bean instanceof DisruptorEventPublisherAware) { - DisruptorEventPublisherAware awareBean = (DisruptorEventPublisherAware) bean; - awareBean.setDisruptorEventPublisher( this.disruptorContext ); - } + if (bean instanceof DisruptorEventPublisherAware) { + DisruptorEventPublisherAware awareBean = (DisruptorEventPublisherAware) bean; + awareBean.setDisruptorEventPublisher(this.disruptorContext); } } diff --git a/src/test/java/com/lmax/disruptor/spring/boot/DisruptorComponentTests.java b/src/test/java/com/lmax/disruptor/spring/boot/DisruptorComponentTests.java new file mode 100644 index 0000000..43ef6ad --- /dev/null +++ b/src/test/java/com/lmax/disruptor/spring/boot/DisruptorComponentTests.java @@ -0,0 +1,265 @@ +package com.lmax.disruptor.spring.boot; + +import com.lmax.disruptor.RingBuffer; +import com.lmax.disruptor.annotation.EventRule; +import com.lmax.disruptor.config.EventHandlerDefinition; +import com.lmax.disruptor.event.DisruptorEvent; +import com.lmax.disruptor.event.DisruptorEventPublisher; +import com.lmax.disruptor.event.DisruptorEventPublisherAware; +import com.lmax.disruptor.spring.boot.context.DisruptorApplicationContext; +import com.lmax.disruptor.spring.boot.context.DisruptorEventAwareProcessor; +import com.lmax.disruptor.spring.boot.context.event.EventPublicationInterceptor; +import com.lmax.disruptor.spring.boot.event.DisruptorApplicationEvent; +import com.lmax.disruptor.event.handler.DisruptorEventDispatcher; +import com.lmax.disruptor.event.handler.DisruptorHandler; +import com.lmax.disruptor.event.handler.Nameable; +import com.lmax.disruptor.event.handler.chain.HandlerChain; +import com.lmax.disruptor.event.handler.chain.HandlerChainManager; +import com.lmax.disruptor.dsl.Disruptor; +import org.aopalliance.intercept.MethodInvocation; +import org.junit.jupiter.api.Test; +import org.springframework.context.ApplicationContext; + +import java.util.concurrent.atomic.AtomicReference; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +class DisruptorComponentTests { + + @Test + void applicationContextPublishesEventWithOriginalSource() { + ApplicationContext springContext = mock(ApplicationContext.class); + AtomicReference published = new AtomicReference<>(); + doAnswer(invocation -> { + published.set(invocation.getArgument(0)); + return null; + }).when(springContext).publishEvent(any(DisruptorApplicationEvent.class)); + + DisruptorApplicationContext context = new DisruptorApplicationContext(); + context.setApplicationContext(springContext); + DisruptorEvent event = new DisruptorEvent("source"); + context.publishEvent(event); + + assertSame(springContext, context.getApplicationContext()); + assertSame(event, published.get().getSource()); + published.get().bind("payload"); + assertEquals("payload", published.get().getBind()); + assertEquals("other", new DisruptorApplicationEvent(event, "other").getBind()); + } + + @Test + void awareProcessorInjectsPublisherAndPreservesBean() throws Exception { + ApplicationContext springContext = mock(ApplicationContext.class); + DisruptorEventAwareProcessor processor = new DisruptorEventAwareProcessor(); + processor.setApplicationContext(springContext); + processor.afterPropertiesSet(); + PublisherAwareBean bean = new PublisherAwareBean(); + + assertSame(bean, processor.postProcessBeforeInitialization(bean, "bean")); + assertSame(bean, processor.postProcessAfterInitialization(bean, "bean")); + assertNotNull(bean.publisher); + DisruptorEvent event = new DisruptorEvent("source"); + bean.publisher.publishEvent(event); + verify(springContext).publishEvent(any(DisruptorApplicationEvent.class)); + } + + @Test + void interceptorPublishesAfterSuccessfulInvocation() throws Throwable { + EventPublicationInterceptor interceptor = new EventPublicationInterceptor(); + assertThrows(IllegalArgumentException.class, interceptor::afterPropertiesSet); + assertThrows(IllegalArgumentException.class, + () -> interceptor.setApplicationEventClass(DisruptorEvent.class)); + assertThrows(IllegalArgumentException.class, + () -> interceptor.setApplicationEventClass(String.class)); + assertThrows(IllegalArgumentException.class, + () -> interceptor.setApplicationEventClass(NoObjectConstructorEvent.class)); + + interceptor.setApplicationEventClass(PublishedEvent.class); + interceptor.afterPropertiesSet(); + DisruptorEventPublisher publisher = mock(DisruptorEventPublisher.class); + interceptor.setDisruptorEventPublisher(publisher); + MethodInvocation invocation = mock(MethodInvocation.class); + Object target = new Object(); + when(invocation.getThis()).thenReturn(target); + when(invocation.proceed()).thenReturn("result"); + + assertEquals("result", interceptor.invoke(invocation)); + verify(publisher).publishEvent(any(PublishedEvent.class)); + } + + @Test + void ringBufferCreatesBothProducerModes() { + RingBufferAutoConfiguration configuration = new RingBufferAutoConfiguration(); + ApplicationContext springContext = mock(ApplicationContext.class); + configuration.setApplicationContext(springContext); + assertSame(springContext, configuration.getApplicationContext()); + assertNotNull(configuration.waitStrategy()); + assertNotNull(configuration.eventFactory()); + + DisruptorProperties properties = new DisruptorProperties(); + properties.setRingBufferSize(8); + properties.setRingThreadNumbers(1); + properties.setMultiProducer(false); + RingBuffer single = configuration.ringBuffer(properties, + configuration.waitStrategy(), configuration.eventFactory(), null, null); + assertEquals(8, single.getBufferSize()); + + properties.setMultiProducer(true); + RingBuffer multi = configuration.ringBuffer(properties, + configuration.waitStrategy(), configuration.eventFactory(), null, null); + assertEquals(8, multi.getBufferSize()); + } + + @Test + void autoConfigurationRegistersNamedHandlersAndChains() { + ApplicationContext springContext = mock(ApplicationContext.class); + DisruptorAutoConfiguration configuration = new DisruptorAutoConfiguration(); + configuration.setApplicationContext(springContext); + assertSame(springContext, configuration.getApplicationContext()); + + Map beans = new HashMap<>(); + NamedHandler namedHandler = new NamedHandler(); + beans.put("named", namedHandler); + beans.put("unnamed", new NamedHandler()); + beans.put("dispatcher", mock(DisruptorEventDispatcher.class)); + when(springContext.getBeansOfType(DisruptorHandler.class)).thenReturn(beans); + when(springContext.findAnnotationOnBean("named", EventRule.class)) + .thenReturn(NamedHandler.class.getAnnotation(EventRule.class)); + Map> handlers = configuration.disruptorHandlers(); + assertEquals(2, handlers.size()); + assertEquals("named", configuration.parseHandlerChainDefinitions("/** = named").get("/**")); + + DisruptorProperties properties = new DisruptorProperties(); + EventHandlerDefinition fromText = new EventHandlerDefinition(); + fromText.setOrder(2); + fromText.setDefinitions("[urls]\n/** = named"); + EventHandlerDefinition fromMap = new EventHandlerDefinition(); + fromMap.setOrder(1); + fromMap.setDefinitionMap(Collections.singletonMap("/events/**", "named")); + properties.setHandlerDefinitions(java.util.Arrays.asList(fromText, fromMap)); + List dispatchers = configuration.disruptorEventHandlers(properties, handlers); + assertEquals(2, dispatchers.size()); + assertEquals(1, dispatchers.get(0).getOrder()); + assertEquals(2, dispatchers.get(1).getOrder()); + + HandlerChainManager manager = configuration.createHandlerChainManager( + handlers, Collections.singletonMap("/**", "named")); + assertTrue(manager.hasChains()); + assertNotNull(manager.getChain("/**")); + assertEquals("named", namedHandler.name); + } + + @Test + void autoConfigurationStartsSingleProducerAndPublishesApplicationEvent() { + DisruptorAutoConfiguration configuration = new DisruptorAutoConfiguration(); + DisruptorProperties properties = new DisruptorProperties(); + properties.setRingBufferSize(8); + properties.setMultiProducer(false); + properties.setEnabled(true); + properties.setRingBuffer(true); + assertTrue(properties.isEnabled()); + assertTrue(properties.isRingBuffer()); + assertNotNull(configuration.waitStrategy()); + assertNotNull(configuration.threadFactory()); + assertNotNull(configuration.eventFactory()); + assertNotNull(configuration.oneArgEventTranslator()); + assertNotNull(configuration.twoArgEventTranslator()); + assertNotNull(configuration.threeArgEventTranslator()); + assertNotNull(configuration.disruptorEventAwareProcessor()); + + Disruptor disruptor = configuration.disruptor(properties, + configuration.waitStrategy(), configuration.threadFactory(), configuration.eventFactory(), + Collections.emptyList()); + try { + assertNotNull(configuration.disruptorTemplate(disruptor, configuration.oneArgEventTranslator())); + DisruptorEvent event = new DisruptorEvent("source"); + configuration.disruptorEventListener(disruptor, configuration.oneArgEventTranslator()) + .onApplicationEvent(new DisruptorApplicationEvent(event)); + assertEquals(0, disruptor.getRingBuffer().getCursor()); + } finally { + disruptor.shutdown(); + } + } + + @Test + void oneToOneRouteCallsOnlyItsConfiguredHandler() throws Exception { + DisruptorAutoConfiguration configuration = new DisruptorAutoConfiguration(); + AtomicInteger createdCalls = new AtomicInteger(); + AtomicInteger cancelledCalls = new AtomicInteger(); + Map> handlers = new HashMap<>(); + handlers.put("createdHandler", (event, chain) -> createdCalls.incrementAndGet()); + handlers.put("cancelledHandler", (event, chain) -> cancelledCalls.incrementAndGet()); + + EventHandlerDefinition definition = new EventHandlerDefinition(); + Map routes = new java.util.LinkedHashMap<>(); + routes.put("/orders/created", "createdHandler"); + routes.put("/orders/cancelled", "cancelledHandler"); + definition.setDefinitionMap(routes); + DisruptorProperties properties = new DisruptorProperties(); + properties.setHandlerDefinitions(Collections.singletonList(definition)); + DisruptorEventDispatcher dispatcher = configuration.disruptorEventHandlers(properties, handlers).get(0); + + DisruptorEvent created = new DisruptorEvent("source"); + created.setTopic("orders"); + created.setTag("created"); + dispatcher.onEvent(created, 0, true); + assertEquals(1, createdCalls.get()); + assertEquals(0, cancelledCalls.get()); + + DisruptorEvent cancelled = new DisruptorEvent("source"); + cancelled.setTopic("orders"); + cancelled.setTag("cancelled"); + dispatcher.onEvent(cancelled, 1, true); + assertEquals(1, createdCalls.get()); + assertEquals(1, cancelledCalls.get()); + } + + static class PublisherAwareBean implements DisruptorEventPublisherAware { + private DisruptorEventPublisher publisher; + + @Override + public void setDisruptorEventPublisher(DisruptorEventPublisher publisher) { + this.publisher = publisher; + } + } + + public static class PublishedEvent extends DisruptorEvent { + public PublishedEvent(Object source) { + super(source); + } + } + + public static class NoObjectConstructorEvent extends DisruptorEvent { + public NoObjectConstructorEvent() { + super(); + } + } + + @EventRule("/**") + static class NamedHandler implements DisruptorHandler, Nameable { + private String name; + + @Override + public void setName(String name) { + this.name = name; + } + + @Override + public void doHandler(DisruptorEvent event, HandlerChain chain) { + } + } +} diff --git a/src/test/java/org/apache/rocketmq/spring/boot/DemoApplicationTests.java b/src/test/java/org/apache/rocketmq/spring/boot/DemoApplicationTests.java index 7d81927..e996198 100644 --- a/src/test/java/org/apache/rocketmq/spring/boot/DemoApplicationTests.java +++ b/src/test/java/org/apache/rocketmq/spring/boot/DemoApplicationTests.java @@ -1,18 +1,41 @@ package org.apache.rocketmq.spring.boot; -import org.junit.Test; -import org.junit.runner.RunWith; +import com.lmax.disruptor.dsl.Disruptor; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.SpringBootConfiguration; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.context.annotation.Configuration; -import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.context.ApplicationContext; +import org.springframework.context.annotation.Bean; -@Configuration -@RunWith(SpringRunner.class) -@SpringBootTest +import java.util.concurrent.Executor; + +import static org.junit.jupiter.api.Assertions.assertNotNull; + +@SpringBootTest(classes = DemoApplicationTests.TestApplication.class, + properties = {"spring.disruptor.enabled=true", "spring.config.name=disruptor-test"}) public class DemoApplicationTests { + @Autowired + private ApplicationContext applicationContext; + @Test public void contextLoads() { + assertNotNull(applicationContext.getBean(Disruptor.class)); } + @SpringBootConfiguration + @EnableAutoConfiguration + static class TestApplication { + @Bean("applicationTaskExecutor") + Executor applicationTaskExecutor() { + return Runnable::run; + } + + @Bean("taskScheduler") + Executor taskScheduler() { + return Runnable::run; + } + } }