Netty統(tǒng)計(jì)連接數(shù)

Netty統(tǒng)計(jì)連接數(shù)

思路

netty如何統(tǒng)計(jì)當(dāng)前的連接數(shù)?
當(dāng)有連接接入netty server的時(shí)候,ChannelInboundHandlerAdapter中就會調(diào)用regiser和active方法。我們只需要在這里對計(jì)數(shù)器遞增即可。
同時(shí)當(dāng)有連接斷開(客戶端程序手動斷開的時(shí)候,客戶端異常斷開不會完成四次揮手,服務(wù)端沒法立刻判斷客戶端是否離開), ChannelInboundHandlerAdapter中會調(diào)用unregisert和inactive方法,我們需要在這里對計(jì)數(shù)器進(jìn)行遞減即可。

注意點(diǎn)

1 例子中的NettyConnectServerHandler不是sharedable的,每次都需要new來創(chuàng)建。
所以統(tǒng)計(jì)的變量應(yīng)該是傳入的參數(shù)。
2 保證多線程的時(shí)候統(tǒng)計(jì)變量不會出現(xiàn)問題,使用AtomicInteger來保證。

核心代碼

public class NettyConnectServerHandler extends ChannelInboundHandlerAdapter {
    private AtomicInteger connectNum;

    public NettyConnectServerHandler(AtomicInteger connectNum) {
        this.connectNum = connectNum;
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        ByteBuf in = (ByteBuf) msg;
        try {
            while (in.isReadable()) { // (1)
                System.out.print((char) in.readByte());
                System.out.flush();
            }
        } finally {
            ReferenceCountUtil.release(msg); // (2)
        }
    }

    @Override
    public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
        super.channelRegistered(ctx);
        if (connectNum.incrementAndGet() % 100 == 0) {
            System.out.println("current connected" + connectNum.get());
        }
    }

    @Override
    public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
        super.channelUnregistered(ctx);
        if (connectNum.decrementAndGet() % 100 == 0) {
            System.out.println("current connected" + connectNum.get());
        }
    }

}

git地址

https://github.com/destinym/nettyconnect.git
count模塊

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,536評論 19 139
  • 1.ios高性能編程 (1).內(nèi)層 最小的內(nèi)層平均值和峰值(2).耗電量 高效的算法和數(shù)據(jù)結(jié)構(gòu)(3).初始化時(shí)...
    歐辰_OSR閱讀 30,215評論 8 265
  • Spring Web MVC Spring Web MVC 是包含在 Spring 框架中的 Web 框架,建立于...
    Hsinwong閱讀 22,939評論 1 92
  • 可否使用 == 來判斷兩個(gè)NSString類型的字符串是否相同?為什么? 不能。==判斷的是兩個(gè)變量的值的內(nèi)存地址...
    漸z閱讀 670評論 0 0
  • 時(shí)間:2017-03-27 18:02:47 該文章為 《HTML5緩存機(jī)制淺析:移動端Web加載性能優(yōu)化》 ...
    izhongxia閱讀 705評論 0 1

友情鏈接更多精彩內(nèi)容