netty如何设置最大并发连接数

Pap*_*aya 2 java netty

我从 Netty 库开始,想将我的服务器上可以连接的客户端数量设置为 4,我该怎么办?

谢谢

Dmi*_*kiy 8

您无法配置 netty 来限制传入连接的数量。但是,您可以在打开超出限制的连接后立即将其关闭。实现这一目标的方法很少。

第一个如上面的示例所示。您需要在管道的开头添加处理程序ConnectionCounter。但是,您需要在检查之前使用而AtomicInteger不是int connections增加计数器(以避免竞争条件问题):

@Sharable
public class ConnectionCounter extends ChannelInboundHandlerAdapter {

private final AtomicInteger connections = new AtomicInteger();

@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
    int val = connections.incrementAndGet();
    if (val <= 4) {
        super.channelActive(ctx);
    } else {
        ctx.close();
    }
}

@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
    super.channelInactive(ctx);
    connections.decrementAndGet();
}
}
Run Code Online (Sandbox Code Playgroud)

PS 请记住,此处理程序是可共享的,您只需创建它的 1 个实例。否则,您需要将connections字段设为静态。

另一种选择是使用单线程EventLoop。正如您所期望的,只有 4 个连接 - 它们可以使用 1 轻松处理EventLoop

new ServerBootstrap().group(bossGroup, new EpollEventLoopGroup(1));
Run Code Online (Sandbox Code Playgroud)

因此,您只有 1 个工作线程,您可以使用上面的ConnectionCounter处理程序代码,但不使用AtomicInteger.

最后一个选项是 - DefaultChannelGroup。然而,它内部使用ConcurrentMap<ChannelId, Channel>. 所以你可以用与handler相同的方式来实现它ConnectionCounter