如何使用netty中的SimpleChannelPool在连接错误时关闭通道?

问题描述 投票:0回答:1

我正在尝试在netty中使用连接池,但是在编写一些错误处理时遇到了问题。我的原始代码如下所示:

ChannelFuture connectFuture = bootstrap.connect(...);
connectFuture.addListener(ChannelFutureListener.CLOSE_ON_FAILURE);

但是,ChannelPool.acquire返回Future<Channel>。这意味着在操作失败时,无法访问该通道,因此我不知道关闭该通道的方法。关闭失败的频道重要吗?我认为即使它无法连接,它仍然可以保留一些系统资源。

我认为相关代码在SimpleChannelPool中的netty类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());
        }
    }

在这里,我们可以看到返回给调用方的诺言失败,但是通道没有传播。

java netty
1个回答
0
投票

这非常简单,您只需要重写SimpleChannelPool.connectChannel()`并在其中添加侦听器。

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.