能力强的人善于解决问题,有智慧的人善于绕过问题。 区别很微妙,小心谨慎做后者。
全部博文(399)
分类: 架构设计与优化
2015-06-08 14:30:40
To understand CQRS, let’s first talk about the object pattern Command-Query Separation (CQS).
CQS at an object level means:
In normal DDD, Aggregate objects are used for both command and query. We will also have Repositories that contain methods to find and persist Aggregate objects.
CQRS simply takes CQS further by separating command and query into different objects. Aggregates would have no query methods, only command methods. Repositories would now only have a single query method (e.g. find), and a single persist method (e.g. save).
In the CQRS pattern, you will find new objects not found in normal DDD.
The Query Model is a pure data model, and is not meant to deliver domain behaviour. These models are denormalized, and meant for display and reporting.
Query Models are usually retrieved by performing a query. The queries can be handled by a Query Processorthat knows how to look up data, say from a database table.
Command Models are different from normal Aggregates in that they only contain command methods. You can never “ask” it anything, only “tell” (in the Tell, Don’t Ask sense).
As a command method completes, it publishes a Domain Event. This is crucial for updating the Query Model with the most recent changes to the Command Model.
Domain Events lets Event Subscribers know that something has changed in the corresponding Command Model. They contain the name of the event, and a payload containing sufficient information for subscribers to correctly update Query Models.
An Event Subscriber receives all Domain Events published by the Command Model. When an event occurs, it updates the Query Model accordingly.
Commands are submitted as the means of executing behaviour on Command Models. A command contains the name of the behaviour to execute and a payload necessary to carry it out.
The submission of a Command is received by a Command Handler, which usually fetches an Command Model from its Repository, and executes a Command method on it.