maven
org.springframework.boot
spring-boot-starter
com.typesafe.akka
akka-actor_2.11
2.4.3
com.typesafe.akka
akka-testkit_2.11
2.4.4
test
org.springframework.boot
spring-boot-starter-test
test
SpringExtension
public class SpringExtension extends AbstractExtensionId {
public static final SpringExtension SpringExtProvider = new SpringExtension();
@Override
public SpringExt createExtension(ExtendedActorSystem system) {
return new SpringExt();
}
public static class SpringExt implements Extension {
private volatile ApplicationContext applicationContext;
public void initialize(ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
}
public Props props(String actorBeanName) {
return Props.create(SpringActorProducer.class, applicationContext, actorBeanName);
}
}
}
public class SpringActorProducer implements IndirectActorProducer {
final private ApplicationContext applicationContext;
final private String actorBeanName;
public SpringActorProducer(ApplicationContext applicationContext, String actorBeanName) {
this.applicationContext = applicationContext;
this.actorBeanName = actorBeanName;
}
@Override
public Actor produce() {
return (Actor) applicationContext.getBean(actorBeanName);
}
@Override
public Class extends Actor> actorClass() {
return (Class extends Actor>) applicationContext.getType(actorBeanName);
}
}
akka config
@Configuration
public class AkkaConfig {
@Autowired
private ApplicationContext applicationContext;
@Bean
public ActorSystem actorSystem() {
ActorSystem actorSystem = ActorSystem.create("ActorSystem");
SpringExtProvider.get(actorSystem).initialize(applicationContext);
return actorSystem;
}
@Bean
public Config akkaConfiguration() {
return ConfigFactory.load();
}
}
actor
workerActor
@Component("workerActor")
@Scope("prototype")
public class WorkerActor extends UntypedActor {
@Autowired
ActorSystem actorSystem;
@Override
public void onReceive(Object message) throws Exception {
if (message instanceof AkkaReq) {
System.out.println("receive req:"+((AkkaReq) message).getData());
Thread.sleep(1000);
getSender().tell(new AkkaResp(((AkkaReq) message).getData()), getSelf());
//getContext().stop(getSelf());
} else {
unhandled(message);
}
}
}
masterActor
@Component("masterActor")
@Scope("prototype")
public class MasterActor extends UntypedActor {
@Override
public void onReceive(Object message) throws Exception {
if (message instanceof AkkaResp) {
System.out.println("get resp:"+((AkkaResp) message).getData());
} else {
unhandled(message);
}
}
}
运行
ActorRef masterRef = actorSystem.actorOf(SpringExtProvider.get(actorSystem).props("masterActor"),"masterActor");
actorSystem.actorOf(SpringExtProvider.get(actorSystem).props("workerActor"),"workerActor").tell(new AkkaReq("test"), masterRef);
doc