我有一個遠程演員,Bar
和本地演員Foo
。我希望使用Foo
在每次調用CLI時將消息傳遞給Bar
。如何使用Akka Remoting通過CLI將消息發送給遠程演員?
Bar
可以成功傳遞消息,但Foo
在等待消息時掛起。爲了解決這個問題,我在Foo
的最後添加了一個sys.exit(0)
。這會導致與Foo
的系統有關聯問題。
如何在連續CLI發行之間關閉本地演員而不手動殺死本地演員?
閉嘴,給我代碼!
的Foo:
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://[email protected]: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)
}
application.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
}
}
}
酒吧:
build.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 */
}
}
application.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
}
}
}
與sbt 'run-main Main -m hello'
運行Foo
,並與sbt 'run-main Main'
運行Bar
。
對不起,長的代碼,但它是我的問題MVCE。
我該如何實現自己想要的行爲 - CLI角色會在連續的CLI調用與遠程參與者等待新消息之間死亡。
爲什麼你認爲'Bar'死了?日誌中是否有指示這一點的內容? –
@PawełBartkiewicz我試圖澄清我的意思。對不起,這個錯誤。 :)希望它更清楚。 – erip