栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

源码阅读-Record

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

源码阅读-Record

源码阅读-Record

Kafka消息格式相关的代码位于clients工程下的/java/org/apache/kafka/common/record包下。

类之间的关系图如下所示:

1. DefaultRecord(默认消息)

类中的消息格式定义(org.apache.kafka.common.record.DefaultRecord):

字段说明
sizeInBytes消息总长度字段
attributes消息属性字段
offset位移增量
timestamp时间戳增量
sequence用于支持消息的幂等性
keykey值
valuevalue值
headers消息头部属性

kafka将record组装成buffer进行输出(org.apache.kafka.common.record.DefaultRecord#writeTo):

public static int writeTo(DataOutputStream out,
                          int offsetDelta,
                          long timestampDelta,
                          ByteBuffer key,
                          ByteBuffer value,
                          Header[] headers) throws IOException {
    // 消息总数
    int sizeInBytes = sizeOfBodyInBytes(offsetDelta, timestampDelta, key, value, headers);
    ByteUtils.writeVarint(sizeInBytes, out);

    // 属性
    byte attributes = 0; // there are no used record attributes at the moment
    out.write(attributes);

    // 时间增量
    ByteUtils.writeVarlong(timestampDelta, out);
    // 位移增量
    ByteUtils.writeVarint(offsetDelta, out);

    // key
    if (key == null) {
        ByteUtils.writeVarint(-1, out);
    } else {
        // key size
        int keySize = key.remaining();
        ByteUtils.writeVarint(keySize, out);
        Utils.writeTo(out, key, keySize);
    }

    // value
    if (value == null) {
        ByteUtils.writeVarint(-1, out);
    } else {
        // value size
        int valueSize = value.remaining();
        ByteUtils.writeVarint(valueSize, out);
        Utils.writeTo(out, value, valueSize);
    }

    // headers
    if (headers == null)
        throw new IllegalArgumentException("Headers cannot be null");

    // headers个数
    ByteUtils.writeVarint(headers.length, out);
 
    for (Header header : headers) {
        // header key
        String headerKey = header.key();
        if (headerKey == null)
            throw new IllegalArgumentException("Invalid null header key found in headers");

        byte[] utf8Bytes = Utils.utf8(headerKey);
        // header key length
        ByteUtils.writeVarint(utf8Bytes.length, out);
        out.write(utf8Bytes);

        // header value
        byte[] headerValue = header.value();
        if (headerValue == null) {
            ByteUtils.writeVarint(-1, out);
        } else {
            // header value length
            ByteUtils.writeVarint(headerValue.length, out);
            out.write(headerValue);
        }
    }

    return ByteUtils.sizeOfVarint(sizeInBytes) + sizeInBytes;
}

消息格式可以用如下表示:

2. DefaultRecordBatch(默认消息集合)

类中的消息集合格式的定义(org.apache.kafka.common.record.DefaultRecordBatch):

消息批次格式可以用如下表示:

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/532243.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号