qiuzhiming0 2016-07-20
现有的架构设计实在受不了,业务的反反复复地变化,导致代码圈复杂度之深让人恐惧。之前的微服务架构经验让我更加彻底点,采用DDD领域驱动设计进行整个改变。
随着经过几个月的努力,确实慢慢地体会到ddd的架构设计的优势,聚合根设计能够协助我们整个服务改造,开发起来越来越迅速。
CQRS访问方式:
在CQRS的架构体系,首先会被独立出来两个组件,一个事command的微服务负责add、update等改变状态的动作,query的微服务顾名思义就是读动作。
案例:
gateway在之前的blog已经写过,不在这里叙述
首先简单的rest controller
@RestController public class NotifyController { @Autowired private CommandGateway commandGateway; @RequestMapping(value = "/notify", method = RequestMethod.GET) public void notify(HttpServletRequest request) { commandGateway.send(asCommandMessage(new CreateTaskCommand("1","chenyang","China")), new CommandCallback() { @Override public void onSuccess(Object result) { //成功继续事情 } @Override public void onFailure(Throwable cause) { //失败 } }); } }
Command:
public class SuccessNotification extends AbstractAnnotatedAggregateRoot<String> { /** * The constant serialVersionUID */ private static final long serialVersionUID = -159779842362041665L; @AggregateIdentifier private String id; @CommandHandler public SuccessNotification(SuccessNotifyCommand command) { apply(new SuccessNotifyEvent(command.getId())); } SuccessNotification() { } @CommandHandler void on(SuccessNotifyCommand command) { apply(new SuccessNotifyEvent(command.getId())); } @EventSourcingHandler public void on(SuccessNotifyEvent event) { this.id = event.getId(); } }
Event:
@EventHandler String on(SuccessNotifyEvent event) { return "world"; }
相对于烟囱式的方式,ddd对于开发者以及架构师要求更高,充当角色之一领域专家,需要对于聚合根理解透彻,才能更好地理解业务。