如何在 netty 中使用 SimpleChannelPool 在连接错误时关闭通道?
How can the channel be closed on connection error using SimpleChannelPool in netty?
我正在尝试在 netty 中使用连接池,但我在编写一些错误处理时遇到了问题。我的原始代码如下所示:
ChannelFuture connectFuture = bootstrap.connect(...);
connectFuture.addListener(ChannelFutureListener.CLOSE_ON_FAILURE);
不过,ChannelPool.acquire
returns一个Future<Channel>
。这意味着在操作失败时,无法访问该频道,所以我不知道关闭它的方法。关闭失败的通道很重要吗?我假设它可能仍然占用一些系统资源,即使它无法连接。
我觉得相关代码在nettyclassSimpleChannelPool
中notifyConnect
:
private void notifyConnect(ChannelFuture future, Promise<Channel> promise) throws Exception {
if (future.isSuccess()) {
Channel channel = future.channel();
handler.channelAcquired(channel);
if (!promise.trySuccess(channel)) {
// Promise was completed in the meantime (like cancelled), just release the channel again
release(channel);
}
} else {
promise.tryFailure(future.cause());
}
}
在这里我们可以看到返回给调用者的承诺失败了,但是通道没有传播。
这最终变得非常简单,您只需要重写 SimpleChannelPool.connectChannel()` 并在其中添加侦听器。
我正在尝试在 netty 中使用连接池,但我在编写一些错误处理时遇到了问题。我的原始代码如下所示:
ChannelFuture connectFuture = bootstrap.connect(...);
connectFuture.addListener(ChannelFutureListener.CLOSE_ON_FAILURE);
不过,ChannelPool.acquire
returns一个Future<Channel>
。这意味着在操作失败时,无法访问该频道,所以我不知道关闭它的方法。关闭失败的通道很重要吗?我假设它可能仍然占用一些系统资源,即使它无法连接。
我觉得相关代码在nettyclassSimpleChannelPool
中notifyConnect
:
private void notifyConnect(ChannelFuture future, Promise<Channel> promise) throws Exception {
if (future.isSuccess()) {
Channel channel = future.channel();
handler.channelAcquired(channel);
if (!promise.trySuccess(channel)) {
// Promise was completed in the meantime (like cancelled), just release the channel again
release(channel);
}
} else {
promise.tryFailure(future.cause());
}
}
在这里我们可以看到返回给调用者的承诺失败了,但是通道没有传播。
这最终变得非常简单,您只需要重写 SimpleChannelPool.connectChannel()` 并在其中添加侦听器。