Lagom:命令处理程序中的异步操作 [英] Lagom: Asynchronous Operations in Command Handlers

查看:88
本文介绍了Lagom:命令处理程序中的异步操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Lagom中,当命令处理程序必须执行一些异步操作时您会怎么做?例如:

In Lagom, what do you do when a command handler must perform some asynchronous operations? For example:

override def behavior = Actions().onCommand[MyCommand, Done] {
  case (cmd, ctx, state) =>
    // some complex code that performs asynchronous operations
    // (for example, querying other persistent entities or the read-side
    // by making calls that return Future[...] and composing those),
    // as summarized in a placeholder below:
    val events: Future[Seq[Event]] = ???
    events map {
      xs => ctx.thenPersistAll(xs: _*) { () => ctx.reply(Done) }
    }
}

此类代码的问题在于,编译器希望命令处理程序返回Persist,而不是Future[Persist].

The problem with the code like that is that the compiler expects the command handler to return Persist, not Future[Persist].

是否这样做是为了确保事件以正确的顺序持久存在(也就是说,必须先保存由先前命令生成的事件,然后再保存由后续命令生成的事件)?但是,不能通过对事件偏移量的适当管理来处理该问题,以使日记始终正确地订购它们,而不管它们何时实际保存?

Is this done on purpose, to make sure that the events are persisted in the correct order (that is, the events generated by a prior command must be saved before the events generated by a later command)? But can't that be handled by proper management of the event offsets, so that the journal always orders them correctly, regardless of when they are actually saved?

在这样的情况下,当命令处理足够复杂以至于需要从命令处理程序进行异步调用时,该怎么办?

And what does one do in situations like this, when the command handling is complex enough to require making asynchronous calls from the command handler?

推荐答案

邮件列表中也有类似的问题,James给出了答案. https://groups.google. com/forum/?utm_medium = email& utm_source = footer#!topic/lagom-framework/Z6lynjNTqgE

There is a similar question on the mailing list with an answer from James. https://groups.google.com/forum/?utm_medium=email&utm_source=footer#!topic/lagom-framework/Z6lynjNTqgE

简而言之,您在CQRS应用程序中的实体是一个一致性边界,并且应该仅依赖于其内部立即可用的数据,而不是外部(不调用外部服务)的数据.

In short, your entity in a CQRS application is a consistency boundary and should only depend on data that it's immediately available inside it, not outside (no call to external services).

您可能正在寻找的是所谓的Command Enrichment.您会收到一个请求,从外部服务收集一些数据,并构建一个命令,其中包含您需要发送给实体的所有内容.

What you are probably looking for a what it's called Command Enrichment. You receive an request, collect some data from external services and build a command containing everything you need to send to your Entity.

您当然不应该查询读取端以在写入端实体内做出业务决策.您也不应对来自其他实体的数据做出业务决策.

You certainly should not query the read-side to make business decisions inside your write-side entity. You also should not make business decisions on data coming from other entities.

您的实体应该能够做出所有决定,因为它是模型的一致性边界.

Your entity should be able to make all the decision because it is the consistency boundary of your model.

这篇关于Lagom:命令处理程序中的异步操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆