天天看點

akka mysql_初試超輕量級actor架構——akka

akka的大名在之前學Scala的時候就時常聽到,就連Scala作者都不得不贊歎它對actor實作的精妙。最近寫一個服務端代碼,對于接受到的請求需要查詢背景多個資料庫,這自然就想到用多線程來并行查詢,然後把結果合并起來。這裡最主要的就是多線程任務的執行以及執行結果的回調。這個時候突然回憶起用Scala時一個簡單的“!”就實作了多線程調用的清爽和友善,那現在用java+akka架構是什麼樣呢?

先找到官方網站大概的翻閱了一下,驚訝的發現這個架構比想象中強太多了。一下載下傳下來就看到很多高品質庫,httpclient, netty, jetty, asm等等,這都不知道他具體想做成什麼了。在官方看到一處說明,akka有兩種使用方式,一種就是作為一個子產品調用,另外一種就是作為一個服務。

看完文檔後,感覺akka确實非常出色!實作了actor模式這點就不說了,首先就是有非常好的容錯性,其次它居然還有對記憶體對象實作事務的功能,還有他能非常友善的實作遠端調用以及線程間通訊,還能定制路由政策,對第三方架構的內建也非常好。基于上述的功能,akka完全有實力作為系統的核心架構,通過它簡單的多線程調用方式和支援遠端調用,實作一個分布式計算的系統非常容易。

最後還是給個小例子,代碼很簡單,隻是用到的庫非常多,放的位置也比較分散,自己慢慢找吧。

這個是TypedActor的接口:

importakka.dispatch.Future;

publicinterfaceMathTypedActor {

publicFuture square(intvalue);

}

這個是TypedActor的具體實作:

importakka.actor.TypedActor;

importakka.dispatch.Future;

publicclassMathTypedActorImplextendsTypedActorimplementsMathTypedActor {

@Override

publicFuture square(intvalue) {

returnfuture(value * value);

}

}

這是調用的main方法:

importakka.actor.TypedActor;

importakka.dispatch.Future;

publicclassMathTypedActorTest {

publicstaticvoidmain(String[] args) {

test();

}

privatestaticvoidtest() {

MathTypedActor math = TypedActor.newInstance(MathTypedActor.class, MathTypedActorImpl.class);

Future future = math.square(10);

future.await();

Integer result = future.result().get();

System.out.println(result);

TypedActor.stop(math);

}

}