阻止Akka Actors中的呼叫 [英] Blocking calls in Akka Actors

查看:178
本文介绍了阻止Akka Actors中的呼叫的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

作为一个新手,我想了解演员如何工作。并且,从文档,我想我明白,演员是在同步模式下执行的对象,并且actor执行可以包含阻塞/同步方法调用,例如。 db请求

As a newbie, I am trying to understand how actors work. And, from the documentation, I think I understand that actors are objects which gets executed in sync mode and also that actor execution can contain blocking/sync method calls, e.g. db requests

但是,我不明白的是,如果你写一个在其中有一些阻塞调用(如阻塞查询执行)的actor,整个线程池(在某种意义上cpu的利用率会下降等等),对吧?我的意思是,从我的理解,没有办法JVM理解是否可以切换到别人,如果/当演员进行阻塞调用时。

But, what I don't understand is that if you write an actor that has some blocking invocations inside (like a blocking query execution), it will mess up the whole thread pool (in the sense that cpu utilization will go down, etc.), right ? I mean, from my understanding, there is no way for JVM to understand whether it can switch that thread to someone else, if/when the actor makes a blocking call.

所以,考虑到并发的性质,应该不是很明显,演员不应该做任何阻塞调用,永远?

So, given the nature of concurrency, shouldn't it be obvious that Actors should not be doing any blocking calls, ever?

如果是这种情况,建议使用非阻塞/异步调用的方法,假设一个Web服务调用获取一些东西并发送消息另一个actor何时该请求完成?我们应该简单地使用像actor中的东西:

If that is the case, what is the recommended way of doing a non-blocking/async call, let's say a web service call that fetches something and sends a message to another actor when that request is completed? Should we simply use something like within the actor:

future map {response => x! response.body}

future map { response => x ! response.body }

这是正确的处理方式吗?

Is this the proper way of handling this?

这对我来说。

推荐答案

这真的取决于用例。如果查询不需要序列化,那么您可以以后执行查询并将结果发送回发件人,如下所示:

It really depends on the use-case. If the queries do not need to be serialized, then you can execute the query in a future and send the results back to the sender as follows:

import scala.concurrent.{ future, blocking}
import akka.pattern.pipe

val resFut = future {
  blocking {
    executeQuery()
  }
}

resFut pipeTo sender

您还可以为DB调用专门创建专用分派器,并使用路由器创建actor。这样,您也可以轻松地限制并发数据库请求的数量。

You could also create a dedicated dispatcher exclusively for the DB calls and use a router for actor creation. This way you can also easily limit the number of concurrent DB requests.

这篇关于阻止Akka Actors中的呼叫的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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