已经大概完成了一个Rpc项目
代理 注册中心 序列化 通信都完成了
开始优化
public class NettyRpcServer {
private int port;
public void start(Object serviceImpl,int port1){
this.port=port1;
EventLoopGroup boss=new NioEventLoopGroup();
EventLoopGroup worker =new NioEventLoopGroup();
ServerBootstrap b= new ServerBootstrap();
b.group(boss,worker)
.channel(NioServerSocketChannel.class)
// TCP默认开启了 Nagle 算法,该算法的作用是尽可能的发送大数据快,减少网络传输。TCP_NODELAY 参数的作用就是控制是否启用 Nagle 算法。
.childOption(ChannelOption.TCP_NODELAY, true)
// 是否开启 TCP 底层心跳机制
.childOption(ChannelOption.SO_KEEPALIVE, true)
//表示系统用于临时存放已完成三次握手的请求的队列的最大长度,如果连接建立频繁,服务器处理创建新连接较慢,可以适当调大这个参数
.option(ChannelOption.SO_BACKLOG, 128)
.handler(new LoggingHandler(LogLevel.INFO))
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
ChannelPipeline channelPipeline=socketChannel.pipeline();
channelPipeline.addLast(new IdleStateHandler(30,0,0, TimeUnit.SECONDS));
channelPipeline.addLast(new RpcEncoder());
channelPipeline.addLast(new RpcDecoder());
channelPipeline.addLast(new RpcServerHandler(serviceImpl));
}
});
try {
ChannelFuture channelFuture=b.bind(port).sync();
channelFuture.channel().closeFuture().sync();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
boss.shutdownGracefully();
worker.shutdownGracefully();
}
}
}
这里的 channelFuture.channel().closeFuture().sync();是同步阻塞的方式来退出,不符合Netty理念
更改为 `
channelFuture.channel().closeFuture().addListener(new channelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
log.info("准备关闭"+channelFuture.channel().toString());
boss.shutdownGracefully();
worker.shutdownGracefully();
}
});
`
****异步地关闭