[Netty源碼分析]Netty解碼(一)

解碼過程.png

解碼,即將二進(jìn)制流解碼為ByteBuf然后進(jìn)行業(yè)務(wù)邏輯的處理
Q:解碼器抽象的解碼過程?
Q:拆箱即用的解碼器有哪些?

ByteToMessageDecoder解碼步驟

  1. 累加字節(jié)流

  2. 調(diào)用子類的decode方法進(jìn)行解析

  3. 將解析的ByteBuf向下傳播

  4. 累加字節(jié)流

//ByteToMessageDecoder
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    if (msg instanceof ByteBuf) {
        CodecOutputList out = CodecOutputList.newInstance();
        try {
            ByteBuf data = (ByteBuf) msg;
            first = cumulation == null;
            if (first) {//第一次從IO流讀取數(shù)據(jù)
                cumulation = data;
            } else {
              //cumulator => MERGE_CUMULATOR => ByteToMessageDecoder.Cumulator;
              cumulation = cumulator.cumulate(ctx.alloc(), cumulation, data);//累加器的數(shù)據(jù)和讀取的數(shù)據(jù)累加
            }
            callDecode(ctx, cumulation, out);
        } catch (DecoderException e) {
            throw e;
        } catch (Exception e) {
            throw new DecoderException(e);
        } finally {
            if (cumulation != null && !cumulation.isReadable()) {
                numReads = 0;
                cumulation.release();
                cumulation = null;
            } else if (++ numReads >= discardAfterReads) {
                // We did enough reads already try to discard some bytes so we not risk to see a OOME.
                // See https://github.com/netty/netty/issues/4275
                numReads = 0;
                discardSomeReadBytes();
            }
            int size = out.size();
            decodeWasNull = !out.insertSinceRecycled();
            fireChannelRead(ctx, out, size);//向下傳播
            out.recycle();//對象回收
        }
    } else {
        ctx.fireChannelRead(msg);
    }
}
↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
//ByteToMessageDecoder.Cumulator;
public static final Cumulator MERGE_CUMULATOR = new Cumulator() {
    @Override
    public ByteBuf cumulate(ByteBufAllocator alloc, ByteBuf cumulation, ByteBuf in) {
        final ByteBuf buffer;
        //判斷是否超出可寫最大范圍,超過進(jìn)行擴(kuò)容
        if (cumulation.writerIndex() > cumulation.maxCapacity() - in.readableBytes()
                || cumulation.refCnt() > 1 || cumulation.isReadOnly()) {
            // Expand cumulation (by replace it) when either there is not more room in the buffer
            // or if the refCnt is greater then 1 which may happen when the user use slice().retain() or
            // duplicate().retain() or if its read-only.
            //
            // See:
            // - https://github.com/netty/netty/issues/2327
            // - https://github.com/netty/netty/issues/1764
            buffer = expandCumulation(alloc, cumulation, in.readableBytes());
        } else {
            buffer = cumulation;
        }
        buffer.writeBytes(in);
        in.release();
        return buffer;
    }
};

2. 調(diào)用子類decode方法進(jìn)行解析
protected void callDecode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) {
    try {
        while (in.isReadable()) {
            int outSize = out.size()
            if (outSize > 0) {
                fireChannelRead(ctx, out, outSize);//事件傳播
                out.clear();
                // Check if this handler was removed before continuing with decoding.
                // If it was removed, it is not safe to continue to operate on the buffer.
                //
                // See:
                // - https://github.com/netty/netty/issues/4635
                if (ctx.isRemoved()) {
                    break;
                }
                outSize = 0;
            }
            int oldInputLength = in.readableBytes();
            decodeRemovalReentryProtection(ctx, in, out);
            // Check if this handler was removed before continuing the loop.
            // If it was removed, it is not safe to continue to operate on the buffer.
            //
            // See https://github.com/netty/netty/issues/1664
            if (ctx.isRemoved()) {
                break;
            }
            if (outSize == out.size()) {
                if (oldInputLength == in.readableBytes()) {
                    break;//說明累加器的數(shù)據(jù)不足以拼接成數(shù)據(jù)包
                } else {
                    continue;//說明讀取到對象但是沒有解析到對象
                }
            }
            if (oldInputLength == in.readableBytes()) {
                throw new DecoderException(
                        StringUtil.simpleClassName(getClass()) +
                                ".decode() did not read anything but decoded a message.");
            }
            if (isSingleDecode()) {
                break;
            }
        }
    } catch (DecoderException e) {
        throw e;
    } catch (Exception cause) {
        throw new DecoderException(cause);
    }
}
↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
(待分析,此處和Netty4不同)
final void decodeRemovalReentryProtection(ChannelHandlerContext ctx, ByteBuf in, List<Object> out)
            throws Exception {
    decodeState = STATE_CALLING_CHILD_DECODE;
    try {
        decode(ctx, in, out);
    } finally {
        boolean removePending = decodeState == STATE_HANDLER_REMOVED_PENDING;
        decodeState = STATE_INIT;
        if (removePending) {
            handlerRemoved(ctx);
        }
    }
}

3. 將ByteBuf向下傳播
static void fireChannelRead(ChannelHandlerContext ctx, CodecOutputList msgs, int numElements) {
    for (int i = 0; i < numElements; i ++) {
        ctx.fireChannelRead(msgs.getUnsafe(i));
    }
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末拓挥,一起剝皮案震驚了整個(gè)濱河市谚中,隨后出現(xiàn)的幾起案子描沟,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 217,406評論 6 503
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件荤牍,死亡現(xiàn)場離奇詭異,居然都是意外死亡庆冕,警方通過查閱死者的電腦和手機(jī)康吵,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,732評論 3 393
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來访递,“玉大人晦嵌,你說我怎么就攤上這事。” “怎么了惭载?”我有些...
    開封第一講書人閱讀 163,711評論 0 353
  • 文/不壞的土叔 我叫張陵旱函,是天一觀的道長。 經(jīng)常有香客問我描滔,道長棒妨,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,380評論 1 293
  • 正文 為了忘掉前任含长,我火速辦了婚禮券腔,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘茎芋。我一直安慰自己颅眶,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,432評論 6 392
  • 文/花漫 我一把揭開白布田弥。 她就那樣靜靜地躺著涛酗,像睡著了一般。 火紅的嫁衣襯著肌膚如雪偷厦。 梳的紋絲不亂的頭發(fā)上商叹,一...
    開封第一講書人閱讀 51,301評論 1 301
  • 那天,我揣著相機(jī)與錄音只泼,去河邊找鬼剖笙。 笑死,一個(gè)胖子當(dāng)著我的面吹牛请唱,可吹牛的內(nèi)容都是我干的弥咪。 我是一名探鬼主播,決...
    沈念sama閱讀 40,145評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼十绑,長吁一口氣:“原來是場噩夢啊……” “哼聚至!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起本橙,我...
    開封第一講書人閱讀 39,008評論 0 276
  • 序言:老撾萬榮一對情侶失蹤扳躬,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后甚亭,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體贷币,經(jīng)...
    沈念sama閱讀 45,443評論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,649評論 3 334
  • 正文 我和宋清朗相戀三年亏狰,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了役纹。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 39,795評論 1 347
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡暇唾,死狀恐怖字管,靈堂內(nèi)的尸體忽然破棺而出啰挪,到底是詐尸還是另有隱情,我是刑警寧澤嘲叔,帶...
    沈念sama閱讀 35,501評論 5 345
  • 正文 年R本政府宣布亡呵,位于F島的核電站,受9級特大地震影響硫戈,放射性物質(zhì)發(fā)生泄漏锰什。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,119評論 3 328
  • 文/蒙蒙 一丁逝、第九天 我趴在偏房一處隱蔽的房頂上張望汁胆。 院中可真熱鬧,春花似錦霜幼、人聲如沸嫩码。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,731評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽铸题。三九已至,卻和暖如春琢感,著一層夾襖步出監(jiān)牢的瞬間丢间,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,865評論 1 269
  • 我被黑心中介騙來泰國打工驹针, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留烘挫,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 47,899評論 2 370
  • 正文 我出身青樓柬甥,卻偏偏與公主長得像饮六,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個(gè)殘疾皇子苛蒲,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,724評論 2 354

推薦閱讀更多精彩內(nèi)容