com.gateway.connector.tcp.server.TcpServer Maven / Gradle / Ivy
package com.gateway.connector.tcp.server;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.gateway.connector.utils.LicenseUtil;
import com.gateway.connector.utils.ThreadNameFactory;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
public class TcpServer {
private final static Logger logger = LoggerFactory.getLogger(TcpServer.class);
private static final int BIZ_GROUP_SIZE = Runtime.getRuntime().availableProcessors() * 2;
private static final int BIZ_THREAD_SIZE = 4;
private final EventLoopGroup bossGroup = new NioEventLoopGroup(BIZ_GROUP_SIZE,
new ThreadNameFactory(this.getClass().getSimpleName() + " Boss"));
private final EventLoopGroup workerGroup = new NioEventLoopGroup(BIZ_THREAD_SIZE,
new ThreadNameFactory(this.getClass().getSimpleName() + " Worker"));
private boolean isGzip = false;
public boolean isGzip() {
return isGzip;
}
public void setGzip(boolean isGzip) {
this.isGzip = isGzip;
}
public void start(ApiProxy apiProxy, String host, int port) throws Exception {
LicenseUtil.install();
Class clazz = NioServerSocketChannel.class;
// Server 服务启动
ServerBootstrap bootstrap = new ServerBootstrap();
bootstrap.group(bossGroup, workerGroup);
bootstrap.channel(clazz);
bootstrap.childHandler(new ServerChannelInitializer(isGzip, apiProxy));
// 可选参数
bootstrap.option(ChannelOption.SO_REUSEADDR, Boolean.TRUE)
.childOption(ChannelOption.TCP_NODELAY, true)
.childOption(ChannelOption.ALLOCATOR, new PooledByteBufAllocator(false)); // heap buf 's better
// 绑定接口,同步等待成功
logger.info(String.format("start tcp server[%s] at port[%s].", host, port));
ChannelFuture future = bootstrap.bind(host, port).sync();
ChannelFuture channelFuture = future.addListener(new ChannelFutureListener() {
public void operationComplete(ChannelFuture future) throws Exception {
if (future.isSuccess()) {
logger.info("tcp server have success bind to " + port);
} else {
logger.error("tcp server fail bind to " + port);
throw new Exception("tcp server start fail !", future.cause());
}
}
});
}
public void stop() {
logger.info("stop tcp server ...");
// 释放线程池资源
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
logger.info("stop tcp server end.");
}
}