Saga的实现模式——进化(Saga implementation patterns – variations)

在之前的几个博客中,我主要讲了两个saga的实现模式:

  • 基于command的控制者模式
  • 基于事件的观察者模式

当然,这些都不是实现saga的唯一方式。我们甚至可以将这些结合起来。

发布者——收集者

回顾我们的麦当劳的例子,我们可以稍稍改进一下我们的方案。我们可以通过一个command去启动一个saga,然后这个saga就会发布消息。然后saga就等待回复事件(忽略顺序):

image

这里有一个优点,那就是我们的saga只有一个入口。因此我们不必担心我们的saga被其他消息触发。

当你在麦当劳下一个订单的时候,总是有一个服务员把托盘放到柜台上。当工作台完成了薯条,三明治等等食物的制作,他们从来不到柜台看看:“我是否还需要一个新的托盘?”因为托盘总是已经被准备好在那里了,就像我们的saga在业务开始之前总是已经开始了的。

在这里没有任何阻止产生额外saga的方法——但是其实是有的。

报告者

saga可以扮演另一个不做任何决定而仅仅报告状态的角色:

image

This is a situation where a saga might never actually complete, and goes on forever. Its role is to communicate status of a longer-running process in the back-end, not for coordination purposes, but for reporting purposes.

The reason we might want a saga for this case is we still don’t know what order we’ve received messages from downstream systems we don’t own. As we learn about downstream events, we can evaluate them based on our knowledge of the overall business process. An order can’t go backwards from “shipped” to “verified”, so receiving these out of order doesn’t change the fact that the order shipped! Note: this doesn’t necessarily imply the status is in the saga entity itself. It still could be separate.

Keeping it as a saga lets us handle messages in any order and keep some centralized logic around interpreting these messages.

Sagas/process managers are pretty flexible in how we compose the pieces together. I often get questions around “why can’t I design a saga like a workflow?” And the answer is that sagas are meant to handle cases where I don’t have a directed workflow, where I live in a world where messages can arrive out of order.

It’s a much easier world to scale – but we need to accept the complexity it brings on the other end.

There is another clear downside here – we have shared state amongst multiple messages and handlers, which can potentially lead to scaling problems. Next time, we’ll look at scaling sagas.

有一种saga可能永远无法完成并且会永远运行下去。它的职责是和后台运行的长时间运行的事务保持通讯,主要为了报告状态而不是为了协调业务。

我们可能需要这种saga的原因是我们仍然不知道从不属于我们的上游系统中得到消息的顺序。当我们处理上游的事件的时候,我们可以通过我们对整个业务过程的理解来判断。就好比一个订单不可能从“已发货”变成“已审核”,所以尽管收到的事件的顺序不一样也不可能改变货物已经发货的事实。注意:这并不意味着状态必须被包含在saga中,它也是可以被分出去的。

saga让我们能够忽略事件到来的顺序,并且能够通过一定的逻辑解读这些消息。

sagas/process manager能够让我们更灵活地把这些消息组织起来。我经常被人问道:“为什么我们不能把saga设计成一个工作流呢?”答案就是saga是用来处理一些不能控制的工作流情况的,因为在现实世界里消息的到来可能会不按照顺序。

posted @ 2016-10-20 17:23  balavatasky  阅读(524)  评论(0编辑  收藏  举报