2017-01-10 47 views
0

我正在嘗試連接Akka HTTP與Actor。我有收到「你好」,併發送回「世界,你好」如何在訪問URL時向actor發送tell消息?

class TestActor extends Actor{ 
    def receive={ 
    case "hello"=>{ 
     sender!"Hello World" 
    } 
    } 
} 

我已經定義了以下路線簡單的演員:

object Main extends App{ 

    val route1: Route = 
    get { 
     path("hello") { 
     complete { 
      "This is hello" 
     } 
     } 
    } 

    implicit val materializer = ActorMaterializer() 
    implicit val system = ActorSystem("h") 
    Http().bindAndHandle(route1, "localhost", 8185) 
} 

我想發出一個訴說消息給TestActor時/在URL中訪問hello,並顯示消息「Hello World」作爲響應。我怎樣才能做到這一點?

回答

1

你有兩個選擇。選項1是使用「Ask」模式。你可以「問」下面的演員。 「詢問」會返回您可以映射並執行其他操作的未來。您也可以在未來完成請求。這裏的警告是它需要超時。你必須配置一個超時以使其工作,這對於在一個更大的項目中維護可能變得單調乏味。

implicit val timeout: Timeout = 2 seconds 
val responseFuture = (actor ? message).mapTo[String] // This will return a Future[String] 
complete(responseFuture) 

選項2是使用「告知」模式。這比「詢問」模式更受歡迎。你可以閱讀關於here。您需要將請求上下文傳遞給新的參與者,並使用該參與者完成請求。你會做下面的事情。

val testActor = actorSystem.actorOf(Props(classOf[TestActor], reqContext), "test-actor") 

而在testActor中,您將完成請求。您可以看到herehere以獲取有關此模式的更多信息。

1

步驟1 - 創建Actor實例。

第2步 - 獲取對它的引用。

第3步 - 發送郵件

class TestActor extends Actor{ 
    def receive = { 
    case "hello" => { 
     sender() ! "Hello World" 
    } 
    } 
} 

object TestActor { 
    def props: Props = Props(classOf[TestActor]) 
} 

現在...

import akka.pattern.ask 

object Main extends App{ 

    val actorSystem = ActorSystem("actor-system") 

    implicit val implicitActorSystem = actorSystem 
    implicit val materializer = ActorMaterializer() 

    // actually create the actor 
    val testActor = actorSystem.actorOf(TestActor.props, "test-actor") 

    val route1: Route = 
    get { 
     path("hello") { 
     // get actor's reference using selection 
     val testActorSelection = actorSystem.actorSelection("/user/test-actor") 
     // now send using selection 
     val responseFuture = testActorSelection ? "hello" 

     // or send using the "val testActor" reference which we already have 
     val responseFuture = testActor ? "hello" 

     onComplete(responseFuture) { 
      case Success(message) => complete(message) 
      case Failure(ex) => complete(ex.message) 
     } 
     } 
    } 

    Http().bindAndHandle(route1, "localhost", 8185) 
} 
+0

我已經稍微修改了代碼和我的要求。演員正在發回郵件而不是打印郵件。此消息需要顯示爲響應。 – codingsplash

+0

那麼...在這種情況下,你可以使用'onComplete'指令.. –

+0

但我不想用問。我想要說出來。 – codingsplash