java - 防止重复 AggregateCreated 事件的最佳实践

标签 java cqrs axon

我有以下(轴突)聚合:

@Aggregate
@NoArgsConstructor
public class Car{
  @AggregateIdentifier
  private String id;

  @CommandHandler
  public Car(CreateCar command){
    apply( new CarCreated(command.getId()) );
  }

  @EventSourcingHandler
  public void carCreated(CarCreated event) {
    this.id = event.getId();
  }

}

我可以通过提交具有特定 ID 的 CreateCar 命令来创建汽车,从而引发 CarCreated 事件。太棒了。

但是,如果我发送另一个具有相同 ID 的 CreateCar 命令,则聚合无法验证该命令(给定的 ID 已存在)。随后,它将简单地触发一个新的 CarCreated 事件。这是一个谎言。

如果汽车已经存在,确保 CreateCar 命令失败的最佳方法是什么?

当然,我可以先检查存储库,但这不会阻止竞争条件......

最佳答案

However, if I send another CreateCar command, with the same Id, the command cannot be validated by the aggregate (that the given id already exists). Subsequently it will simply fire a new CarCreated event. Which is a lie.

Axon 实际上会为您解决这个问题。当聚合发布事件时,它不会立即发布到其他组件。它在工作单元中暂存,等待处理程序执行完成。 处理程序执行后,将调用许多“准备提交”处理程序。其中之一存储聚合(使用事件源时这是无操作),另一个是事件的发布(在事务范围内)。

根据您是否使用事件溯源,将聚合实例添加到持久存储将会失败(重复键),或者创建事件的发布将会失败(重复聚合标识符 + 序列号)。

关于java - 防止重复 AggregateCreated 事件的最佳实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53187544/

相关文章:

domain-driven-design - 在 DDD 和 CQRS 中,我是否应该将所需的表示逻辑直接放入每个 Read (Finder) 查询中?

java - 如何获得在Axon错误处理程序中产生错误的事件处理程序?

java - 在 doFilter 调用后设置响应 header

java - 如何在ubuntu中将参数传递给tomcat?

java - Java 中的 Application.DoEvents() 等效吗?

java - arraylist 有问题 arrayList<int[]>

domain-driven-design - 每个有界上下文读取模型

java - Command Handler 是否只是从总线接收命令并发布事件?

cqrs - Axon 框架的排序策略如何在状态方面发挥作用

java - Spring Boot 应用程序无法运行 - spring.resources.cache-period 未绑定(bind)