接續前面的實作,這次改用另一種寫法:在 Controller 中透過 Future 搭配 Timeout 呼叫 Actor 池,由 Akka 自動輪流分派。
app/controllers/MyController.java 中的 myFunc 方法修改如下:
import akka.util.Timeout;
import scala.concurrent.duration.Duration;
public Result myFunc(String str1, String str2) throws Exception {
Logger.info("Class:[{}], Method: [{}], Message: [{}]",
"myController", "myFunc", "para1: " + str1 + ", para2: " + str2);
String messages = str1 + ":" + str2;
Timeout timeout = new Timeout(Duration.create(1, "seconds"));
Future<Object> future = Patterns.ask(
AkkaSystem.getMyActorPoolActorRef(), messages, timeout);
String result = (String) Await.result(future, timeout.duration());
return ok(result);
}
app/actors/MyActorPool.java:
@Override
public void onReceive(Object message) throws Exception {
System.out.println(this.toString());
if(message instanceof String) {
String str = (String) message;
System.out.println("copied:\n" + str);
getSender().tell("echo:\n" + str, getSelf());
} else {
unhandled(message);
}
}
Actor 池的宣告:
myActorPool = actorSystem.actorOf(
new RoundRobinPool(2).props(Props.create(MyActor.class)),
"myActorPool");
連續呼叫四次 curl -X PUT https://localhost:9000/my1/my2,終端機會看到兩個 MyActor 實例(@6bc1da7a 與 @15592c1a)輪流接手請求,回應都是 echo: my1:my2。
非同步 Future:Future 與 Promise 是非同步開發的兩個常用介面。Future 持有一個只能被賦值一次的結果狀態,isCompleted 為 true 且 success 代表操作成功;Scala 以阻塞方式取值,常用 Await.result。
角色模型:Actor 類繼承 UntypedActor,核心方法是 onReceive;Props 是配置類,用 Props.create(...) 建立;ActorSystem.actorOf 是接受 Props 實例的工廠方法。回覆訊息時用 getSender() 取得對方角色引用,再呼叫 tell。此外還支援終止、熱替換、逾時與 stash 等特性。
配置:Akka 使用 Typesafe Config Library(純 Java 設定庫),也可以完全不寫配置。Akka 與設定之間的唯一介面是 ActorSystem 實例,它是設定資訊的唯一消費者。Play 在 conf 目錄預設產生 application.conf、logback.xml、routes 三個檔案,編譯後會被複製到 target/scala-2.11/classes 也就是 class 檔的頂層目錄。