Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1519788
  • 博文数量: 399
  • 博客积分: 8508
  • 博客等级: 中将
  • 技术积分: 5302
  • 用 户 组: 普通用户
  • 注册时间: 2009-10-14 09:28
个人简介

能力强的人善于解决问题,有智慧的人善于绕过问题。 区别很微妙,小心谨慎做后者。

文章分类

全部博文(399)

文章存档

2018年(3)

2017年(1)

2016年(1)

2015年(69)

2013年(14)

2012年(17)

2011年(12)

2010年(189)

2009年(93)

分类: 架构设计与优化

2015-06-08 14:30:40

Command-Query Responsibility Segregation

To understand CQRS, let’s first talk about the object pattern Command-Query Separation (CQS).

CQS at an object level means:

  1. If a method mutates the state of the object, it is a command, and it must not return a value.
  2. If the method returns some value, it is a query, and it must not mutate state.

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.

Query Model

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 Processor

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 Model

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 Event

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.

Note: Domain Events are always in past tense since they describe what has already occurred (e.g. 'ITEM_ADDED_TO_CART').

Event Subscriber

An Event Subscriber receives all Domain Events published by the Command Model. When an event occurs, it updates the Query Model accordingly.

Command

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.

Note: Commands are always in imperative tense since they describe behaviours that need to be executed (e.g. AddItemToCart).

Command Handler

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.

阅读(3578) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~