介绍akka之前需要简单说一下Scala,Scala号称下一代jvm语言,
集成了Java的面向对象,以及函数式编程于一体,异常强大,但也复杂,此文不作争论,姑且简单介绍。
Akka框架是基于scala以及少量java代码实现的,Scala从其2.11.0版本起将自有的底层actor库替换成了akka,可见akka的强大。
Akka官网的自吹:
Akka is a toolkit and runtime for building highly concurrent, distributed, and fault tolerant event-driven applications on the JVM.
Akka同时提供了Java和Scala两种API接口,下面就Java接口为例简单介绍一下。
Ø Actor表示
² public class Greeting implements Serializable {
² public final String who;
² public Greeting(String who) { this.who = who; }
² }
²
² public class GreetingActor extends UntypedActor {
² LoggingAdapter log = Logging.getLogger(getContext().system(), this);
²
² public void onReceive(Object message) throws Exception {
² if (message instanceof Greeting)
² log.info("Hello " + ((Greeting) message).who);
² }
² }
²
² ActorSystem system = ActorSystem.create("MySystem");
² ActorRef greeter = system.actorOf(Props.create(GreetingActor.class), "greeter");
² greeter.tell(new Greeting("Charlie Parker"), ActorRef.noSender());
继承UntypeActor可以定义一个actor角色的类,其中的onReceive方法可以接受来自其他actor传递过来的消息
ActorSystem类负责创建最顶层的actor,其负责管理整个系统中actors监控树。
Ø 分布式
ActorSystem system = ActorSystem.create("MySystem");
//获取机器2上面的一个actor:greeter
ActorSelection greeter = system.actorSelection("akka.tcp://MySystem@machine2:2552/user/greeter");
// 向上面的actor发送消息,Greeting表示消息
greeter.tell(new Greeting("Sonny Rollins"), ActorRef.noSender());
上面的几行代码简单展示了akka中的分布式环境中不同机器节点之间actor的相互通信方式,可以看出和Erlang很类似,即屏蔽底层节点之间的通信细节,然后提供简单API接口。
Ø 监控
class Supervisor extends UntypedActor {
private SupervisorStrategy strategy = new OneForOneStrategy(
10, Duration.create("1 minute"), new Function<Throwable, Directive>() {
@Override
public Directive apply(Throwable t) {
if (t instanceof ArithmeticException) return resume();
else if (t instanceof NullPointerException) return restart();
else return escalate();
}
});
@Override
public SupervisorStrategy supervisorStrategy() {
return strategy;
}
ActorRef worker = context.actorOf(Props.create(Worker.class));
public void onReceive(Object message) throws Exception {
if (message instanceof Integer) worker.forward(message, getContext());
}
}
上面代码定义了一个监控角色的actor,可以看到其也是继承与UntypeActor,因为监控者变身也是一个actor,其变身也可以被监控。与普通 工作actor不同的是,其定义了监控策略SupervisorStrategy,负责处理子actor的重启、停止工作。