Objective
In the springboot load Netty, I think it's good to start a netty by thread alone. Later, because of changes in work habits, more and more rely on AOP, SOA, feel springboot management Netty after, actually also good, because very little on Netty operation Orm, the only kind of like is based on AOP log.
Entrance
Before I write a netty server, I will let him implements Runnable/callable, then write to thread inside start. Now look at Springboot how to load Netty.
First write the Netty server annotated, defined as service
@Service
public class Websocketserver {
@PostConstruct
public void init () {
Service initialization code here
}
@PreDestroy
public void Destroy () {
...
}
This is the typical bean definition format. If you want to specify a parameter, such as a listening port, the init () method loads from the resource file with the spring template, which is not discussed here.
@PreDestroy part write the destruction code, such as connection pool destroy, monitor runloop destroy
public void Destroy () {
if (Bossloop!=null) {
Bossloop.shutdowngracefully ();
}
if (Workerloop!=null) {
Workerloop.shutdowngracefully ();
}
}
External Springboot
@SpringBootApplication
public class APP implements Commandlinerunner, Applicationcontextaware {
@Resource
Private Websocketserver WSServer; Inject Nettyserver
Public staticvoid Main (string[] args) {
Springapplication.run (App.class,args); Start Springboot, run this line of code before starting bean injection
}}
"Non-bean-initiated services"
In Springboot, our App class can also specifically specify the portal for the service, using the overridden Run method
@Override
public void Run (String...args) throws Exception {
Etcdutil.regist ();
Runtime.getruntime (). Addshutdownhook (New Thread () {
@Override
public void Run () {
Etcdutil.destroy ();
}
});
}
"Normal Java class instance fetch Bean"
I recommend implementing the Applicationcontextaware interface, because in Netty, many instances are less convenient as component, such as handler. So in these handler want to load the bean, need to use the ApplicationContext getbean ability. Therefore, in the Portal class app, it is recommended that the context load be implemented.
private static ApplicationContext ApplicationContext;
@SuppressWarnings ("Static-access")
@Override
public void Setapplicationcontext (Applicationcontextapplicationcontext) throws Beansexception {
This.applicationcontext =applicationcontext;
}
public static <T> T Getbean (class<t>clazz) {
Return Applicationcontext.getbean (Clazz);
This allows you to get the bean through the Getbean method
Destruction
It's not a problem to press the action above, but sometimes it's possible to connect other things besides Netty, such as Etcd,jedis before. So we need a portal to destroy the resources. Still inside the app class.