集成到Spring或者java应用程序
集成到Spring应用
集成Akka在Spring应用非常容易,需要在Spring application context加入以下Bean:
<!-- AKKA System Setup -->
<bean id="myActorSystem" class="akka.actor.ActorSystem" factory-method="create" destroy-method="shutdown" scope="singleton">
<constructor-arg value="mySpingAkkaSystem"/>
</bean>
通过这种方式,将创建一个ActorStstem,你可以将它注入到自己的Bean中创建Actor并且发送消息。 注意 destory-method调用的是shutdown方法,当spring容器销毁时,Akka同时关闭。
集成到java Web应用
如果集成到java Web应用,有一点要注意,就是akka的生命周期。你需要创建一个监听来监控应用的销毁。
接下来的例子,Akka system 通过spring(基于springMVX)设置,我们可以获取Akka系统实例,并且关闭当收到contextDestory事件消息:
import akka.actor.ActorSystem;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.support.SpringBeanAutowiringSupport;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
/**
* Manage Akka lifecycle
*/
public class AkkaWebInitializer implements ServletContextListener {
private static final Logger LOG = LoggerFactory.getLogger(AkkaWebInitializer.class);
@Autowired
private ActorSystem system;
@Override
public void contextInitialized(ServletContextEvent servletContextEvent) {
//Get the actor system from the spring context
SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
}
@Override
public void contextDestroyed(ServletContextEvent servletContextEvent) {
if (system != null) {
LOG.info("Killing ActorSystem as a part of web application ctx destruction.");
system.shutdown();
system.awaitTermination(Duration.create(15, TimeUnit.SECONDS));
} else {
LOG.warn("No actor system loaded, yet trying to shut down. Check AppContext config and consider if you need this listener.");
}
}
}
然后将ServletContextListener添加到web.xml
<listener>
<listener-class>com.issa.akka.AkkaWebInitializer</listener-class>
</listener>