作者 crossoverJie

:sparkles: Introducing new features.优化启动

package com.crossoverjie.netty.action;
import com.crossoverjie.netty.action.server.HeartBeatServer;
import io.netty.channel.ChannelFuture;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
... ... @@ -16,6 +17,8 @@ public class Application implements CommandLineRunner{
private final static Logger LOGGER = LoggerFactory.getLogger(Application.class);
@Autowired
private HeartBeatServer heartBeatServer ;
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
... ... @@ -24,6 +27,15 @@ public class Application implements CommandLineRunner{
@Override
public void run(String... args) throws Exception {
ChannelFuture future = heartBeatServer.start();
Runtime.getRuntime().addShutdownHook(new Thread(){
@Override
public void run() {
heartBeatServer.destroy();
}
});
future.channel().closeFuture().syncUninterruptibly() ;
}
}
\ No newline at end of file
... ...
... ... @@ -12,6 +12,7 @@ import io.netty.handler.timeout.IdleStateHandler;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import java.net.InetSocketAddress;
... ... @@ -22,30 +23,36 @@ import java.net.InetSocketAddress;
* Date: 21/05/2018 00:30
* @since JDK 1.8
*/
@Configuration
@Component
public class HeartBeatServer {
@Bean
public ChannelFuture buildFuture() {
private EventLoopGroup boss = new NioEventLoopGroup();
private EventLoopGroup work = new NioEventLoopGroup();
EventLoopGroup boss = new NioEventLoopGroup();
EventLoopGroup work = new NioEventLoopGroup();
try {
/**
* 启动 Netty
* @return
* @throws InterruptedException
*/
public ChannelFuture start() throws InterruptedException {
ServerBootstrap bootstrap = new ServerBootstrap()
.group(boss, work)
.channel(NioServerSocketChannel.class)
.localAddress(new InetSocketAddress(11211))
.childHandler(new HeartbeatInitializer());
ServerBootstrap bootstrap = new ServerBootstrap()
.group(boss, work)
.channel(NioServerSocketChannel.class)
.localAddress(new InetSocketAddress(11211))
.childHandler(new HeartbeatInitializer());
ChannelFuture future = bootstrap.bind().sync();
return future;
}
ChannelFuture future = bootstrap.bind().sync();
future.channel().closeFuture().sync();
return future;
} catch (InterruptedException e) {
} finally {
}
return null;
/**
* 销毁
*/
public void destroy(){
boss.shutdownGracefully() ;
work.shutdownGracefully() ;
}
}
... ...