Akka/Scala:映射Future vs pipeTo

rap*_*apt 11 scala actor akka

Akka演员中,是否存在任何差异 - 在使用的​​线程数或线程锁定方面 - 通过以下方式将Future结果发送给另一个演员:

A.映射Future到函数,tell结果到演员.

B.定义onSuccess对未来的回调,其tell结果是演员.

C.将Future结果传递给演员pipeTo.

其中一些选项在前一个问题中讨论过:

Akka:向演员发送未来消息

三者中哪一个是首选方式,为什么?

另外,我想知道,如果receive应该是类型Any => Unit,那么为什么代码编译时在某些情况下receive返回a 的部分函数Future,不是Unit

以下是我在上面提到的三个选项的代码示例:

import akka.actor.{Actor, ActorRef, ActorSystem, Props}
import akka.pattern.ask
import akka.util.Timeout
import akka.pattern.pipe

import scala.concurrent.Future
import scala.concurrent.duration._
import scala.language.postfixOps
import scala.util.Success

class ActorIncrement extends Actor {

  def receive = {
    case i: Int =>
      println(s"increment $i")
      sender ! i + 1
  }
}

class ActorEven extends Actor {

  def receive = {
    case i: Int =>
      println(s"$i is even")
  }
}


class ActorOdd extends Actor {

  def receive = {
    case i: Int =>
      println(s"$i is odd")
  }
}

class MyActor(actorIncrement: ActorRef, actorEven: ActorRef, actorOdd: ActorRef) extends Actor {
  import scala.concurrent.ExecutionContext.Implicits.global

  implicit val timeout = Timeout(5 seconds)

  def receive = {
    case i: Int if i % 2 == 0 =>
      println(s"receive a: $i")
      actorIncrement ? i map {
        case j: Int =>
          println(s"$j from increment a")
          actorOdd ! j
      }
    case i: Int =>
      println(s"receive b: $i")
      val future: Future[Any] = actorIncrement ? i
      future onSuccess {
        case i: Int =>
          println(s"$i from increment b")
          actorEven ! i
      }

    case s: String =>
      println(s"receive c: $s")
      (actorIncrement ? s.toInt).mapTo[Int] filter(_ % 2 == 0) andThen { case Success(i: Int) => println(s"$i from increment c") } pipeTo actorEven
  }
}

object TalkToActor extends App {

  // Create the 'talk-to-actor' actor system
  val system = ActorSystem("talk-to-actor")

  val actorIncrement = system.actorOf(Props[ActorIncrement], "actorIncrement")
  val actorEven = system.actorOf(Props[ActorEven], "actorEven")
  val actorOdd = system.actorOf(Props[ActorOdd], "actorOdd")

  val myActor = system.actorOf(Props(new MyActor(actorIncrement, actorEven, actorOdd)), "myActor")

  myActor ! 2
  myActor ! 7
  myActor ! "11"

  Thread.sleep(1000)

  //shutdown system
  system.terminate()
}
Run Code Online (Sandbox Code Playgroud)

Sar*_*ngh 14

如果你看看如何pipeTo定义akka.pattern.PipeToSupport,

def pipeTo(recipient: ActorRef)(implicit sender: ActorRef = 
  Actor.noSender): Future[T] = {
    future andThen {
      case Success(r) ? recipient ! r
      case Failure(f) ? recipient ! Status.Failure(f)
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

正如你所看到的...... pipeTo只是添加andThen对你的调用没有什么不同,你Future可以将未来结果或Status.Failure消息发送给管道演员,以防你Future失败.

现在主要的区别在于这种Status.Failure故障处理.如果您不使用pipeTo,您可以以任何您想要的方式处理您的失败.

  • 这就是所谓的值丢弃:/sf/ask/2886688171/#41239759 (2认同)