gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 08:58:24 27 4
gpt4 key购买 nike

我有以下(轴突)聚合:

@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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com