我从 Netty 库开始,想将我的服务器上可以连接的客户端数量设置为 4,我该怎么做?
谢谢
最佳答案
您无法配置 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();
}
}
P。 S. 请记住,此处理程序是可共享的,您只需创建它的 1 个实例。否则,您需要制作 connections
字段静态。
另一种选择是使用单线程 EventLoop
。正如您所期望的,只有 4 个连接 - 它们可以通过 1 EventLoop
轻松处理。 :
new ServerBootstrap().group(bossGroup, new EpollEventLoopGroup(1));
因此,您只有 1 个可以在上面使用的工作线程 ConnectionCounter
处理程序代码但没有 AtomicInteger
.
最后一个选项是 - DefaultChannelGroup
。然而,它内部使用 ConcurrentMap<ChannelId, Channel>
。所以可以像 ConnectionCounter
一样实现处理程序。
关于java - netty如何设置最大并发连接数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46849964/