作为一个新手,我想了解演员如何工作。并且,从文档,我想我明白,演员是在同步模式下执行的对象,并且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中的呼叫
发布评论