《微服务架构设计》——Eventuate Tram框架订阅/消费模式源码解析
Eventuate Tram框架官方文档: https://eventuate.io/docs/manual/eventuate-tram/latest/getting-started-eventuate-tram.html#getting-started
Eventuate Tram架构在DDD架构时使用了其消费/订阅模式,官网给的样例如下:
领域事件发布代码:
public abstract class AbstractTramEventTest { @Autowired private DomainEventPublisher domainEventPublisher; @Test public void shouldReceiveEvent() throws InterruptedException { long uniqueId = config.getUniqueId(); String accountId = ...; DomainEvent domainEvent = new AccountDebited(...); domainEventPublisher.publish("Account", accountId, Collections.singletonList(domainEvent));
消费领域事件代码:
首先,定义DomainEventHandlers
:
public class TramEventTestEventConsumer { public DomainEventHandlers domainEventHandlers() { return DomainEventHandlersBuilder .forAggregateType("Account") .onEvent(AccountDebited.class, this::handleAccountDebited) .build(); } public void handleAccountDebited(DomainEventEnvelopeevent) { ... } }
导入TramEventSubscriberConfiguration
并配置一个DomainEventDispatcher
:
@Configuration @Import(TramEventSubscriberConfiguration.class) public class AbstractTramEventTestConfiguration { @Bean public DomainEventDispatcher domainEventDispatcher(DomainEventDispatcherFactory domainEventDispatcherFactory, AbstractTramEventTestConfig config, TramEventTestEventConsumer target) { return domainEventDispatcherFactory.make("eventDispatcherId" + config.getUniqueId(),target.domainEventHandlers()); } @Bean public TramEventTestEventConsumer tramEventTestTarget(AbstractTramEventTestConfig config) { return new TramEventTestEventConsumer(); }
官方的案例让我没看明白他们到底通过什么进行订阅消费,于是扒了下源码:
可以下载保存后本地放大观看。
通过源码发现Eventuate Tram是通过领域事件类型和事件Class类来进行订阅消费,参数中的xxxxId只做到标记以保证出错时能打出日志,并不参与订阅消费的流程中,不要想当然的被误导了。