我在读Accounting Pattern,并对在CQRS中实施它非常好奇。如何在CQRS中建立银行转帐模型
我觉得AccountingTransaction是一个聚合根,因为它保护不变:
没有钱泄漏,应该是从一个账户转移到另一个。
public class AccountingTransaction {
private String sequence;
private AccountId from;
private AccountId to;
private MonetaryAmount quantity;
private DateTime whenCharged;
public AccountingTransaction(...) {
raise(new AccountingEntryBookedEvent(sequence, from, quantity.negate(),...);
raise(new AccountingEntryBookedEvent(sequence, to, quantity,...);
}
}
将AccountingTransaction添加到其存储库时。它发布了几个AccountingEntryBookedEvent,用于更新查询端相应帐户的余额。
每个db事务更新一个聚合根,最终一致性,到目前为止非常好。
但是如果某些账户应用转账限制,例如不能将更多的数量转移到当前余额?我可以使用查询端来获取帐户的余额,但是我担心查询端的数据是陈旧的。
public class TransferApplication {
public void transfer(...) {
AccountReadModel from = accountQuery.findBy(fromId);
AccountReadModel to = accountQuery.findBy(toId);
if (from.balance() > quantity) {
//create txn
}
}
}
我应该在命令端模拟帐户吗?我必须更新每个db事务至少三个聚合根(从/到帐户和帐户txn)。
public class TransferApplication {
public void transfer(...) {
Account from = accountRepository.findBy(fromId);
Account to = accountRepository.findBy(toId);
Transaction txn = new Transaction(from, to, quantity);
//unit or work locks and updates all three aggregates
}
}
public class AccountingTransaction {
public AccountingTransaction(...) {
if (from.permit(quantity) {
from.debit(quantity);
to.credit(quantity);
raise(new TransactionCreatedEvent(sequence, from, to, quantity,...);
}
}
}
您是否想要使用DDD进行银行应用? – Developer
@Singh谢谢你的评论。是的,DDD与CQRS。 – Hippoom
我有一个关于银行应用程序的项目。你想要吗? – Developer