1akka的监督策略有OneForOneStrategy,AllForOneStrategy(一个出问题,对所有兄弟都进行处理)
2actorSelection:选择actor的标准:
systemName+“user”+fatherName+selfName
package akka;
import akka.actor.*;
import akka.japi.Function;
import com.typesafe.config.ConfigFactory;
import scala.Option;
import scala.concurrent.duration.Duration;
import java.util.concurrent.TimeUnit;
public class strategy {
public static class Supervisor extends UntypedActor{
public static SupervisorStrategy supervisorStrategy=new OneForOneStrategy(
3, Duration.create(1, TimeUnit.MINUTES),
//表示一秒内若出三次问题就自动结束
new Function<Throwable, SupervisorStrategy.Directive>() {
@Override
public SupervisorStrategy.Directive apply(Throwable t) throws Exception {
if(t instanceof ArithmeticException){
System.out.println("arithme ,just resume");
return SupervisorStrategy.resume();
//若是数问题,则不做处理
}else if(t instanceof NullPointerException){
System.out.println("nullpoint ,restart");
return SupervisorStrategy.restart();
//空指针则重启
}else if(t instanceof IllegalArgumentException){
return SupervisorStrategy.stop();
}else {
return SupervisorStrategy.escalate();
//其他的交给父级处理
}
}
}
);
@Override
public SupervisorStrategy supervisorStrategy() {
return supervisorStrategy;
//这里覆盖了父类的supervisorStrategy,使用自定义的strategy
}
@Override
public void onReceive(Object o) throws Throwable {
if(o instanceof Props){
//如果收到一个actor,会进行监听
getContext().actorOf((Props)o,"RestartActor");
}else unhandled(o);
}
}
//RestartActor 类
public static class RestartActor extends UntypedActor{
public static enum msg{
DONE,RESTART
}
@Override
public void preStart() throws Exception {
System.out.println("prestart hashcode"+this.hashCode());
}
@Override
public void postStop() throws Exception {
System.out.println("postStop hashcode"+this.hashCode());
}
@Override
public void postRestart(Throwable reason) throws Exception {
super.postRestart(reason);
System.out.println("postRestart hashcode"+this.hashCode());
}
@Override
public void preRestart(Throwable reason, Option<Object> message) throws Exception {
System.out.println("preRestart hashcode"+this.hashCode());
}
@Override
public void onReceive(Object o) throws Throwable {
if(o==msg.DONE){
getContext().stop(getSelf());
}else if(o==msg.RESTART){
System.out.println(((Object)null).toString());
//模拟空指针异常
double a=0/0;
//
}
unhandled(o);
}
}
public static void main(String[] args) {
ActorSystem system=ActorSystem.create("lifecycle", ConfigFactory.load("akka.conf"));
ActorRef actorRef = system.actorOf(Props.create(Supervisor.class),"Supervisor");
actorRef.tell(Props.create(RestartActor.class),ActorRef.noSender());
ActorSelection selection=system.actorSelection("akka://lifecycle/user/Supervisor/RestartActor");
for(int i=0;i<10;i++){
selection.tell(RestartActor.msg.RESTART,ActorRef.noSender());
}
}
}