【问题标题】:How to set maximum concurrent connections with netty如何使用 netty 设置最大并发连接数
【发布时间】:2017-10-23 18:40:07
【问题描述】:

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

谢谢

【问题讨论】:

标签: java netty


【解决方案1】:

您不能配置 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&lt;ChannelId, Channel&gt;。所以你可以像ConnectionCounter handler一样实现它。

【讨论】:

    【解决方案2】:

    最简单的方法是编写您自己的处理程序,以静态整数对连接的客户端进行计数。

    类似这样的:

    import io.netty.channel.ChannelHandler.Sharable;
    import io.netty.channel.ChannelHandlerContext;
    import io.netty.channel.ChannelInboundHandlerAdapter;
    
    @Sharable
    public class ConnectionCounter extends ChannelInboundHandlerAdapter {
    
        private static int connections = 0;
    
        @Override
        public void channelActive(ChannelHandlerContext ctx) throws Exception {
            if(connections < 4) {
                connections++;
                super.channelActive(ctx);
            } else
                ctx.close();
        }
    
        @Override
        public void channelInactive(ChannelHandlerContext ctx) throws Exception {
            super.channelInactive(ctx);
            connections--;
        }
    }
    

    编辑

    您应该记住,您必须使用一个线程,否则可能会导致一些问题(竞争条件)。如果必须使用多线程,请将 int 更改为 AtomicInteger 或在静态 int 上使用 synchronized 关键字。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-03-30
      • 2013-09-29
      • 1970-01-01
      • 1970-01-01
      • 2013-01-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多