the*_*eon 17 asynchronous scala future actor akka
当调用?或ask在Akka Actor上时,Future[Any]返回a并且我必须通过显式转换future.mapTo[MyType].
我不喜欢失去这种类型的安全.如果我直接使用Futures(没有演员)我可以明确地返回Future[MyType]并保持类型安全.
我的具体用例涉及一个演员将其消息委托给两个子演员,然后汇总这些演员的结果并将其返回给父母的发件人.我父母的接收方法与Akka Docs中的这种方法类似:
http://doc.akka.io/docs/akka/2.0/scala/futures.html#For_Comprehensions
val f1 = actor1 ? msg
val f2 = actor2 ? msg
val f3 = for {
a ? f1.mapTo[Int]
b ? f2.mapTo[Int]
c ? ask(actor3, (a + b)).mapTo[Int]
} yield c
Run Code Online (Sandbox Code Playgroud)
有没有更好的方法来实现我的用例?
我想发布一个新答案,因为@Roland Kuhn最近提出了一个新的解决方案,称为Typed Channels:
val f: Future[MyType] = actor <-?- message
Run Code Online (Sandbox Code Playgroud)
尝试打字的演员.基本上,它们允许您使用强类型特征/接口而不是通过交换消息来与actor进行交互.在幕后,Akka使用动态代理实现这些接口,并实现异步魔术.
类型化的actor可以返回具有不同的强类型返回值的方法(来自上面提到的文档):
def squareDontCare(i: Int): Unit //fire-forget
def square(i: Int): Future[Int] //non-blocking send-request-reply
def squareNowPlease(i: Int): Option[Int] //blocking send-request-reply
def squareNow(i: Int): Int //blocking send-request-reply
Run Code Online (Sandbox Code Playgroud)
这些方法代表,tell而剩下的是不同的风味ask.