我们更新到netty4.0最终版,但是Channel.id()已经被删除了。
我们需要服务器主动向客户端发送消息,如何找到合适的Channel?我们不直接处理返回给客户端的完成处理程序,而是需要将处理过程转移到另一个服务器然后返回发送给客户端。
之前我们用Channel.id()可以做到,但是Channel.id()已经去掉了,有什么替代方案呢?用channel.hashcode()可以吗?
Github 上出现了一些关于此删除的问题。Norman 表示您可以使用 Channel.hashcode() 但不能保证它是唯一的:
https://github.com/netty/netty/pull/1540
另一个想法是创建一个自定义 ChannelGroup,但这会带来其自身的复杂性,这里简要讨论:
我做了一个简单的计数器:
public class SimpleChannel extends NioSocketChannel {
protected static final AtomicLong nextId = new AtomicLong(0);
protected long id = nextId.getAndIncrement();
public SimpleChannel() {
}
public SimpleChannel(SocketChannel socket) {
super(socket);
}
public SimpleChannel(Channel parent, Integer id, SocketChannel socket) {
super(parent, id, socket);
}
public long getId() {
return id;
}
}
将自定义类设置为 Bootstrap:
EventLoopGroup workerGroup = new NioEventLoopGroup();
Bootstrap clientFactory = new Bootstrap();
clientFactory.group(workerGroup);
clientFactory.channel(SimpleChannel.class);
对于服务器有点困难:
public class SimpleServerChannel extends NioServerSocketChannel {
private static final InternalLogger log = InternalLoggerFactory.getInstance(HttpServerChannel.class);
@Override
protected int doReadMessages(List<Object> buf) throws Exception {
SocketChannel ch = javaChannel().accept();
try {
if (ch != null) {
buf.add(new SimpleChannel(this, ch));
return 1;
}
} catch (Throwable t) {
log.warn("Failed to create a new channel from an accepted socket.", t);
try {
ch.close();
} catch (Throwable t2) {
log.warn("Failed to close a socket.", t2);
}
}
return 0;
}
}
将自定义类设置为 ServerBootstrap:
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workerGroup);
b.channel(SimpleServerChannel.class);