3

获得与服务器的许多活动连接是真的吗?我写了一个简单的 http 服务器,我需要知道他有多少活动连接。

我试过了,但在 10000 次请求后它给了我错误的结果

@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
    super.channelInactive(ctx);
    StatusData.decreaseConnectionCounter();
}
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
    super.channelActive(ctx);
    log.info("Channel " + ctx.channel() + " is now active");
    StatusData.increaseConnectionCounter();
}

我更改了我的类,所以它看起来像这个 StatusData,当我在 100 个线程中生成 10000 个请求时,它的计数是正确的。

class StatusData{

private AtomicInteger counter = new AtomicInteger();

    public void increaseConnectionCounter() {
        synchronized (counter){
        int newValue = counter.intValue() + 1;
        counter.set(newValue);
        }
    }

    public void decreaseConnectionCounter() {
        synchronized (counter){
        int newValue = counter.intValue() - 1;
        counter.set(newValue);
        }
    }

    public int getActiveConnectionCounter() {
        return counter.get();
    }
}   
4

1 回答 1

1

您的解决方案看起来正确。这很可能是 StatusData 中的错误,例如不使用 AtomicLong。

于 2013-10-22T04:25:55.260 回答