我有一个远程演员Bar
和一个本地演员,Foo
. 我想用来在每次调用 CLIFoo
时传递消息。Bar
Bar
可以成功传递消息,但Foo
在等待消息时挂起。为了解决这个问题,我在mainsys.exit(0)
的末尾添加了一个。Foo
这会导致与系统的关联问题Foo
。
如何在连续 CLI 发布之间关闭我的本地演员,而无需手动杀死我的本地演员?
闭嘴,给我密码!
福:
build.sbt
name := "Foo"
version := "1.0"
scalaVersion := "2.11.8"
libraryDependencies += "com.typesafe.akka" %% "akka-actor" % "2.4.11"
libraryDependencies += "com.typesafe.akka" %% "akka-remote" % "2.4.11"
libraryDependencies += "com.github.scopt" %% "scopt" % "3.5.0"
fork in run := true
Main.scala
import akka.actor._
import com.typesafe.config.ConfigFactory
case class Config(mode: String = "", greeting: String="")
class Foo extends Actor {
// create the remote actor
val BarActor = context.actorSelection("akka.tcp://BarSystem@127.0.0.1:2552/user/BarActor")
def receive = {
case method: String => BarActor ! method
}
}
object CommandLineInterface {
val config = ConfigFactory.load()
val system = ActorSystem("FooSystem", config.getConfig("FooApp"))
val FooActor = system.actorOf(Props[Foo], name = "FooActor")
val parser = new scopt.OptionParser[Config]("Foo") {
head("foo", "1.x")
help("help").text("prints usage text")
opt[String]('m', "method").action( (x, c) =>
c.copy(greeting = x) ).text("Bar will greet with <method>")
}
}
object Main extends App {
import CommandLineInterface.{parser, FooActor}
parser.parse(args, Config()) match {
case Some(config) => FooActor ! config.greeting
case None => sys.error("Bad news...")
}
/*
When sys.exit(0) commented, this hangs and Bar greet.
When sys.exit(0) uncommented, this doesn't hang, but also Bar doesn't greet.
*/
//sys.exit(0)
}
应用程序.conf
FooApp {
akka {
loglevel = "INFO"
actor {
provider = "akka.remote.RemoteActorRefProvider"
}
remote {
enabled-transports = ["akka.remote.netty.tcp"]
netty.tcp {
hostname = "127.0.0.1"
port = 0
}
log-sent-messages = on
log-received-messages = on
}
}
}
酒吧:
构建.sbt
name := "Bar"
version := "1.0"
scalaVersion := "2.11.8"
libraryDependencies += "com.typesafe.akka" %% "akka-actor" % "2.4.11"
libraryDependencies += "com.typesafe.akka" %% "akka-remote" % "2.4.11"
Main.scala
import akka.actor._
import com.typesafe.config.ConfigFactory
class Bar extends Actor {
def receive = {
case greeting: String => Bar.greet(greeting)
}
}
object Bar {
val config = ConfigFactory.load()
val system = ActorSystem("BarSystem", config.getConfig("BarApp"))
val BarActor = system.actorOf(Props[Bar], name = "BarActor")
def greet(greeting: String) = println(greeting)
def main(args: Array[String]): Unit = {
/* Intentionally empty */
}
}
应用程序.conf
BarApp {
akka {
loglevel = "INFO"
actor {
provider = remote
}
remote {
enabled-transports = ["akka.remote.netty.tcp"]
netty.tcp {
hostname = "127.0.0.1"
port = 2552
}
log-sent-messages = on
log-received-messages = on
}
}
}
运行Foo
,sbt 'run-main Main -m hello'
并Bar
运行sbt 'run-main Main'
。
抱歉,代码很长,但这是我的问题的 MVCE。
我怎样才能实现我想要的行为——CLI 参与者在连续 CLI 调用之间死亡,远程参与者等待新消息。