一 概述
Bootstrap 是 Netty 提供的一个便利的工厂类,可以通过它来完成 Netty 的客户端或服务器端的 Netty 初始化。
- 服务端是ServerBootstrap
- 客户端是Bootstrap
二 启动过程
private EventLoopGroup boss = new NioEventLoopGroup();
private EventLoopGroup work = new NioEventLoopGroup();
@Value("${cim.server.port}")
private int nettyPort;
/**
* 启动 cim server
*
* @return
* @throws InterruptedException
*/
@PostConstruct
public void start() throws InterruptedException {
ServerBootstrap bootstrap = new ServerBootstrap()
.group(boss, work) // step1
.channel(NioServerSocketChannel.class) // step2
.localAddress(new InetSocketAddress(nettyPort)) // step3
//保持长连接
.childOption(ChannelOption.SO_KEEPALIVE, true) // step4
.childHandler(new CIMServerInitializer()); // step5
ChannelFuture future = bootstrap.bind().sync(); // step6
if (future.isSuccess()) {
LOGGER.info("启动 cim server 成功");
}
}
step1 设置reactor线程组
在设置 reactor 反应器线程组之前,创建了两个 NioEventLoopGroup 线程组:
- boss 表示服务器连接监听线程组,专门接受 accept 新的客户端client 连接
- work 表示处理每一条连接的数据收发的线程组
step2 设置通道的IO类型
IO类型可以选择BIO和NIO,这里我们一般都是NIO
step3 设置监听端口
step4 给每条child channel 连接设置一些TCP底层相关的属性
上面的例子是保持长连接
step5 装配流水线
public class CIMServerInitializer extends ChannelInitializer<Channel> {
private final CIMServerHandle cimServerHandle = new CIMServerHandle() ;
@Override
protected void initChannel(Channel ch) throws Exception {
ch.pipeline()
//11 秒没有向客户端发送消息就发生心跳
.addLast(new IdleStateHandler(11, 0, 0))
// google Protobuf 编解码
.addLast(new ProtobufVarint32FrameDecoder())
.addLast(new ProtobufDecoder(CIMRequestProto.CIMReqProtocol.getDefaultInstance()))
.addLast(new ProtobufVarint32LengthFieldPrepender())
.addLast(new ProtobufEncoder())
.addLast(cimServerHandle);
}
}
step6 开始绑定server
ChannelFuture future = bootstrap.bind().sync(); // step6
三 销毁过程
boss.shutdownGracefully().syncUninterruptibly();
work.shutdownGracefully().syncUninterruptibly();