netty自定义channel id、自定义服务端id、netty custom channel id
netty自定义channel id、自定义服务端id、netty custom channel id
netty自定义channel id、自定义服务端id、netty custom id
netty自定义channel id、自定义服务端id、netty custom channel id
自定义服务端id、netty自定义channel id
通过上篇文章,https://blog.csdn.net/weixin_44480167/article/details/126304030
知道创建连接时的工厂类是
同理,服务端的生成id与此工厂类有关:如果你直接重写newId是无效的
通过断点发现是从此处生成的ID:io.netty.channel.socket.nio.NioServerSocketChannel
于是我们继承NioSocketChannel并重写实现ID生成
public class FinalServerNioSocketChannel extends NioSocketChannel {
public FinalServerNioSocketChannel(Channel parent, SocketChannel socket) {
super(parent, socket);
}
// 自定义ID
@Override
protected ChannelId newId() {
return new ChannelId() {
private String id = IdUtil.objectId();
@Override
public String asShortText() {
return id;
}
@Override
public String asLongText() {
return id;
}
@Override
public int compareTo(ChannelId o) {
return id.equals(o.asLongText()) ? 1 : 0;
}
};
}
}
同时重写NioServerSocketChannel类
public class FinalServerNioServerSocketChannel extends NioServerSocketChannel {
private static final Logger logger=LoggerFactory.getLogger(FinalServerNioServerSocketChannel.class);
@Override
protected int doReadMessages(List<Object> buf) throws Exception {
SocketChannel ch = SocketUtils.accept(javaChannel());
try {
if (ch != null) {
// 此处重写ID
NioSocketChannel nioSocketChannel = new FinalServerNioSocketChannel(this, ch);
buf.add(nioSocketChannel);
return 1;
}
} catch (Throwable t) {
logger.warn("Failed to create a new channel from an accepted socket.", t);
try {
ch.close();
} catch (Throwable t2) {
logger.warn("Failed to close a socket.", t2);
}
}
return 0;
}
}
启动类
ServerBootstrap serverBootstrap = new ServerBootstrap();
serverBootstrap.group(mainGroup, subGroup) //设置主从线程
.channel(FinalServerNioServerSocketChannel.class) // 设置nio的双向管道
//当连接被阻塞时BACKLOG代表的是阻塞队列的长度
.option(ChannelOption.SO_BACKLOG, 256)
//置连接为保持活动的状态
.childOption(ChannelOption.SO_KEEPALIVE, true);
// 子处理器
serverBootstrap.childHandler(new ServerInitializer(applicationContext));
效果