一、简介
Akka的actor是对actor模型的实现,下面的例子中使用简单的demo说明akka的actor的用法(作为jar包使用,akka也可以作为单独的服务使用而且很强大),akka的scala版本使用起来比较简洁,但是java版的就有点略显繁琐。
二、示例
1、maven配置:下载下来的jar包除了akka-actor还有依赖包scala-library和config
<dependency>
<groupId>com.typesafe.akka</groupId>
<artifactId>akka-actor_2.10</artifactId>
<version>2.2.4</version>
</dependency>
2、定义actor并重写里边的生命周期方法(方便观察生命周期),和消息处理方法
import scala.Option;
import akka.actor.UntypedActor;
public class HelloWorld extends UntypedActor {
@Override
public void preStart() {
System.out.println("===preStart");
}
@Override
public void preRestart(Throwable reason, Option<Object> message) throws Exception {
System.out.println("===preRestart");
super.preRestart(reason, message);
}
@Override
public void postRestart(Throwable reason) throws Exception {
System.out.println("===postRestart");
super.postRestart(reason);
}
@Override
public void postStop() throws Exception {
System.out.println("===postStop");
super.postStop();
}
@Override
public void onReceive(Object msg) {
if (msg.toString().equals("hello")) {
System.out.println("----" + msg);
// getContext().stop(getSelf());
} else {
// 导致崩溃,actor会自动重启
System.out.println(3 / 0);
// unhandled(msg);
}
}
}
3、启动actor的入口类
import akka.actor.ActorRef;
import akka.actor.ActorSelection;
import akka.actor.ActorSystem;
import akka.actor.Props;
import com.akka.actor.HelloWorld;
public class App {
public static void main(String[] args) throws InterruptedException {
ActorSystem system = ActorSystem.create("akka");
ActorRef rcActor = system.actorOf(Props.create(HelloWorld.class), "helloWorld");
rcActor.tell("hi", ActorRef.noSender());
//Thread.sleep(3000);
//Actor树
ActorSelection as = system.actorSelection("/user/helloWorld");
as.tell("hello", ActorRef.noSender());
}
}
三、结果
===preStart
===preRestart
===postStop
===postRestart
===preStart
----hello
[ERROR] [03/17/2014 17:31:00.919] [akka-akka.actor.default-dispatcher-2] [akka://akka/user/helloWorld] / by zero
java.lang.ArithmeticException: / by zero ... ....
启动时调用了preStart方法
因为消息处理导致崩溃,akka停止处理消息并自动重启(preRestart --> preStart)
重启之后可以继续处理mailbox中的消息
输出的日志信息并不是异常出现的位置,是因为akka的日志处理本身也是交由actor(/system)处理,是异步的