问题描述
我有一个相当简单的域模型,其中包含一个 Facility
聚合根列表.鉴于我使用 CQRS 和事件总线来处理从域引发的事件,您如何处理集的验证?例如,假设我有以下要求:
I have a fairly simple domain model involving a list of Facility
aggregate roots. Given that I'm using CQRS and an event-bus to handle events raised from the domain, how could you handle validation on sets? For example, say I have the following requirement:
设施
的名称必须是唯一的.
Facility
's must have a unique name.
由于我在查询端使用最终一致的数据库,因此无法保证其中的数据在事件处理器或处理事件时准确无误.
Since I'm using an eventually consistent database on the query side, the data in it is not guaranteed to be accurate at the time the event processesor processes the event.
例如,FacilityCreatedEvent
在查询数据库事件处理队列中等待处理并写入数据库.一个新的 CreateFacilityCommand
被发送到要处理的域.域服务查询读取的数据库以查看是否有任何其他 Facility
已使用该名称注册,但返回 false,因为 CreateNewFacilityEvent
尚未处理和写入到商店.新的 CreateFacilityCommand
现在将成功并抛出另一个 FacilityCreatedEvent
,当事件处理器尝试将其写入数据库并发现另一个 Facility
时,它会爆炸code> 已存在该名称.
For example, a FacilityCreatedEvent
is in the query database event processing queue waiting to be processed and written into the database. A new CreateFacilityCommand
is sent to the domain to be processed. The domain services query the read database to see if there are any other Facility
's registered already with that name, but returns false because the CreateNewFacilityEvent
has not yet been processed and written to the store. The new CreateFacilityCommand
will now succeed and throw up another FacilityCreatedEvent
which would blow up when the event processor tries to write it into the database and finds that another Facility
already exists with that name.
推荐答案
我采用的解决方案是添加一个 System
聚合根,它可以维护当前 Facility名称.创建新的
Facility
时,我使用 System
聚合(只有一个 System
作为全局对象/单例)作为它的工厂.如果给定的设施名称已经存在,则会抛出验证错误.
The solution I went with was to add a
System
aggregate root that could maintain a list of the current Facility
names. When creating a new Facility
, I use the System
aggregate (only one System
as a global object / singleton) as a factory for it. If the given facility name already exists, then it will throw a validation error.
这将验证约束保留在域内,并且不依赖于最终一致的查询存储.
This keeps the validation constraints within the domain and does not rely on the eventually consistent query store.
这篇关于如何在 CQRS 中处理基于集合的一致性验证?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!