知识卡片

结构图卡

自定义分区器替换路由

理解等级:中级

Partitioner 是消息路由的可替换接口:partition 根据主题、原始及序列化后的键值、集群元数据返回分区号;它继承 Configurable 的 configure,并提供 close 回收资源。默认实现按键哈希或空键轮询分配;书中的 DemoPartitioner 用计数器对全部分区数取模,改写空键分支,并通过 partitioner.class 配置替换默认实现。替换后路由行为取决于自定义实现,不能继续假设空键只去可用分区;这与 [[生产者分区决策路径]] 中的默认规则有别。

结构图: 类图中实线空心箭头表示接口继承,虚线空心箭头表示类实现接口。

classDiagram
    class Configurable {
        <<interface>>
        +configure(Map configs) void
    }
    class Partitioner {
        <<interface>>
        +partition(String topic, Object key, byte[] keyBytes, Object value, byte[] valueBytes, Cluster cluster) int
        +close() void
    }
    class DefaultPartitioner
    class DemoPartitioner
    Configurable <|-- Partitioner
    Partitioner <|.. DefaultPartitioner
    Partitioner <|.. DemoPartitioner
这张卡片看不懂?

已有反馈 · 0 / 10 条

    还没有人提交反馈。

    原书出处

    参考来源

    - 位置:《深入理解Kafka:核心设计与实践原理 2019》第2章《生产者》2.1.4「分区器」(源文件:`_epub-src/OEBPS/Text/chapter3.xhtml`;接口和实现代码截图 `44_2.jpg`、`45_1.jpg`、`45_2.jpg`、`46_1.jpg`、`46_2.jpg`) - 结论依据:原文说明 `DefaultPartitioner` 实现 `Partitioner`,后者继承 `Configurable`,并列出三个方法职责;示例截图显示 `DemoPartitioner` 的空键计数路由及 `partitioner.class` 配置。 - 原始内容:分区器的作用就是为消息分配分区。 Kafka中提供的默认分区器是org.apache.kafka.clients.producer.internals.DefaultPartitioner,它实现了org.apache.kafka.clients.producer.Partitioner接口,这个接口中定义了2个方法……Partitioner 接口还有一个父接口 org.apache.kafka.common.Configurable,这个接口中只有一个方法: Configurable接口中的configure()方法主要用来获取配置信息及初始化数据。