YangMark

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

So far we have defined our Actor and its messages. Now let's create an instance of this actor. 

In Akka you can't create an instance of an Actor the regular way using new, instead you create it using a factory. 

在Akka中你無法使用new創建Actor的實例, 而是使用工廠創建它.

What is returned from this factory is not an instance of the Actor itself but an ActorRef pointing to our actor instance.

不是Actor本身由工廠返回實例, 而是一個ActorRef指向我們的actor實例.

 

This level of indirection adds a lot of power and flexibility. It enables for example location transparency meaning that the ActorRef can, while retaining the same semantics, represent an instance of the running actor in-process or on a remote machine. I.e. location doesn't matter. 

這個間接的方式增加了很多功能與靈活性. 它使如本地透明度(location transparency)變的容易(這句不知道怎麼翻比較好), 意味是ActorRef能保技相同的語意, 表示執行在過程中的actor或遠端的機器, 也就是說位置是不重要的.

This also means that the runtime can if needed optimize the system by changing an actor's location or the application's topology while it is running. Another thing that this level of indirection enables is the "let it crash" model of failure management in which the system can heal itself by crashing and restarting faulty actors.

這也意味著若在運行期間需要可以改變actor的位置去優化系統或應用程序的拓撲結構, 雖然它是運行的. 另一件事這個間接方式使"let it crash" 失敗管理模型變為可能, 系統可以藉著損壞自我修復與重啟錯誤的actors.

 

This factory in Akka is the ActorSystem and is to some extent similar to Spring's BeanFactory in that it also acts as a container for your Actors, managing their life-cycles etc. You create an Actor through the actorOf factory method. This method takes a configuration object called Props and a name. Actor (and ActorSystem) names are important in Akka, you use them for example when looking Actors up as well as when you configure them in the configuration file[1], so you should take your time giving your Actors good names.

這個工廠在Akka中是ActorSystem, 而且在一定程度上類似於Spring's BeanFactory, 你的Actors也可以做為一個容器, 如管理生命週期等. 你可以透過actorOffactory方法創建Actor.  此方法採用了所謂的Props與一個名稱的配置對象. 在Akka中Actor (and ActorSystem)的命名是重要的, 你使用它們例如找出Actor且你在配置檔案[1]中配置它們, 所以你應該花時間給你的Actors好名字.

 

This is the code that we have to write in Java:

// Java code
final ActorSystem system = ActorSystem.create("helloakka");
final ActorRef greeter = system.actorOf(Props.create(Greeter.class), "greeter");

The Scala code is not much different:

// Scala code
val system = ActorSystem("helloakka")
val greeter = system.actorOf(Props[Greeter], "greeter")

Now we have a running instance of a Greeter actor. Next we will learn how to communicate with it.

posted on 2014-06-04 12:33  YangMark  阅读(227)  评论(0编辑  收藏  举报