<
您正在查看旧版 Kafka 的文档 - 在此处查看我们的当前文档。

文档

Kafka 3.5 文档

早期版本: 0.7.x0.8.00.8.1.X0.8.2.X0.9.0.X0.10.0.X0.10.1.X0.10.2.X0.11.0.X1.0.X1.1.X2.0.X2.1.X2.2.X2.3.X2.4.X2.5.X2.6.X2.7.X2.8.X3.0.X3.1.X3.2.X3.3.X3.4.X

1. 开始使用

1.1 介绍

什么是事件流式处理?

事件流是人体中枢神经系统的数字等价物。它是 为“永远在线”的世界奠定技术基础,在这个世界里,企业越来越多地使用软件定义 和 automated,而软件的用户更多的是 Software。

从技术上讲,事件流式处理是从事件源实时捕获数据的做法 如数据库、传感器、移动设备、云服务和流形式的软件应用程序 事件;持久存储这些事件流以供以后检索;作、处理和反应 实时和回顾性地访问事件流;并将事件流路由到不同的 destination 技术。因此,事件流确保了 数据,以便在正确的时间、正确的地点提供正确的信息。

事件流式处理可以用于什么?

事件流适用于众多行业和组织的各种使用案例。它的许多示例包括:

  • 实时处理付款和金融交易,例如在证券交易所、银行和保险中。
  • 实时跟踪和监控汽车、卡车、车队和货物,例如物流和汽车行业。
  • 持续捕获和分析来自 IoT 设备或其他设备(例如工厂和风电场)的传感器数据。
  • 收集客户互动和订单并立即做出反应,例如在零售、酒店和旅游行业以及移动应用程序中。
  • 监测住院护理的患者并预测病情变化,以确保在紧急情况下得到及时治疗。
  • 连接、存储和提供公司不同部门生成的数据。
  • 作为数据平台、事件驱动型架构和微服务的基础。

Apache Kafka® 是一个事件流式处理平台。那是什么意思?

Kafka 结合了三个关键功能,因此您可以使用单个久经考验的解决方案实现端到端事件流的使用案例

  1. 发布(写入)和订阅(读取)事件流,包括连续导入/导出 来自其他系统的数据。
  2. 根据需要持久可靠地存储事件流。
  3. 在事件发生时或回顾性地处理事件流。

所有这些功能都以分布式、高度可扩展、弹性、容错和 安全的方式。Kafka 可以部署在裸机硬件、虚拟机和容器上,也可以部署在本地 以及在云中。您可以选择自行管理 Kafka 环境和使用完全托管式 由各种供应商提供的服务。

简而言之,Kafka 是如何工作的?

Kafka 是一个分布式系统,由服务器和客户端组成,这些服务器客户端 通过高性能 TCP 网络协议进行通信。 它可以部署在本地和云中的裸机硬件、虚拟机和容器上 环境。

服务器:Kafka 作为一个或多个服务器的集群运行,这些服务器可以跨越多个数据中心 或云区域。其中一些服务器构成了存储层,称为代理。其他服务器运行 Kafka Connect 以持续导入和导出 数据作为事件流,以将 Kafka 与现有系统(如关系数据库)集成,以及 其他 Kafka 集群。为了让您实施任务关键型使用案例,Kafka 集群具有高度可扩展性 和容错:如果它的任何服务器出现故障,其他服务器将接管它们的工作以确保 连续运行,不会丢失任何数据。

客户端:它们允许您编写分布式应用程序和微服务,这些应用程序以及读取、写入、 并行、大规模和以容错方式处理事件流,即使在网络的情况下也是如此 问题或机器故障。Kafka 附带了一些这样的客户端,这些客户端由 Kafka 提供的数十个客户端进行增强 社区:客户端可用于 Java 和 Scala,包括更高级别的 Kafka Streams 库、Go、Python、C/C++ 和 许多其他编程语言以及 REST API。

主要概念和术语

事件记录了世界上或您的企业中 “发生了什么” 的事实。在文档中也称为 record 或 message。当您向 Kafka 读取或写入数据时,您以事件的形式执行此作。从概念上讲,事件具有键、值、时间戳和可选的元数据标头。下面是一个示例事件:

  • 事件键:“Alice”
  • 事件价值:“已向 Bob 支付 200 美元”
  • 事件时间戳:“2020 年 6 月 25 日下午 2:06。

创建者是将事件发布(写入)到 Kafka 的客户端应用程序,而使用者是订阅(读取和处理)这些事件的客户端应用程序。在 Kafka 中,生产者和使用者完全解耦且彼此不可知,这是实现 Kafka 众所周知的高可扩展性的关键设计元素。例如,生产者永远不需要等待消费者。Kafka 提供各种保证,例如能够精确处理一次事件。

事件被组织并持久存储在主题中。非常简单,主题类似于文件系统中的文件夹,事件是该文件夹中的文件。示例主题名称可以是 “payments”。Kafka 中的主题始终是多创建者和多订阅者:一个主题可以有零个、一个或多个向其写入事件的创建者,以及订阅这些事件的零个、一个或多个使用者。可以根据需要随时读取主题中的事件 - 与传统消息传递系统不同,事件在使用后不会删除。相反,您可以通过每个主题的配置设置定义 Kafka 应将事件保留多长时间,之后将丢弃旧事件。Kafka 的性能在数据大小方面实际上是恒定的,因此长时间存储数据是完全可以的。

主题是分区的,这意味着主题分布在位于不同 Kafka 代理上的多个“存储桶”中。这种分布式数据放置对于可伸缩性非常重要,因为它允许客户端应用程序同时从多个代理读取和写入数据。当新事件发布到主题时,它实际上会附加到主题的某个分区中。具有相同事件键的事件(例如,客户或车辆 ID)将写入同一分区,Kafka 保证给定主题分区的任何使用者将始终以与写入事件完全相同的顺序读取该分区的事件。

图:此示例主题有四个分区 P1–P4。两个不同的生产者客户端正在发布 通过网络将事件写入主题的 分区。具有相同键的事件(由它们在图中的颜色表示)将写入相同的 分区。请注意,如果合适,两个 producer 都可以写入同一个分区。

为了使您的数据具有容错性和高可用性,每个主题都可以复制,甚至可以跨地理区域或数据中心复制,以便始终有多个代理拥有数据副本,以防万一出现问题,您想对代理进行维护,等等。常见的生产设置是复制因子 3,即数据始终有三个副本。此复制在 topic-partitions 级别执行。

这本引物应该足以作为介绍。如果您感兴趣,文档的 Design 部分详细介绍了 Kafka 的各种概念。

Kafka API 接口

除了用于管理和管理任务的命令行工具外,Kafka 还具有适用于 Java 和 Scala 的五个核心 API:

  • 用于管理和检查主题、代理和其他 Kafka 对象的 Admin API
  • 生产者 API,用于将事件流发布(写入)到一个或多个 Kafka 主题。
  • Consumer API,用于订阅(读取)一个或多个主题并处理向它们生成的事件流。
  • Kafka Streams API,用于实施流处理应用程序和微服务。它提供更高级别的函数来处理事件流,包括转换、聚合和联接等有状态作、窗口化、基于事件时间的处理等。从一个或多个主题中读取输入,以便生成对一个或多个主题的输出,从而有效地将输入流转换为输出流。
  • Kafka Connect API,用于构建和运行可重用的数据导入/导出连接器,这些连接器使用(读取)或生成(写入)来自外部系统和应用程序的事件流,以便它们可以与 Kafka 集成。例如,指向关系数据库(如 PostgreSQL)的连接器可能会捕获对一组表的每次更改。但是,在实践中,您通常不需要实施自己的连接器,因为 Kafka 社区已经提供了数百个现成的连接器。

从这里去哪里

1.2 使用案例

以下是 Apache Kafka® 的一些常见使用案例的描述。 有关其中许多领域的实际应用概述,请参阅此博客文章

消息

Kafka 可以很好地替代更传统的消息代理。 使用消息代理的原因有很多(将处理与数据创建者分离、缓冲未处理的消息等)。 与大多数消息传递系统相比,Kafka 具有更好的吞吐量、内置分区、复制和容错功能,这使其成为一个很好的 适用于大规模消息处理应用程序的解决方案。

根据我们的经验,消息传递用途通常吞吐量相对较低,但可能需要较低的端到端延迟,并且通常依赖于强大的 Kafka 提供的持久性保证。

在这个领域,Kafka 可与 ActiveMQRabbitMQ 等传统消息传递系统相媲美。

网站活动跟踪

Kafka 的原始用例是能够将用户活动跟踪管道重建为一组实时发布-订阅源。 这意味着网站活动(页面查看、搜索或用户可能执行的其他作)将发布到中心主题,每个活动类型一个主题。 这些订阅源可用于一系列使用案例,包括实时处理、实时监控和加载到 Hadoop 或 用于离线处理和报告的离线数据仓库系统。

活动跟踪通常非常高,因为每个用户页面视图都会生成许多活动消息。

指标

Kafka 通常用于运营监控数据。 这涉及聚合来自分布式应用程序的统计数据,以生成运营数据的集中源。

日志聚合

许多人使用 Kafka 作为日志聚合解决方案的替代品。 日志聚合通常从服务器收集物理日志文件,并将它们放在一个中心位置(可能是文件服务器或 HDFS)进行处理。 Kafka 抽象出文件的详细信息,并将日志或事件数据更清晰地抽象为消息流。 这允许更低的处理延迟,并更轻松地支持多个数据源和分布式数据使用。 与 Scribe 或 Flume 等以日志为中心的系统相比,Kafka 提供了同样好的性能、更强的持久性保证(由于复制)、 以及更低的端到端延迟。

流处理

Kafka 的许多用户在由多个阶段组成的处理管道中处理数据,其中原始输入数据从 Kafka 主题中使用,然后 聚合、丰富或以其他方式转换为新主题以供进一步使用或后续处理。 例如,用于推荐新闻文章的处理管道可能会从 RSS 源中抓取文章内容并将其发布到“文章”主题; 进一步的处理可能会规范化或删除重复的内容,并将清理后的文章内容发布到新主题; 最终处理阶段可能会尝试向用户推荐此内容。 此类处理管道根据各个主题创建实时数据流图。 从 0.10.0.0 开始,Apache Kafka 中提供了一个名为 Kafka Streams 的轻量级但功能强大的流处理库,用于执行上述数据处理。 除了 Kafka Streams,其他开源流处理工具还包括 Apache StormApache Samza

事件溯源

事件溯源是一种应用程序设计风格,其中状态更改被记录为 按时间排序的记录序列。Kafka 对非常大的存储日志数据的支持使其成为以这种样式构建的应用程序的出色后端。

提交日志

Kafka 可以用作分布式系统的一种外部提交日志。日志有助于在节点之间复制数据并充当重新同步 失败节点恢复其数据的机制。 Kafka 中的日志压缩功能有助于支持这种用法。 在这个用法中,Kafka 类似于 Apache BookKeeper 项目。

1.3 快速开始

第 1 步:获取 Kafka

下载最新的 Kafka 版本并提取它:

$ tar -xzf kafka_2.13-3.5.2.tgz
$ cd kafka_2.13-3.5.2

第 2 步:启动 Kafka 环境

注意:您的本地环境必须安装 Java 8+。

Apache Kafka 可以使用 ZooKeeper 或 KRaft 启动。要开始使用任一配置,请遵循以下部分之一,但不能同时执行这两部分。

带有 ZooKeeper 的 Kafka

运行以下命令以按正确顺序启动所有服务:

# Start the ZooKeeper service
$ bin/zookeeper-server-start.sh config/zookeeper.properties

打开另一个终端会话并运行:

# Start the Kafka broker service
$ bin/kafka-server-start.sh config/server.properties

成功启动所有服务后,您将有一个基本的 Kafka 环境运行并可供使用。

带有 KRaft 的 Kafka

生成集群 UUID

$ KAFKA_CLUSTER_ID="$(bin/kafka-storage.sh random-uuid)"

设置日志目录的格式

$ bin/kafka-storage.sh format -t $KAFKA_CLUSTER_ID -c config/kraft/server.properties

启动 Kafka 服务器

$ bin/kafka-server-start.sh config/kraft/server.properties

成功启动 Kafka 服务器后,您将有一个基本的 Kafka 环境运行并可供使用。

第 3 步:创建主题以存储您的事件

Kafka 是一个分布式事件流平台,可让您读取、写入、存储和处理事件(在文档中也称为记录消息) 跨多台机器。

示例事件包括付款交易、手机的地理位置更新、发货订单、传感器测量 来自 IoT 设备或医疗设备等等。这些事件被组织并存储在主题中。 非常简单,主题类似于文件系统中的文件夹,事件是该文件夹中的文件。

因此,在编写第一个事件之前,必须创建一个主题。打开另一个终端会话并运行:

$ bin/kafka-topics.sh --create --topic quickstart-events --bootstrap-server localhost:9092

所有 Kafka 的命令行工具都有额外的选项:运行kafka-topics.sh命令,没有任何 参数来显示使用信息。例如,它还可以显示新主题的分区计数等详细信息

$ bin/kafka-topics.sh --describe --topic quickstart-events --bootstrap-server localhost:9092
Topic: quickstart-events        TopicId: NPmZHyhbR9y00wMglMH2sg PartitionCount: 1       ReplicationFactor: 1	Configs:
    Topic: quickstart-events Partition: 0    Leader: 0   Replicas: 0 Isr: 0

步骤 4:将一些事件写入主题

Kafka 客户端通过网络与 Kafka 代理通信以写入(或读取)事件。 收到事件后,代理将以持久且容错的方式存储事件,只要您 需要——甚至永远。

运行控制台创建者客户端,将一些事件写入您的主题中。 默认情况下,您输入的每一行都会导致将单独的事件写入主题。

$ bin/kafka-console-producer.sh --topic quickstart-events --bootstrap-server localhost:9092
This is my first event
This is my second event

您可以使用Ctrl-C随时。

步骤 5:读取事件

打开另一个终端会话并运行控制台使用者客户端以读取您刚刚创建的事件:

$ bin/kafka-console-consumer.sh --topic quickstart-events --from-beginning --bootstrap-server localhost:9092
This is my first event
This is my second event

您可以使用Ctrl-C随时。

随意尝试:例如,切换回您的 producer 终端(上一步)以编写 additional events 的 Events,并查看事件如何立即显示在您的消费终端中。

由于事件持久存储在 Kafka 中,因此您可以根据需要多次读取这些事件,并由任意数量的使用者读取。 您可以通过打开另一个终端会话并再次重新运行上一个命令来轻松验证这一点。

第 6 步:使用 Kafka Connect 将数据导入/导出为事件流

您可能在现有系统(如关系数据库或传统消息传递系统)中拥有大量数据。 以及许多已经使用这些系统的应用程序。Kafka Connect 允许您持续摄取 数据从外部系统到 Kafka,反之亦然。它是一个运行连接器的可扩展工具,这些连接器实现用于与外部系统交互的自定义逻辑。 因此,将现有系统与 Kafka 集成非常容易。为了使此过程更加简单, 有数百个这样的连接器随时可用。

在本快速入门中,我们将了解如何使用导入数据的简单连接器运行 Kafka Connect 从文件导出到 Kafka 主题,并将数据从 Kafka 主题导出到文件。

首先,确保添加到connect-file-3.5.2.jarplugin.pathConnect worker 配置中的属性。 在本快速入门中,我们将使用相对路径,并将连接器的包视为一个 uber jar,当从安装目录运行快速入门命令时,该 jar 将起作用。 但是,值得注意的是,对于生产部署,使用绝对路径始终是可取的。有关如何设置此配置的详细说明,请参阅 plugin.path

编辑文件,添加或更改config/connect-standalone.propertiesplugin.pathconfiguration 属性与以下内容匹配,然后保存文件:

> echo "plugin.path=libs/connect-file-3.5.2.jar"

然后,首先创建一些种子数据以进行测试:

> echo -e "foo\nbar" > test.txt
或者在 Windows 上:
> echo foo> test.txt
> echo bar>> test.txt

接下来,我们将启动两个以独立模式运行的连接器,这意味着它们在单个本地专用 过程。我们提供了三个配置文件作为参数。第一个始终是 Kafka Connect 的配置 进程,其中包含常见配置,例如要连接的 Kafka 代理和数据序列化格式。 其余配置文件分别指定要创建的连接器。这些文件包括一个唯一的连接器名称,即 类来实例化,以及连接器所需的任何其他配置。

> bin/connect-standalone.sh config/connect-standalone.properties config/connect-file-source.properties config/connect-file-sink.properties

这些示例配置文件(包含在 Kafka 中)使用您之前启动的默认本地集群配置 并创建两个连接器:第一个是源连接器,它从输入文件中读取行并将每个行生成到 Kafka 主题 第二个是接收器连接器,它从 Kafka 主题中读取消息,并在输出文件中将每个消息生成为一行。

在启动过程中,您将看到许多日志消息,其中一些消息指示连接器正在实例化。 Kafka Connect 进程启动后,源连接器应开始从test.txt和 针对主题制作它们connect-test,接收器连接器应开始从主题connect-test并将它们写入文件test.sink.txt.我们可以验证数据是否已通过整个管道交付 通过检查输出文件的内容:

> more test.sink.txt
foo
bar

请注意,数据存储在 Kafka 主题中connect-test,因此我们还可以运行控制台使用者来查看 data 中(或使用自定义使用者代码对其进行处理):

> bin/kafka-console-consumer.sh --bootstrap-server localhost:9092 --topic connect-test --from-beginning
{"schema":{"type":"string","optional":false},"payload":"foo"}
{"schema":{"type":"string","optional":false},"payload":"bar"}
...

连接器继续处理数据,因此我们可以将数据添加到文件中,并查看它在管道中移动:

> echo Another line>> test.txt

您应该会看到该行出现在控制台使用者输出和 sink 文件中。

第 7 步:使用 Kafka Streams 处理事件

将数据作为事件存储在 Kafka 中后,您可以使用适用于 Java/Scala 的 Kafka Streams 客户端库处理数据。 它允许您实施任务关键型实时应用程序和微服务,其中输入 和/或输出数据存储在 Kafka 主题中。Kafka Streams 结合了编写和部署的简单性 客户端的标准 Java 和 Scala 应用程序,具有 Kafka 服务器端集群的优势 技术使这些应用程序具有高度可扩展性、弹性、容错性和分布式。库 支持恰好一次处理、有状态作和聚合、窗口化、联接、基于处理 在事件时间等等。

为了让您初步体验一下,以下是如何实现流行的WordCount算法:

KStream<String, String> textLines = builder.stream("quickstart-events");

KTable<String, Long> wordCounts = textLines
            .flatMapValues(line -> Arrays.asList(line.toLowerCase().split(" ")))
            .groupBy((keyIgnored, word) -> word)
            .count();

wordCounts.toStream().to("output-topic", Produced.with(Serdes.String(), Serdes.Long()));

Kafka Streams 演示应用程序开发教程演示了如何从头到尾编写和运行此类流式处理应用程序。

步骤 8:终止 Kafka 环境

现在,您已经完成了快速入门的结尾,请随时拆除 Kafka 环境,或者 继续玩。

  1. 停止生产者和使用者客户端Ctrl-C,如果您尚未执行此作。
  2. 停止 Kafka 代理Ctrl-C.
  3. 最后,如果遵循 Kafka with ZooKeeper 部分,请使用Ctrl-C.

如果您还想删除本地 Kafka 环境的任何数据,包括您创建的任何事件 在此过程中,运行以下命令:

$ rm -rf /tmp/kafka-logs /tmp/zookeeper /tmp/kraft-combined-logs

祝贺!

您已成功完成 Apache Kafka 快速入门。

要了解更多信息,我们建议执行以下步骤:

从任何版本 0.8.x 到 3.4.x 升级到 3.5.2

所有升级步骤与升级到 3.5.0 相同
3.5.2 中的显著变化
  • 当将生产者 ID 区块从 ZK 迁移到 KRaft 时,可能会有重复的生产者 ID 被赋予 事务性或幂等生产者。这可能会导致长期问题,因为生产者 ID 是 保留并重用了很长时间。 有关更多详细信息,请参阅 KAFKA-15552
  • 在 3.5.0 和 3.5.1 中,可能存在在 AlterPartition 请求后从控制器返回空 ISR 的问题 在滚动升级期间。此问题将影响 topic 分区的可用性。 有关更多详细信息,请参阅 KAFKA-15353

从任何版本 0.8.x 到 3.4.x 升级到 3.5.1

所有升级步骤与升级到 3.5.0 相同
3.5.1 中的显著变化
  • 将依赖项 snappy-java 升级到不易受 CVE-2023-34455 攻击的版本。您可以在 Kafka CVE 列表中找到有关 CVE 的更多信息。
  • 修复了 3.3.0 中引入的回归,该回归导致security.protocol要限制为的配置值 仅限大写。修复后,security.protocol值不区分大小写。 有关详细信息,请参阅 KAFKA-15053

从任何版本 0.8.x 到 3.4.x 升级到 3.5.0

3.5.0 中的显著更改
  • Kafka Streams 引入了一种新的状态存储类型,即版本化的键值存储、 用于为每个键存储多个记录版本,从而启用时间戳检索 作返回截至指定时间戳的最新记录(每个键)。 有关更多详细信息,请参阅 KIP-889KIP-914。 如果在 DSL 中使用新的存储类型化,则会应用 KIP-914 中所述的改进处理语义。
  • KTable 聚合语义通过 KIP-904 得到了进一步改进, 现在避免虚假的中间结果。
  • Kafka Streams 的ProductionExceptionHandler通过 KIP-399 得到改进, 现在还涵盖序列化错误。
  • MirrorMaker 现在默认使用 incrementalAlterConfigs API 来同步主题配置,而不是已弃用的 alterConfigs API。 一个名为use.incremental.alter.configs允许用户控制要使用的 API。 此新设置被标记为已弃用,并且当始终使用 incrementalAlterConfigs API 时,将在下一个主要版本中删除该设置。 有关详细信息,请参阅 KIP-894
  • JmxTool、EndToEndLatency、StreamsResetter、ConsumerPerformance 和 ClusterTool 已迁移到 tools 模块。 “kafka.tools”包已弃用,在下一个主要版本中将更改为“org.apache.kafka.tools”。 有关更多详细信息,请参阅 KAFKA-14525
升级基于 ZooKeeper 的集群

如果您从 2.1.x 之前的版本升级,请参阅下面步骤 5 中有关用于存储使用者偏移量的架构的更改的说明。 将 inter.broker.protocol.version 更改为最新版本后,将无法降级到 2.1 之前的版本。

对于滚动升级:

  1. 更新所有代理上的 server.properties 并添加以下属性。CURRENT_KAFKA_VERSION 是指您 正在升级。CURRENT_MESSAGE_FORMAT_VERSION 是指当前正在使用的消息格式版本。如果您之前有 覆盖了 Message Format version,则应保留其当前值。或者,如果您要从之前的版本升级 设置为 0.11.0.x,则CURRENT_MESSAGE_FORMAT_VERSION应设置为 MATCH CURRENT_KAFKA_VERSION。
    • inter.broker.protocol.version=CURRENT_KAFKA_VERSION 的3.4,3.3等)
    • log.message.format.version=CURRENT_MESSAGE_FORMAT_VERSION (查看潜在的性能影响) 有关此配置的作用的详细信息。
    如果您从版本 0.11.0.x 或更高版本升级,并且您没有覆盖消息格式,则只需覆盖 Inter-Broker 协议版本。
    • inter.broker.protocol.version=CURRENT_KAFKA_VERSION 的3.4,3.3等)
  2. 一次升级一个代理:关闭代理,更新代码,然后重新启动它。完成此作后, Broker 将运行最新版本,您可以验证集群的行为和性能是否符合预期。 如果有任何问题,此时仍然可以降级。
  3. 验证集群的行为和性能后,通过编辑来增加协议版本inter.broker.protocol.version并将其设置为3.5.
  4. 逐个重启 broker,新协议版本才能生效。一旦代理开始使用最新的 协议版本,则无法再将集群降级到旧版本。
  5. 如果您已按照上述说明覆盖了消息格式版本,则需要再执行一次滚动重启,以 将其升级到最新版本。所有(或大多数)消费者都升级到 0.11.0 或更高版本后, 将 log.message.format.version 更改为 3.5,然后逐个重启。请注意,较旧的 Scala 客户端 不再维护,不支持 0.11 中引入的 message 格式,从而避免转换成本 (或利用 Exactly once 语义)、 必须使用较新的 Java 客户端。
升级基于 KRaft 的集群

如果您要从 3.3.0 之前的版本升级,请参阅下面第 3 步中的说明。将 metadata.version 更改为最新版本后,将无法降级到 3.3-IV0 之前的版本。

对于滚动升级:

  1. 一次升级一个代理:关闭代理,更新代码,然后重新启动它。完成此作后, Broker 将运行最新版本,您可以验证集群的行为和性能是否符合预期。
  2. 验证集群的行为和性能后,通过运行 ./bin/kafka-features.sh upgrade --metadata 3.5
  3. 请注意,集群元数据版本升级后,无法降级到预生产 3.0.x、3.1.x 或 3.2.x 版本。 但是,可以降级到生产版本,例如 3.3-IV0、3.3-IV1 等。

从任何版本 0.8.x 到 3.3.x 升级到 3.4.0

如果您从 2.1.x 之前的版本升级,请参阅下面的说明,了解用于存储使用者偏移量的架构的更改。 将 inter.broker.protocol.version 更改为最新版本后,将无法降级到 2.1 之前的版本。

对于滚动升级:

  1. 更新所有代理上的 server.properties 并添加以下属性。CURRENT_KAFKA_VERSION 是指您 正在升级。CURRENT_MESSAGE_FORMAT_VERSION 是指当前正在使用的消息格式版本。如果您之前有 覆盖了 Message Format version,则应保留其当前值。或者,如果您要从之前的版本升级 设置为 0.11.0.x,则CURRENT_MESSAGE_FORMAT_VERSION应设置为 MATCH CURRENT_KAFKA_VERSION。
    • inter.broker.protocol.version=CURRENT_KAFKA_VERSION 的3.3,3.2等)
    • log.message.format.version=CURRENT_MESSAGE_FORMAT_VERSION (查看潜在的性能影响) 有关此配置的作用的详细信息。
    如果您从版本 0.11.0.x 或更高版本升级,并且您没有覆盖消息格式,则只需覆盖 Inter-Broker 协议版本。
    • inter.broker.protocol.version=CURRENT_KAFKA_VERSION 的3.3,3.2等)
  2. 一次升级一个代理:关闭代理,更新代码,然后重新启动它。完成此作后, Broker 将运行最新版本,您可以验证集群的行为和性能是否符合预期。 如果有任何问题,此时仍然可以降级。
  3. 验证集群的行为和性能后,通过编辑来增加协议版本inter.broker.protocol.version并将其设置为3.4.
  4. 逐个重启 broker,新协议版本才能生效。一旦代理开始使用最新的 协议版本,则无法再将集群降级到旧版本。
  5. 如果您已按照上述说明覆盖了消息格式版本,则需要再执行一次滚动重启,以 将其升级到最新版本。所有(或大多数)消费者都升级到 0.11.0 或更高版本后, 将每个代理的 log.message.format.version 更改为 3.4,然后逐个重新启动它们。请注意,较旧的 Scala 客户端 不再维护,不支持 0.11 中引入的 message 格式,从而避免转换成本 (或利用 Exactly once 语义)、 必须使用较新的 Java 客户端。

将基于 KRaft 的集群从任何版本 3.0.x 升级到 3.4.0 到 3.3.x

如果您从 3.3.0 之前的版本升级,请参阅下面的说明。将 metadata.version 更改为最新版本后,将无法降级到 3.3-IV0 之前的版本。

对于滚动升级:

  1. 一次升级一个代理:关闭代理,更新代码,然后重新启动它。完成此作后, Broker 将运行最新版本,您可以验证集群的行为和性能是否符合预期。
  2. 验证集群的行为和性能后,通过运行 ./bin/kafka-features.sh upgrade --metadata 3.4
  3. 请注意,集群元数据版本升级后,无法降级到预生产 3.0.x、3.1.x 或 3.2.x 版本。 但是,可以降级到生产版本,例如 3.3-IV0、3.3-IV1 等。
3.4.0 中的显著更改
  • 从 Apache Kafka 3.4.0 开始,我们添加了一个系统属性(“org.apache.kafka.disallowed.login.modules”)来禁用有问题的 SASL JAAS 配置中的登录模块使用情况。此外,默认情况下,Apache Kafka 3.4.0 中禁用了 “com.sun.security.auth.module.JndiLoginModule”。

从任何版本 0.8.x 到 3.2.x 升级到 3.3.1

如果您从 2.1.x 之前的版本升级,请参阅下面的说明,了解用于存储使用者偏移量的架构的更改。 将 inter.broker.protocol.version 更改为最新版本后,将无法降级到 2.1 之前的版本。

对于滚动升级:

  1. 更新所有代理上的 server.properties 并添加以下属性。CURRENT_KAFKA_VERSION 是指您 正在升级。CURRENT_MESSAGE_FORMAT_VERSION 是指当前正在使用的消息格式版本。如果您之前有 覆盖了 Message Format version,则应保留其当前值。或者,如果您要从之前的版本升级 设置为 0.11.0.x,则CURRENT_MESSAGE_FORMAT_VERSION应设置为 MATCH CURRENT_KAFKA_VERSION。
    • inter.broker.protocol.version=CURRENT_KAFKA_VERSION 的3.2,3.1等)
    • log.message.format.version=CURRENT_MESSAGE_FORMAT_VERSION (查看潜在的性能影响) 有关此配置的作用的详细信息。
    如果您从版本 0.11.0.x 或更高版本升级,并且您没有覆盖消息格式,则只需覆盖 Inter-Broker 协议版本。
    • inter.broker.protocol.version=CURRENT_KAFKA_VERSION 的3.2,3.1等)
  2. 一次升级一个代理:关闭代理,更新代码,然后重新启动它。完成此作后, Broker 将运行最新版本,您可以验证集群的行为和性能是否符合预期。 如果有任何问题,此时仍然可以降级。
  3. 验证集群的行为和性能后,通过编辑来增加协议版本inter.broker.protocol.version并将其设置为3.3.
  4. 逐个重启 broker,新协议版本才能生效。一旦代理开始使用最新的 协议版本,则无法再将集群降级到旧版本。
  5. 如果您已按照上述说明覆盖了消息格式版本,则需要再执行一次滚动重启,以 将其升级到最新版本。所有(或大多数)消费者都升级到 0.11.0 或更高版本后, 将 log.message.format.version 更改为 3.3,然后逐个重启。请注意,较旧的 Scala 客户端 不再维护,不支持 0.11 中引入的 message 格式,从而避免转换成本 (或利用 Exactly once 语义)、 必须使用较新的 Java 客户端。

将基于 KRaft 的集群从任何版本 3.0.x 升级到 3.3.1 到 3.2.x

如果您从 3.3.1 之前的版本升级,请参阅下面的说明。将 metadata.version 更改为最新版本后,将无法降级到 3.3-IV0 之前的版本。

对于滚动升级:

  1. 一次升级一个代理:关闭代理,更新代码,然后重新启动它。完成此作后, Broker 将运行最新版本,您可以验证集群的行为和性能是否符合预期。
  2. 验证集群的行为和性能后,通过运行 ./bin/kafka-features.sh upgrade --metadata 3.3
  3. 请注意,集群元数据版本升级后,无法降级到预生产 3.0.x、3.1.x 或 3.2.x 版本。但是,可以降级到生产版本,例如 3.3-IV0、3.3-IV1 等。
3.3.1 中的显著更改
  • KRaft 模式可用于新集群的生产环境。有关更多详细信息(包括限制),请参阅 KIP-833
  • 默认情况下用于无键记录的分区程序已得到改进,以避免在一个或多个代理速度较慢时出现病态行为。 新逻辑可能会影响批处理行为,可以使用batch.size和/或linger.ms配置设置。 可以通过设置partitioner.class=org.apache.kafka.clients.producer.internals.DefaultPartitioner. 有关更多详细信息,请参阅 KIP-794
  • 如上所述,现在 KRaft 集群的升级过程与基于 ZK 的集群略有不同。
  • 引入了新的 APIaddMetricIfAbsentMetrics这将创建一个新的 Metric(如果不存在)或返回相同的 Metric 如果已经注册。请注意,此行为与addMetricAPI 会抛出一个IllegalArgumentException什么时候 尝试创建已存在的量度。(有关详细信息,请参阅 KIP-843)。

从任何版本 0.8.x 到 3.1.x 升级到 3.2.0

如果您从 2.1.x 之前的版本升级,请参阅下面的说明,了解用于存储使用者偏移量的架构的更改。 将 inter.broker.protocol.version 更改为最新版本后,将无法降级到 2.1 之前的版本。

对于滚动升级:

  1. 更新所有代理上的 server.properties 并添加以下属性。CURRENT_KAFKA_VERSION 是指您 正在升级。CURRENT_MESSAGE_FORMAT_VERSION 是指当前正在使用的消息格式版本。如果您之前有 覆盖了 Message Format version,则应保留其当前值。或者,如果您要从之前的版本升级 设置为 0.11.0.x,则CURRENT_MESSAGE_FORMAT_VERSION应设置为 MATCH CURRENT_KAFKA_VERSION。
    • inter.broker.protocol.version=CURRENT_KAFKA_VERSION 的3.1,3.0等)
    • log.message.format.version=CURRENT_MESSAGE_FORMAT_VERSION (查看潜在的性能影响) 有关此配置的作用的详细信息。
    如果您从版本 0.11.0.x 或更高版本升级,并且您没有覆盖消息格式,则只需覆盖 Inter-Broker 协议版本。
    • inter.broker.protocol.version=CURRENT_KAFKA_VERSION 的3.1,3.0等)
  2. 一次升级一个代理:关闭代理,更新代码,然后重新启动它。完成此作后, Broker 将运行最新版本,您可以验证集群的行为和性能是否符合预期。 如果有任何问题,此时仍然可以降级。
  3. 验证集群的行为和性能后,通过编辑来增加协议版本inter.broker.protocol.version并将其设置为3.2.
  4. 逐个重启 broker,新协议版本才能生效。一旦代理开始使用最新的 协议版本,则无法再将集群降级到旧版本。
  5. 如果您已按照上述说明覆盖了消息格式版本,则需要再执行一次滚动重启,以 将其升级到最新版本。所有(或大多数)消费者都升级到 0.11.0 或更高版本后, 将 log.message.format.version 更改为 3.2,然后逐个重启。请注意,较旧的 Scala 客户端 不再维护,不支持 0.11 中引入的 message 格式,从而避免转换成本 (或利用 Exactly once 语义)、 必须使用较新的 Java 客户端。
3.2.0 中的显著变化
  • 如果未设置冲突配置,则默认情况下会启用生产者的幂等性。当向 2.8.0 之前的 broker 生产时, 这IDEMPOTENT_WRITE需要权限。检查兼容性 部分了解 KIP-679 的 THE MissAV.com 的 MissAV.com 的 MissAV.com |在 3.0.0 和 3.1.0 中,一个错误阻止了这个默认值的应用。 这意味着幂等性将保持禁用状态,除非用户明确设置enable.idempotence设置为 true (有关更多详细信息,请参阅 KAFKA-13598)。 此问题已修复,默认值已在 3.0.1、3.1.1 和 3.2.0 中正确应用。
  • 一个值得注意的例外是 Connect,默认情况下,它对其所有 producer 来统一支持使用各种 Kafka 代理版本。 用户可以更改此行为,以便为部分或全部生产者启用幂等性 通过 Connect worker 和/或 connector 配置。Connect 可以启用幂等生产者 在将来的主要版本中默认。
  • 出于安全考虑,Kafka 已将 log4j 替换为 reload4j。 这仅影响指定日志记录后端 (connect-runtimekafka-tools就是两个这样的例子)。 许多模块,包括kafka-clients,请让应用程序指定日志记录后端。 更多信息可以在 reload4j 上找到。 依赖于 Kafka 项目中受影响的模块的项目应使用 slf4j-log4j12 版本 1.7.35 或更高版本,或者 slf4j-reload4j 以避免由日志记录框架引起的可能兼容性问题
  • 示例连接器FileStreamSourceConnectorFileStreamSinkConnector一直 从默认 Classpath 中删除。要在 Kafka Connect 独立或分布式模式下使用它们,它们需要 显式添加,例如CLASSPATH=./libs/connect-file-3.2.0.jar ./bin/connect-distributed.sh.

从任何版本 0.8.x 升级到 3.1.0 到 3.0.x

如果您从 2.1.x 之前的版本升级,请参阅下面的说明,了解用于存储使用者偏移量的架构的更改。 将 inter.broker.protocol.version 更改为最新版本后,将无法降级到 2.1 之前的版本。

对于滚动升级:

  1. 更新所有代理上的 server.properties 并添加以下属性。CURRENT_KAFKA_VERSION 是指您 正在升级。CURRENT_MESSAGE_FORMAT_VERSION 是指当前正在使用的消息格式版本。如果您之前有 覆盖了 Message Format version,则应保留其当前值。或者,如果您要从之前的版本升级 设置为 0.11.0.x,则CURRENT_MESSAGE_FORMAT_VERSION应设置为 MATCH CURRENT_KAFKA_VERSION。
    • inter.broker.protocol.version=CURRENT_KAFKA_VERSION 的3.0,2.8等)
    • log.message.format.version=CURRENT_MESSAGE_FORMAT_VERSION (查看潜在的性能影响) 有关此配置的作用的详细信息。
    如果您从版本 0.11.0.x 或更高版本升级,并且您没有覆盖消息格式,则只需覆盖 Inter-Broker 协议版本。
    • inter.broker.protocol.version=CURRENT_KAFKA_VERSION 的3.0,2.8等)
  2. 一次升级一个代理:关闭代理,更新代码,然后重新启动它。完成此作后, Broker 将运行最新版本,您可以验证集群的行为和性能是否符合预期。 如果有任何问题,此时仍然可以降级。
  3. 验证集群的行为和性能后,通过编辑来增加协议版本inter.broker.protocol.version并将其设置为3.1.
  4. 逐个重启 broker,新协议版本才能生效。一旦代理开始使用最新的 协议版本,则无法再将集群降级到旧版本。
  5. 如果您已按照上述说明覆盖了消息格式版本,则需要再执行一次滚动重启,以 将其升级到最新版本。所有(或大多数)消费者都升级到 0.11.0 或更高版本后, 将 log.message.format.version 更改为 3.1,然后逐个重启。请注意,较旧的 Scala 客户端 不再维护,不支持 0.11 中引入的 message 格式,从而避免转换成本 (或利用 Exactly once 语义)、 必须使用较新的 Java 客户端。
3.1.1 中的显著更改
  • 如果未设置冲突配置,则默认情况下会启用生产者的幂等性。当向 2.8.0 之前的 broker 生产时, 这IDEMPOTENT_WRITE需要权限。检查兼容性 部分了解 KIP-679 的 THE MissAV.com 的 MissAV.com 的 MissAV.com |一个错误阻止了生产者幂等默认值的应用,这意味着除非用户 显式设置enable.idempotence设置为 true。请参阅 KAFKA-13598 更多细节。此问题已修复,默认值已正确应用。
  • 一个值得注意的例外是 Connect,默认情况下,它对其所有 producer 来统一支持使用各种 Kafka 代理版本。 用户可以更改此行为,以便为部分或全部生产者启用幂等性 通过 Connect worker 和/或 connector 配置。Connect 可以启用幂等生产者 在将来的主要版本中默认。
  • 出于安全考虑,Kafka 已将 log4j 替换为 reload4j。 这仅影响指定日志记录后端 (connect-runtimekafka-tools就是两个这样的例子)。 许多模块,包括kafka-clients,请让应用程序指定日志记录后端。 更多信息可以在 reload4j 上找到。 依赖于 Kafka 项目中受影响的模块的项目应使用 slf4j-log4j12 版本 1.7.35 或更高版本,或者 slf4j-reload4j 以避免由日志记录框架引起的可能兼容性问题
3.1.0 中的显著更改
  • Apache Kafka 支持 Java 17。
  • 以下指标已被弃用:bufferpool-wait-time-total,io-waittime-total, 和iotime-total.请使用bufferpool-wait-time-ns-total,io-wait-time-ns-total, 和io-time-ns-total相反。有关更多详细信息,请参阅 KIP-773
  • IBP 3.1 将主题 ID 作为 KIP-516 的一部分引入 FetchRequest。

从任何版本 0.8.x 到 2.8.x 升级到 3.0.1

如果您从 2.1.x 之前的版本升级,请参阅下面的说明,了解用于存储使用者偏移量的架构的更改。 将 inter.broker.protocol.version 更改为最新版本后,将无法降级到 2.1 之前的版本。

对于滚动升级:

  1. 更新所有代理上的 server.properties 并添加以下属性。CURRENT_KAFKA_VERSION 是指您 正在升级。CURRENT_MESSAGE_FORMAT_VERSION 是指当前正在使用的消息格式版本。如果您之前有 覆盖了 Message Format version,则应保留其当前值。或者,如果您要从之前的版本升级 设置为 0.11.0.x,则CURRENT_MESSAGE_FORMAT_VERSION应设置为 MATCH CURRENT_KAFKA_VERSION。
    • inter.broker.protocol.version=CURRENT_KAFKA_VERSION 的2.8,2.7等)
    • log.message.format.version=CURRENT_MESSAGE_FORMAT_VERSION (查看潜在的性能影响) 有关此配置的作用的详细信息。
    如果您从版本 0.11.0.x 或更高版本升级,并且您没有覆盖消息格式,则只需覆盖 Inter-Broker 协议版本。
    • inter.broker.protocol.version=CURRENT_KAFKA_VERSION 的2.8,2.7等)
  2. 一次升级一个代理:关闭代理,更新代码,然后重新启动它。完成此作后, Broker 将运行最新版本,您可以验证集群的行为和性能是否符合预期。 如果有任何问题,此时仍然可以降级。
  3. 验证集群的行为和性能后,通过编辑来增加协议版本inter.broker.protocol.version并将其设置为3.0.
  4. 逐个重启 broker,新协议版本才能生效。一旦代理开始使用最新的 协议版本,则无法再将集群降级到旧版本。
  5. 如果您已按照上述说明覆盖了消息格式版本,则需要再执行一次滚动重启,以 将其升级到最新版本。所有(或大多数)消费者都升级到 0.11.0 或更高版本后, 将 log.message.format.version 修改为 3.0,然后逐个重启。请注意,较旧的 Scala 客户端 不再维护,不支持 0.11 中引入的 message 格式,从而避免转换成本 (或利用 Exactly once 语义)、 必须使用较新的 Java 客户端。
3.0.1 中的显著更改
  • 如果未设置冲突配置,则默认情况下会启用生产者的幂等性。当向 2.8.0 之前的 broker 生产时, 这IDEMPOTENT_WRITE需要权限。检查兼容性 部分了解 KIP-679 的 THE MissAV.com 的 MissAV.com 的 MissAV.com |一个错误阻止了生产者幂等默认值的应用,这意味着除非用户 显式设置enable.idempotence设置为 true。请参阅 KAFKA-13598 更多细节。此问题已修复,默认值已正确应用。
3.0.0 中的显著更改
  • 默认情况下,创建者具有更强的传输保证:idempotence已启用,并且acks设置为all而不是1. 有关详细信息,请参阅 KIP-679。 在 3.0.0 和 3.1.0 中,一个错误阻止了幂等默认值的应用,这意味着除非用户明确设置enable.idempotence设置为 true。请注意,该 bug 不会影响acks=all改变。有关更多详细信息,请参阅 KAFKA-13598。 此问题已修复,默认值已在 3.0.1、3.1.1 和 3.2.0 中正确应用。
  • Java 8 和 Scala 2.12 支持自 Apache Kafka 3.0 起已弃用,并将在 Apache Kafka 4.0 中删除。 有关更多详细信息,请参阅 KIP-750KIP-751
  • ZooKeeper 已升级到版本 3.6.3。
  • KRaft 模式的预览版可用,但无法从 2.8 Early Access 版本升级到它。看 这config/kraft/README.md文件了解详细信息。
  • 发布 tarball 不再包含 test、sources、javadoc 和 test sources jar。这些仍会发布到 Maven Central 存储库。
  • 现在,运行时类路径中提供了许多实现依赖项 jar 而不是 compile 和 runtime 类路径。升级后的编译错误可以通过显式添加缺少的依赖项 jar 来修复 或更新应用程序以不使用内部类。
  • 使用者配置的默认值session.timeout.ms由 10 秒增加至 45 秒。有关更多详细信息,请参阅 KIP-735
  • 代理配置log.message.format.version和 Topic 配置message.format.version已被弃用。 这两个配置的值始终假定为3.0如果inter.broker.protocol.version3.0或更高。 如果log.message.format.versionmessage.format.version设置,我们建议在清除inter.broker.protocol.version升级到 3.0。这将避免潜在的兼容性问题,如果inter.broker.protocol.version被降级。有关更多详细信息,请参阅 KIP-724
  • Streams API 删除了版本 2.5.0 或更早版本中不推荐使用的所有已弃用的 API。 有关已删除 API 的完整列表,请参阅详细的 Kafka Streams 升级说明。
  • Kafka Streams 不再依赖于 “connect:json” 模块 (KAFKA-5146)。 依赖此传递依赖项的项目必须显式声明它。
  • 通过principal.builder.class现在必须实现KafkaPrincipalSerde接口以允许在 broker 之间进行转发。有关使用 KafkaPrincipalSerde 的更多详细信息,请参阅 KIP-590
  • 许多已弃用的类、方法和工具已从clients,connect,coretools模块:
    • The ScalaAuthorizer,SimpleAclAuthorizer,并且已删除相关类。请使用 JavaAuthorizerAclAuthorizer相反。
    • Metric#value()方法已删除 (KAFKA-12573)。
    • SumTotal类已删除 (KAFKA-12584)。 请使用WindowedSumCumulativeSum相反。
    • CountSampledTotal类被删除。请使用WindowedCountWindowedSum相反。
    • PrincipalBuilder,DefaultPrincipalBuilderResourceFilter类被删除。
    • SslConfigs,SaslConfigs,AclBindingAclBindingFilter.
    • Admin.electedPreferredLeaders()方法。请使用Admin.electLeaders相反。
    • kafka-preferred-replica-election命令行工具已删除。请使用kafka-leader-election相反。
    • --zookeeper选项已从kafka-topicskafka-reassign-partitions命令行工具。 请使用--bootstrap-server相反。
    • kafka-configs命令行工具、--zookeeper选项仅支持更新 SCRAM 凭证配置描述/更新代理未运行时的动态代理配置。请使用--bootstrap-server用于其他配置作。
    • ConfigEntry构造函数已删除 (KAFKA-12577)。 请改用剩余的 public 构造函数。
    • config 值default对于客户端配置client.dns.lookup已被删除。在不太可能的情况下 如果您显式设置了此配置,我们建议将配置保留为未设置 (use_all_dns_ips默认使用)。
    • ExtendedDeserializerExtendedSerializer类已被删除。请使用DeserializerSerializer相反。
    • close(long, TimeUnit)方法已从 producer、consumer 和 admin 客户端中删除。请使用close(Duration).
    • ConsumerConfig.addDeserializerToConfigProducerConfig.addSerializerToConfig方法 被删除。这些方法不是公共 API,因此没有替代方法。
    • NoOffsetForPartitionException.partition()方法已删除。请使用partitions()相反。
    • 默认的partition.assignment.strategy更改为 “[RangeAssignor, CooperativeStickyAssignor]”, 默认情况下,它将使用 RangeAssignor,但允许升级到 CooperativeStickyAssignor,只需一次滚动反弹即可从列表中删除 RangeAssignor。 有关更多详细信息,请在此处查看客户端升级路径指南。
    • The Scalakafka.common.MessageFormatter已删除。请使用 Javaorg.apache.kafka.common.MessageFormatter.
    • MessageFormatter.init(Properties)方法已删除。请使用configure(Map)相反。
    • checksum()方法已从ConsumerRecordRecordMetadata.信息 格式 v2(自 0.11 起一直是默认值)将校验和从记录批次移动到记录批次。因此,这些方法 没有意义,也没有替代品。
    • ChecksumMessageFormatter类已删除。它不是公共 API 的一部分,但可能已被使用 跟kafka-console-consumer.sh.它报告了每条记录的校验和,但一直不支持 从 Message Format V2.
    • org.apache.kafka.clients.consumer.internals.PartitionAssignor类已被删除。请使用org.apache.kafka.clients.consumer.ConsumerPartitionAssignor相反。
    • quota.producer.defaultquota.consumer.default配置已删除 (KAFKA-12591)。 必须改用动态配额默认值。
    • porthost.name配置已删除。请使用listeners相反。
    • advertised.portadvertised.host.name配置已删除。请使用advertised.listeners相反。
    • 已弃用的 worker 配置rest.host.namerest.port已从 Kafka Connect 工作程序配置中删除 (KAFKA-12482)。 请使用listeners相反。
  • Producer#sendOffsetsToTransaction(Map offsets, String consumerGroupId)方法已弃用。请使用Producer#sendOffsetsToTransaction(Map offsets, ConsumerGroupMetadata metadata)相反,其中ConsumerGroupMetadata可以通过以下方式检索KafkaConsumer#groupMetadata()以获得更强的语义。请注意,完整的使用者组元数据集仅为 被 broker 或 2.5 或更高版本理解,因此您必须升级 Kafka 集群以获得更强的语义。否则,你可以直接通过 在new ConsumerGroupMetadata(consumerGroupId)与较老的经纪人合作。有关更多详细信息,请参阅 KIP-732
  • 连接internal.key.converterinternal.value.converter属性已被完全删除。 自版本 2.0.0 起,这些 Connect 工作线程属性的使用已被弃用。 Worker 现在被硬编码为使用 JSON 转换器schemas.enable设置为false.如果您的集群一直在使用 使用不同的内部密钥或值转换器,您可以按照 KIP-738 中概述的迁移步骤安全地将 Connect 集群升级到 3.0。
  • 基于 Connect 的 MirrorMaker (MM2) 包括对支持的更改IdentityReplicationPolicy,在不重命名主题的情况下启用复制。 现有的DefaultReplicationPolicy仍默认使用,但可以通过replication.policyconfiguration 属性。这对于从旧版 MirrorMaker (MM1) 迁移的用户或 具有简单单向复制拓扑的用例,其中不需要主题重命名。请注意,IdentityReplicationPolicyDefaultReplicationPolicy无法阻止基于主题名称的复制周期,因此在构建 复制拓扑。
  • 原始 MirrorMaker (MM1) 和相关类已被弃用。请使用基于 Connect 的 MirrorMaker (MM2),如异地复制部分所述。

从任何版本 0.8.x 升级到 2.7.x 到 2.7.1

如果您从 2.1.x 之前的版本升级,请参阅下面的说明,了解用于存储使用者偏移量的架构的更改。 将 inter.broker.protocol.version 更改为最新版本后,将无法降级到 2.1 之前的版本。

对于滚动升级:

  1. 更新所有代理上的 server.properties 并添加以下属性。CURRENT_KAFKA_VERSION 是指您 正在升级。CURRENT_MESSAGE_FORMAT_VERSION 是指当前正在使用的消息格式版本。如果您之前有 覆盖了 Message Format version,则应保留其当前值。或者,如果您要从之前的版本升级 设置为 0.11.0.x,则CURRENT_MESSAGE_FORMAT_VERSION应设置为 MATCH CURRENT_KAFKA_VERSION。
    • inter.broker.protocol.version=CURRENT_KAFKA_VERSION 的2.7,2.6等)
    • log.message.format.version=CURRENT_MESSAGE_FORMAT_VERSION (查看潜在的性能影响) 有关此配置的作用的详细信息。
    如果您从版本 0.11.0.x 或更高版本升级,并且您没有覆盖消息格式,则只需覆盖 Inter-Broker 协议版本。
    • inter.broker.protocol.version=CURRENT_KAFKA_VERSION 的2.7,2.6等)
  2. 一次升级一个代理:关闭代理,更新代码,然后重新启动它。完成此作后, Broker 将运行最新版本,您可以验证集群的行为和性能是否符合预期。 如果有任何问题,此时仍然可以降级。
  3. 验证集群的行为和性能后,通过编辑来增加协议版本inter.broker.protocol.version并将其设置为2.8.
  4. 逐个重启 broker,新协议版本才能生效。一旦代理开始使用最新的 协议版本,则无法再将集群降级到旧版本。
  5. 如果您已按照上述说明覆盖了消息格式版本,则需要再执行一次滚动重启,以 将其升级到最新版本。所有(或大多数)消费者都升级到 0.11.0 或更高版本后, 将每个代理上的 log.message.format.version 更改为 2.8,然后逐个重新启动它们。请注意,较旧的 Scala 客户端 不再维护,不支持 0.11 中引入的 message 格式,从而避免转换成本 (或利用 Exactly once 语义)、 必须使用较新的 Java 客户端。
2.8.0 中的显著变化
  • 2.8.0 版本向 KIP-679 中引入的授权方接口添加了一种新方法。 动机是解锁我们的未来计划,以默认启用最强的消息传递保证。 自定义授权方应考虑提供更高效的实现,以支持审核日志记录和任何自定义配置或访问规则。
  • IBP 2.8 作为 KIP-516 的一部分,为主题引入了主题 ID。 使用 ZooKeeper 时,此信息存储在 TopicZNode 中。如果集群已降级到以前的 IBP 或版本, 将来的主题不会获得主题 ID,并且不能保证主题将在 ZooKeeper 中保留其主题 ID。 这意味着在再次升级时,某些主题或所有主题将被分配新的 ID。
  • Kafka Streams 引入了类型安全的split()运算符作为 deprecated 的替代品KStream#branch()方法 (参见 KIP-418)。

从任何版本 0.8.x 升级到 2.7.0 到 2.6.x

如果您从 2.1.x 之前的版本升级,请参阅下面的说明,了解用于存储使用者偏移量的架构的更改。 将 inter.broker.protocol.version 更改为最新版本后,将无法降级到 2.1 之前的版本。

对于滚动升级:

  1. 更新所有代理上的 server.properties 并添加以下属性。CURRENT_KAFKA_VERSION 是指您 正在升级。CURRENT_MESSAGE_FORMAT_VERSION 是指当前正在使用的消息格式版本。如果您之前有 覆盖了 Message Format version,则应保留其当前值。或者,如果您要从之前的版本升级 设置为 0.11.0.x,则CURRENT_MESSAGE_FORMAT_VERSION应设置为 MATCH CURRENT_KAFKA_VERSION。
    • inter.broker.protocol.version=CURRENT_KAFKA_VERSION 的2.6,2.5等)
    • log.message.format.version=CURRENT_MESSAGE_FORMAT_VERSION (查看潜在的性能影响) 有关此配置的作用的详细信息。
    如果您从版本 0.11.0.x 或更高版本升级,并且您没有覆盖消息格式,则只需覆盖 Inter-Broker 协议版本。
    • inter.broker.protocol.version=CURRENT_KAFKA_VERSION 的2.6,2.5等)
  2. 一次升级一个代理:关闭代理,更新代码,然后重新启动它。完成此作后, Broker 将运行最新版本,您可以验证集群的行为和性能是否符合预期。 如果有任何问题,此时仍然可以降级。
  3. 验证集群的行为和性能后,通过编辑来增加协议版本inter.broker.protocol.version并将其设置为2.7.
  4. 逐个重启 broker,新协议版本才能生效。一旦代理开始使用最新的 协议版本,则无法再将集群降级到旧版本。
  5. 如果您已按照上述说明覆盖了消息格式版本,则需要再执行一次滚动重启,以 将其升级到最新版本。所有(或大多数)消费者都升级到 0.11.0 或更高版本后, 将 log.message.format.version 更改为 2.7,然后逐个重启。请注意,较旧的 Scala 客户端 不再维护,不支持 0.11 中引入的 message 格式,从而避免转换成本 (或利用 Exactly once 语义)、 必须使用较新的 Java 客户端。
2.7.0 中的显著变化
  • 2.7.0 版本包括 KIP-595 中指定的核心 Raft 实现。 有一个单独的 “raft” 模块,包含大部分 logic。在与 controller 完成后,用户可以使用一个独立的服务器来测试 性能。有关详细信息,请参阅 raft 模块中的 README.md
  • KIP-651 增加了对将 PEM 文件用于密钥和信任存储的支持。
  • KIP-612 增加了对强制执行代理范围和每个侦听器连接创建速率的支持。2.7.0 版本包含 KIP-612 的第一部分,动态配置将在 2.8.0 版本中推出。
  • 能够限制主题和分区创建,或者 主题删除以防止集群受到 KIP-599 的损害
  • 当 Kafka 中提供新功能时,有两个主要问题:
    1. Kafka 客户端如何了解代理功能?
    2. 经纪人如何决定启用哪些功能?
    KIP-584 为客户端发现、功能门控和滚动升级提供了灵活且作简单的解决方案,只需重新启动一次即可。
  • 能够使用ConsoleConsumer现在可以 通过 KIP-431
  • KIP-554 的加入继续朝着从 Kafka 中删除 Zookeeper 的目标迈进。KIP-554 的加入 意味着您不必再直接连接到 ZooKeeper 来管理 SCRAM 凭证。
  • 更改现有侦听器的 non-re-configurable configs 导致InvalidRequestException. 相比之下,之前的(意外的)行为会导致更新的配置被持久化。 但事实并非如此 生效,直到 Broker 重新启动。有关更多讨论,请参阅 KAFKA-10479。 看DynamicBrokerConfig.DynamicSecurityConfigsSocketServer.ListenerReconfigurableConfigs对于现有侦听器支持的 reconfigurable configs。
  • Kafka Streams 在 KStreams DSL 中添加了对滑动窗口聚合的支持。
  • 对状态存储进行反向迭代,使用 KIP-617 实现更高效的最新更新搜索
  • Kafka Steams 中的端到端延迟指标,请参阅 KIP-613 了解更多详情
  • Kafka Streams 使用 KIP-607 添加了报告默认 RocksDB 属性的指标
  • KIP-616 中更好的 Scala 隐式 Serdes 支持

从任何版本 0.8.x 升级到 2.6.0 到 2.5.x

如果您从 2.1.x 之前的版本升级,请参阅下面的说明,了解用于存储使用者偏移量的架构的更改。 将 inter.broker.protocol.version 更改为最新版本后,将无法降级到 2.1 之前的版本。

对于滚动升级:

  1. 更新所有代理上的 server.properties 并添加以下属性。CURRENT_KAFKA_VERSION 是指您 正在升级。CURRENT_MESSAGE_FORMAT_VERSION 是指当前正在使用的消息格式版本。如果您之前有 覆盖了 Message Format version,则应保留其当前值。或者,如果您要从之前的版本升级 设置为 0.11.0.x,则CURRENT_MESSAGE_FORMAT_VERSION应设置为 MATCH CURRENT_KAFKA_VERSION。
    • inter.broker.protocol.version=CURRENT_KAFKA_VERSION 的2.5,2.4等)
    • log.message.format.version=CURRENT_MESSAGE_FORMAT_VERSION (查看潜在的性能影响) 有关此配置的作用的详细信息。
    如果您从版本 0.11.0.x 或更高版本升级,并且您没有覆盖消息格式,则只需覆盖 Inter-Broker 协议版本。
    • inter.broker.protocol.version=CURRENT_KAFKA_VERSION 的2.5,2.4等)
  2. 一次升级一个代理:关闭代理,更新代码,然后重新启动它。完成此作后, Broker 将运行最新版本,您可以验证集群的行为和性能是否符合预期。 如果有任何问题,此时仍然可以降级。
  3. 验证集群的行为和性能后,通过编辑来增加协议版本inter.broker.protocol.version并将其设置为2.6.
  4. 逐个重启 broker,新协议版本才能生效。一旦代理开始使用最新的 协议版本,则无法再将集群降级到旧版本。
  5. 如果您已按照上述说明覆盖了消息格式版本,则需要再执行一次滚动重启,以 将其升级到最新版本。所有(或大多数)消费者都升级到 0.11.0 或更高版本后, 将 log.message.format.version 修改为 2.6,然后逐个重启。请注意,较旧的 Scala 客户端 不再维护,不支持 0.11 中引入的 message 格式,从而避免转换成本 (或利用 Exactly once 语义)、 必须使用较新的 Java 客户端。
2.6.0 中的显著变化
  • Kafka Streams 添加了一种新的处理模式(需要代理 2.5 或更高版本),以改进应用程序 使用 Exactly-Once 保证的可扩展性 (参见 KIP-447)
  • 默认情况下,Java 11 或更高版本已启用 TLSv1.3。如果 两者都支持它,否则回退到 TLSv1.2。有关更多详细信息,请参阅 KIP-573
  • client.dns.lookup配置已从defaultuse_all_dns_ips.如果主机名解析为多个 IP 地址,则客户端和代理现在将 尝试按顺序连接到每个 IP,直到成功建立连接。有关更多详细信息,请参阅 KIP-602
  • NotLeaderForPartitionException已弃用并替换为NotLeaderOrFollowerException. Fetch 请求和其他仅用于 leader 或 follower 的请求返回 NOT_LEADER_OR_FOLLOWER(6) 而不是 REPLICA_NOT_AVAILABLE(9) 如果代理不是副本,请确保所有客户端在重新分配期间将此暂时性错误作为可重试异常处理。

从任何版本 0.8.x 到 2.4.x 升级到 2.5.0

如果您从 2.1.x 之前的版本升级,请参阅下面的说明,了解用于存储使用者偏移量的架构的更改。 将 inter.broker.protocol.version 更改为最新版本后,将无法降级到 2.1 之前的版本。

对于滚动升级:

  1. 更新所有代理上的 server.properties 并添加以下属性。CURRENT_KAFKA_VERSION 是指您 正在升级。CURRENT_MESSAGE_FORMAT_VERSION 是指当前正在使用的消息格式版本。如果您之前有 覆盖了 Message Format version,则应保留其当前值。或者,如果您要从之前的版本升级 设置为 0.11.0.x,则CURRENT_MESSAGE_FORMAT_VERSION应设置为 MATCH CURRENT_KAFKA_VERSION。
    • inter.broker.protocol.version=CURRENT_KAFKA_VERSION 的2.4,2.3等)
    • log.message.format.version=CURRENT_MESSAGE_FORMAT_VERSION (查看潜在的性能影响) 有关此配置的作用的详细信息。
    如果您从版本 0.11.0.x 或更高版本升级,并且您没有覆盖消息格式,则只需覆盖 Inter-Broker 协议版本。
    • inter.broker.protocol.version=CURRENT_KAFKA_VERSION 的2.4,2.3等)
  2. 一次升级一个代理:关闭代理,更新代码,然后重新启动它。完成此作后, Broker 将运行最新版本,您可以验证集群的行为和性能是否符合预期。 如果有任何问题,此时仍然可以降级。
  3. 验证集群的行为和性能后,通过编辑来增加协议版本inter.broker.protocol.version并将其设置为2.5.
  4. 逐个重启 broker,新协议版本才能生效。一旦代理开始使用最新的 协议版本,则无法再将集群降级到旧版本。
  5. 如果您已按照上述说明覆盖了消息格式版本,则需要再执行一次滚动重启,以 将其升级到最新版本。所有(或大多数)消费者都升级到 0.11.0 或更高版本后, 将每个代理上的 log.message.format.version 更改为 2.5,然后逐个重新启动它们。请注意,较旧的 Scala 客户端 不再维护,不支持 0.11 中引入的 message 格式,从而避免转换成本 (或利用 Exactly once 语义)、 必须使用较新的 Java 客户端。
  6. 重新分配工具有几项显著变化kafka-reassign-partitions.shKIP-455 完成后。 此工具现在需要--additional标志,以便在更改 主动重新分配。现在可以使用--cancel命令。最后,使用--zookeeper已被弃用,取而代之的是--bootstrap-server.有关更多详细信息,请参阅 KIP。
2.5.0 中的显著更改
  • 什么时候RebalanceProtocol#COOPERATIVEConsumer#poll仍可返回数据 当它处于消费者仍然拥有的那些分区的再平衡过程中;另外Consumer#commitSync现在可能会抛出一个非致命的RebalanceInProgressException通知 用户此类事件,为了区分致命的CommitFailedException并允许 users 完成正在进行的再平衡,然后重新尝试为那些仍然拥有的分区提交偏移量。
  • 为了提高典型网络环境中的弹性,默认值zookeeper.session.timeout.ms由 6 秒增加到 18 秒,并且replica.lag.time.max.ms从 10 秒到 30 秒。
  • 新的 DSL 运算符cogroup()已添加,以便一次将多个流聚合在一起。
  • 添加了一个新的KStream.toTable()用于将输入事件流转换为 KTable 的 API。
  • 添加了新的 Serde 类型Void表示 Input 主题中的 Null 键或 Null 值。
  • 荒废的UsePreviousTimeOnInvalidTimestamp并将其替换为UsePartitionTimeOnInvalidTimeStamp.
  • 通过添加待处理的偏移隔离机制和更强的事务提交,改进了 exactly-once 语义 一致性检查,这大大简化了可扩展的 Exactly-Once 应用程序的实现。 我们还在 examples 文件夹下添加了一个新的 exactly-once 语义代码示例。查看 KIP-447 了解完整详细信息。
  • 添加了新的公共 APIKafkaStreams.queryMetadataForKey(String, K, Serializer) to get detailed information on the key being queried. It provides information about the partition number where the key resides in addition to hosts containing the active and standby partitions for the key.
  • 通过弃用,支持查询过时的存储(以实现高可用性)和属于特定分区的存储KafkaStreams.store(String, QueryableStoreType)并将其替换为KafkaStreams.store(StoreQueryParameters).
  • 添加了一个新的公共 API,用于访问实例本地存储的滞后信息,其中包含KafkaStreams.allLocalStorePartitionLags().
  • Scala 2.11 不再受支持。有关详细信息,请参阅 KIP-531
  • 包中的所有 Scala 类kafka.security.auth已被弃用。请参阅 KIP-504,了解 2.4.0 中添加的新 Java 授权方 API 的详细信息。请注意,kafka.security.auth.Authorizerkafka.security.auth.SimpleAclAuthorizer在 2.4.0 中已弃用。
  • TLSv1 和 TLSv1.1 默认处于禁用状态,因为它们具有已知的安全漏洞。现在只有 TLSv1.2 默认启用。您可以通过在配置选项中显式启用 TLSv1 和 TLSv1.1 来继续使用它们ssl.protocolssl.enabled.protocols.
  • ZooKeeper 已升级到 3.5.7,如果 3.4 数据目录中没有快照文件,则从 3.4.X 到 3.5.7 的 ZooKeeper 升级可能会失败。 这通常发生在测试升级中,其中 ZooKeeper 3.5.7 尝试加载尚未创建快照文件的现有 3.4 数据目录。 有关此问题的更多详细信息,请参阅 ZOOKEEPER-3056ZOOKEEPER-3056 中给出了一个修复方法,即将snapshot.trust.empty=trueconfig 中zookeeper.properties升级前。
  • ZooKeeper 版本 3.5.7 支持与 ZooKeeper 的 TLS 加密连接,无论是否使用客户端证书, 以及其他 Kafka 配置可用于利用这一点。 有关详细信息,请参阅 KIP-515

从 0.8.x、0.9.x、0.10.0.x、0.10.1.x、0.10.2.x、0.11.0.x、1.0.x、1.1.x、2.0.x 或 2.1.x 或 2.2.x 或 2.3.x 升级到 2.4.0

如果您从 2.1.x 之前的版本升级,请参阅下面的说明,了解用于存储使用者偏移量的架构的更改。 将 inter.broker.protocol.version 更改为最新版本后,将无法降级到 2.1 之前的版本。

对于滚动升级:

  1. 更新所有代理上的 server.properties 并添加以下属性。CURRENT_KAFKA_VERSION 是指您 正在升级。CURRENT_MESSAGE_FORMAT_VERSION 是指当前正在使用的消息格式版本。如果您之前有 覆盖了 Message Format version,则应保留其当前值。或者,如果您要从之前的版本升级 设置为 0.11.0.x,则CURRENT_MESSAGE_FORMAT_VERSION应设置为 MATCH CURRENT_KAFKA_VERSION。
    • inter.broker.protocol.version=CURRENT_KAFKA_VERSION (例如 0.10.0、0.11.0、1.0、2.0、2.2)。
    • log.message.format.version=CURRENT_MESSAGE_FORMAT_VERSION (查看潜在的性能影响) 有关此配置的作用的详细信息。
    如果您从版本 0.11.0.x 或更高版本升级,并且您没有覆盖消息格式,则只需覆盖 Inter-Broker 协议版本。
    • inter.broker.protocol.version=CURRENT_KAFKA_VERSION (0.11.0, 1.0, 1.1, 2.0, 2.1, 2.2, 2.3).
  2. 一次升级一个代理:关闭代理,更新代码,然后重新启动它。完成此作后, Broker 将运行最新版本,您可以验证集群的行为和性能是否符合预期。 如果有任何问题,此时仍然可以降级。
  3. 验证集群的行为和性能后,通过编辑来增加协议版本inter.broker.protocol.version并将其设置为 2.4。
  4. 逐个重启 broker,新协议版本才能生效。一旦代理开始使用最新的 协议版本,则无法再将集群降级到旧版本。
  5. 如果您已按照上述说明覆盖了消息格式版本,则需要再执行一次滚动重启,以 将其升级到最新版本。所有(或大多数)消费者都升级到 0.11.0 或更高版本后, 将 log.message.format.version 更改为 2.4,然后逐个重启。请注意,较旧的 Scala 客户端 不再维护,不支持 0.11 中引入的 message 格式,从而避免转换成本 (或利用 Exactly once 语义)、 必须使用较新的 Java 客户端。

其他升级说明:

  1. ZooKeeper 已升级到 3.5.6。如果 3.4 数据目录中没有快照文件,则 ZooKeeper 从 3.4.X 升级到 3.5.6 可能会失败。 这通常发生在测试升级中,其中 ZooKeeper 3.5.6 尝试加载尚未创建快照文件的现有 3.4 数据目录。 有关此问题的更多详细信息,请参阅 ZOOKEEPER-3056ZOOKEEPER-3056 中给出了一个修复方法,即将snapshot.trust.empty=trueconfig 中zookeeper.properties升级前。但是,我们在使用snapshot.trust.empty=trueconfig。有关该问题的更多详细信息,请参阅 ZOOKEEPER-3644。 因此,我们建议将空快照文件复制到 3.4 数据目录 如果 3.4 数据目录中没有快照文件。有关解决方法的更多详细信息,请参阅 ZooKeeper 升级常见问题解答
  2. 在 ZooKeeper 3.5 中添加的基于 Jetty 的嵌入式 AdminServer。 AdminServer 在 ZooKeeper 中默认启用,并在端口 8080 上启动。 默认情况下,AdminServer 在 ZooKeeper 配置(zookeeper.properties) 由 Apache Kafka 发行版提供。 请务必更新您的本地zookeeper.properties文件替换为admin.enableServer=false如果您希望禁用 AdminServer。 请参考 AdminServer 配置 AdminServer。
2.4.0 中的显著变化
  • 添加了用于分区重新分配的新 Admin API。由于 Kafka 传播重新分配信息的方式发生了变化, 升级到新版本时,在失败的边缘情况下可能会丢失重新分配状态。建议不要在升级时开始重新分配。
  • ZooKeeper 已从 3.4.14 升级到 3.5.6。新版本支持 TLS 和动态重新配置。
  • bin/kafka-preferred-replica-election.sh命令行工具已弃用。它已被bin/kafka-leader-election.sh.
  • 方法electPreferredLeaders在 Java 中AdminClientclass 已被弃用,取而代之的是electLeaders.
  • Scala 代码利用NewTopic(String, int, short)构造函数将需要显式调用toShort在第二个文本上。
  • 构造函数中的参数GroupAuthorizationException(String)现在用于指定异常消息。 以前,它指的是授权失败的组。这样做是为了与其他异常类型保持一致,并 避免潜在的误用。构造函数TopicAuthorizationException(String)之前用于单个 未授权的话题也被类似地改变了。
  • 内部的PartitionAssignorinterface 已弃用并替换为新的ConsumerPartitionAssignor在公共 API 中。一些 方法/签名在两个接口之间略有不同。实现自定义 PartitionAssignor 的用户应尽快迁移到新接口。
  • DefaultPartitioner现在使用粘性分区策略。这意味着特定主题的记录具有 null 键且没有分配的分区 将发送到同一分区,直到该批次准备好发送为止。创建新批处理时,将选择新分区。这减少了 produce 的延迟,但 在边缘情况下,它可能会导致记录在分区之间的分布不均匀。通常,用户不会受到影响,但这种差异在测试和 其他情况会在很短的时间内生成记录。
  • 阻塞KafkaConsumer#committed方法已扩展为允许将分区列表作为输入参数,而不是单个分区。 它可以减少客户端和代理之间获取使用者组提交的偏移量的请求/响应迭代。 旧的重载函数已弃用,我们建议用户更改代码以利用新方法(详细信息 可以在 KIP-520 中找到)。
  • 我们引入了一个新的INVALID_RECORDerror 与CORRUPT_MESSAGE错误。 更具体地说,以前,当一批记录作为单个请求的一部分发送到 broker 并且一个或多个记录失败时 由于各种原因(魔术字节不匹配、CRC 校验和错误、日志压缩主题的空键等)导致的验证,整个批次将被拒绝 具有相同的误导性CORRUPT_MESSAGE,并且创建者客户端的调用方将看到来自以下任一 的未来对象RecordMetadatasendcall 以及Callback#onCompletion(RecordMetadata metadata, Exception exception)现在,有了新的错误代码和改进的异常错误消息,创建者调用者可以更好地了解其发送记录失败的根本原因。
  • 我们正在将增量协作再平衡引入客户端的组协议,这允许消费者在再平衡期间保留所有分配的分区 最后,仅撤销那些必须迁移到另一个使用者以实现整体集群平衡的 API。这ConsumerCoordinator将选择最新的RebalanceProtocol这通常受到 Consumer 的所有支持的 assignor 的支持。您可以使用新的内置CooperativeStickyAssignor或插入您自己的自定义 Cooperative Assignor。待办事项 因此,您必须实现ConsumerPartitionAssignor接口和 includeRebalanceProtocol.COOPERATIVE在 return by 返回的列表中ConsumerPartitionAssignor#supportedProtocols. 然后,您的自定义分配器可以利用ownedPartitions字段在每个使用者的Subscription尽可能将分区归还给以前的所有者。请注意,当 分区要重新分配给另一个消费者,必须将其从新分配中删除,直到它从其原始所有者处撤销。任何必须撤销分区的消费者都将触发 后续再平衡,以允许将已撤销的分区安全地分配给其新所有者。有关更多信息,请参见ConsumerPartitionAssignor RebalanceProtocol javadocs
    要从旧的 (eager) 协议(总是在重新平衡之前撤销所有分区)升级到协作式重新平衡,您必须遵循特定的升级路径以使所有客户端位于同一
    ConsumerPartitionAssignor支持合作协议。这可以通过两次滚动弹跳来完成,使用CooperativeStickyAssignor例如:在第一个作中,将 “cooperative-sticky” 添加到支持的分配器列表中 对于每个成员(不删除前一个分配者 - 请注意,如果以前使用默认值,则还必须显式包含该分配器)。然后,您可以退回和/或升级它。 一旦整个组都处于 2.4+ 状态,并且所有成员在其支持的分配器中都有 “cooperative-sticky”,则删除其他分配器并执行第二次滚动退回,以便到最后所有成员都只支持 合作协议。有关协作式再平衡协议和升级路径的更多详细信息,请参阅 KIP-429
  • 有一些行为变化ConsumerRebalanceListener以及新的 API。在侦听器的三个回调中的任何一个期间引发的异常将不再被吞噬,而是被重新引发 一直到Consumer.poll()叫。这onPartitionsLost方法,以允许用户对消费者可能失去其分区所有权的异常情况做出反应 (例如错过了 rebalance)并且无法提交偏移量。默认情况下,这将简单地调用现有的onPartitionsRevokedAPI 与之前的行为保持一致。但请注意,onPartitionsLost不会 当 LOST PARTITIONS 集为空时调用。这意味着,在加入组的新 Consumer 的第一次再平衡开始时,不会调用任何回调。
    的语义
    ConsumerRebalanceListener's当遵循上述 Cooperative Rebalancing 协议时,回调会进一步更改。除了onPartitionsLost,onPartitionsRevoked当已撤销的分区集为空时,也永远不会调用。回调通常仅在再平衡结束时调用,并且仅在要移动到另一个使用者的分区集上调用。这onPartitionsAssigned然而,即使分区集为空,也将始终调用 callback 作为通知用户 Rebalance 事件的一种方式(对于 cooperative 和 eager 都是如此)。有关详细信息 新的回调语义,请参见 ConsumerRebalanceListener javadocs
  • Scala 特征kafka.security.auth.Authorizer已弃用并替换为新的 Java APIorg.apache.kafka.server.authorizer.Authorizer.鉴权方实现类kafka.security.auth.SimpleAclAuthorizer也被弃用并替换为新的 实现kafka.security.authorizer.AclAuthorizer.AclAuthorizer使用功能 受新 API 支持,以改进授权日志记录,并与SimpleAclAuthorizer. 有关更多详细信息,请参阅 KIP-504

从 0.8.x、0.9.x、0.10.0.x、0.10.1.x、0.10.2.x、0.11.0.x、1.0.x、1.1.x、2.0.x 或 2.1.x 或 2.2.x 升级到 2.3.0

如果您从 2.1.x 之前的版本升级,请参阅下面的说明,了解用于存储使用者偏移量的架构的更改。 将 inter.broker.protocol.version 更改为最新版本后,将无法降级到 2.1 之前的版本。

对于滚动升级:

  1. 更新所有代理上的 server.properties 并添加以下属性。CURRENT_KAFKA_VERSION 是指您 正在升级。CURRENT_MESSAGE_FORMAT_VERSION 是指当前正在使用的消息格式版本。如果您之前有 覆盖了 Message Format version,则应保留其当前值。或者,如果您要从之前的版本升级 设置为 0.11.0.x,则CURRENT_MESSAGE_FORMAT_VERSION应设置为 MATCH CURRENT_KAFKA_VERSION。
    • inter.broker.protocol.version=CURRENT_KAFKA_VERSION(例如 0.8.2、0.9.0、0.10.0、0.10.1、0.10.2、0.11.0、1.0、1.1)。
    • log.message.format.version=CURRENT_MESSAGE_FORMAT_VERSION (查看潜在的性能影响) 有关此配置的作用的详细信息。
    如果要从 0.11.0.x、1.0.x、1.1.x、2.0.x 或 2.1.x 升级,并且尚未覆盖消息格式,则只需覆盖 Inter-Broker 协议版本。
    • inter.broker.protocol.version=CURRENT_KAFKA_VERSION (0.11.0, 1.0, 1.1, 2.0, 2.1, 2.2).
  2. 一次升级一个代理:关闭代理,更新代码,然后重新启动它。完成此作后, Broker 将运行最新版本,您可以验证集群的行为和性能是否符合预期。 如果有任何问题,此时仍然可以降级。
  3. 验证集群的行为和性能后,通过编辑来增加协议版本inter.broker.protocol.version并将其设置为 2.3。
  4. 逐个重启 broker,新协议版本才能生效。一旦代理开始使用最新的 协议版本,则无法再将集群降级到旧版本。
  5. 如果您已按照上述说明覆盖了消息格式版本,则需要再执行一次滚动重启,以 将其升级到最新版本。所有(或大多数)消费者都升级到 0.11.0 或更高版本后, 将每个代理上的 log.message.format.version 更改为 2.3,然后逐个重新启动它们。请注意,较旧的 Scala 客户端 不再维护,不支持 0.11 中引入的 message 格式,从而避免转换成本 (或利用 Exactly once 语义)、 必须使用较新的 Java 客户端。
2.3.0 中的显著变化
  • 我们正在为 Kafka Connect 引入一种基于增量协作再平衡的新再平衡协议。 新协议不要求在 Connect 工作程序之间的再平衡阶段停止所有任务。相反,只需要交换的任务 在 worker 之间停止,并在后续 rebalance 中启动。从 2.3.0 开始,新的 Connect 协议默认启用。 有关其工作原理以及如何启用预先再平衡的旧行为的更多详细信息,请查看增量协作再平衡设计
  • 我们正在向消费者用户引入静态成员资格。此功能可减少正常应用程序升级或滚动退回期间不必要的重新平衡。 有关如何使用它的更多详细信息,请查看静态成员资格设计
  • Kafka Streams DSL 会切换其使用的存储类型。虽然此更改主要对用户透明,但在某些极端情况下可能需要更改代码。 有关更多详细信息,请参阅 Kafka Streams 升级部分
  • Kafka Streams 2.3.0 需要 0.11 格式或更高版本的消息格式,并且不适用于较旧的消息格式。

从 0.8.x、0.9.x、0.10.0.x、0.10.1.x、0.10.2.x、0.11.0.x、1.0.x、1.1.x、2.0.x 或 2.1.x 升级到 2.2.0

如果您从 2.1.x 之前的版本升级,请参阅下面的说明,了解用于存储使用者偏移量的架构的更改。 将 inter.broker.protocol.version 更改为最新版本后,将无法降级到 2.1 之前的版本。

对于滚动升级:

  1. 更新所有代理上的 server.properties 并添加以下属性。CURRENT_KAFKA_VERSION 是指您 正在升级。CURRENT_MESSAGE_FORMAT_VERSION 是指当前正在使用的消息格式版本。如果您之前有 覆盖了 Message Format version,则应保留其当前值。或者,如果您要从之前的版本升级 设置为 0.11.0.x,则CURRENT_MESSAGE_FORMAT_VERSION应设置为 MATCH CURRENT_KAFKA_VERSION。
    • inter.broker.protocol.version=CURRENT_KAFKA_VERSION(例如 0.8.2、0.9.0、0.10.0、0.10.1、0.10.2、0.11.0、1.0、1.1)。
    • log.message.format.version=CURRENT_MESSAGE_FORMAT_VERSION (查看潜在的性能影响) 有关此配置的作用的详细信息。
    如果要从 0.11.0.x、1.0.x、1.1.x 或 2.0.x 升级,并且尚未覆盖消息格式,则只需覆盖 Inter-Broker 协议版本。
    • inter.broker.protocol.version=CURRENT_KAFKA_VERSION (0.11.0, 1.0, 1.1, 2.0).
  2. 一次升级一个代理:关闭代理,更新代码,然后重新启动它。完成此作后, Broker 将运行最新版本,您可以验证集群的行为和性能是否符合预期。 如果有任何问题,此时仍然可以降级。
  3. 验证集群的行为和性能后,通过编辑来增加协议版本inter.broker.protocol.version并将其设置为 2.2。
  4. 逐个重启 broker,新协议版本才能生效。一旦代理开始使用最新的 协议版本,则无法再将集群降级到旧版本。
  5. 如果您已按照上述说明覆盖了消息格式版本,则需要再执行一次滚动重启,以 将其升级到最新版本。所有(或大多数)消费者都升级到 0.11.0 或更高版本后, 将 log.message.format.version 修改为 2.2,然后逐个重启。请注意,较旧的 Scala 客户端 不再维护,不支持 0.11 中引入的 message 格式,从而避免转换成本 (或利用 Exactly once 语义)、 必须使用较新的 Java 客户端。
2.2.1 中的显著更改
  • Kafka Streams 2.2.1 需要 0.11 或更高的消息格式,并且不适用于较旧的消息格式。
2.2.0 中的显著变化
  • 默认消费组 ID 由空字符串 () 改为""null.使用新的默认 Group ID 的 Consumer 将无法订阅 Topic, 以及 fetch 或 commit offsets。作为使用者组 ID 的空字符串已弃用,但在将来的主要版本之前将受支持。依赖空字符串组 ID 的旧客户端现在将 必须显式地将其作为其 consumer 配置的一部分提供。有关更多信息,请参阅 KIP-289
  • bin/kafka-topics.sh命令行工具现在能够直接连接到代理--bootstrap-server而不是 Zookeeper。旧的--zookeeper选项目前仍然可用。请阅读 KIP-377 了解更多信息。
  • Kafka Streams 依赖于需要 MacOS 10.13 或更高版本的较新版本的 RocksDB。

从 0.8.x、0.9.x、0.10.0.x、0.10.1.x、0.10.2.x、0.11.0.x、1.0.x、1.1.x 或 2.0.0 升级到 2.1.0

请注意,2.1.x 包含对用于存储使用者偏移量的内部架构的更改。升级后 complete,则无法降级到以前的版本。有关更多详细信息,请参阅下面的滚动升级说明。

对于滚动升级:

  1. 更新所有代理上的 server.properties 并添加以下属性。CURRENT_KAFKA_VERSION 是指您 正在升级。CURRENT_MESSAGE_FORMAT_VERSION 是指当前正在使用的消息格式版本。如果您之前有 覆盖了 Message Format version,则应保留其当前值。或者,如果您要从之前的版本升级 设置为 0.11.0.x,则CURRENT_MESSAGE_FORMAT_VERSION应设置为 MATCH CURRENT_KAFKA_VERSION。
    • inter.broker.protocol.version=CURRENT_KAFKA_VERSION(例如 0.8.2、0.9.0、0.10.0、0.10.1、0.10.2、0.11.0、1.0、1.1)。
    • log.message.format.version=CURRENT_MESSAGE_FORMAT_VERSION (查看潜在的性能影响) 有关此配置的作用的详细信息。
    如果要从 0.11.0.x、1.0.x、1.1.x 或 2.0.x 升级,并且尚未覆盖消息格式,则只需覆盖 Inter-Broker 协议版本。
    • inter.broker.protocol.version=CURRENT_KAFKA_VERSION (0.11.0, 1.0, 1.1, 2.0).
  2. 一次升级一个代理:关闭代理,更新代码,然后重新启动它。完成此作后, Broker 将运行最新版本,您可以验证集群的行为和性能是否符合预期。 如果有任何问题,此时仍然可以降级。
  3. 验证集群的行为和性能后,通过编辑来增加协议版本inter.broker.protocol.version并将其设置为 2.1。
  4. 逐个重启 broker,新协议版本才能生效。一旦代理开始使用最新的 协议版本,则无法再将集群降级到旧版本。
  5. 如果您已按照上述说明覆盖了消息格式版本,则需要再执行一次滚动重启,以 将其升级到最新版本。所有(或大多数)消费者都升级到 0.11.0 或更高版本后, 将每个代理上的 log.message.format.version 更改为 2.1,然后逐个重新启动它们。请注意,较旧的 Scala 客户端 不再维护,不支持 0.11 中引入的 message 格式,从而避免转换成本 (或利用 Exactly once 语义)、 必须使用较新的 Java 客户端。

其他升级说明:

  1. 此版本中的偏移过期语义略有变化。根据新的语义,组中分区的偏移量将 当组订阅了相应的主题并且仍然处于活动状态(具有活跃的使用者)时,不会被删除。如果 group 变为 empty 在默认偏移保持期(或代理设置的保持期)过后,将删除其所有偏移量(除非该组变为 再次激活)。默认情况下,与不使用 Kafka 组管理的独立(简单)消费者关联的偏移量将被删除 offset 保留期(或 Broker 设置的保留期)自上次提交以来已过去。
  2. 控制台使用者的enable.auto.commitproperty (当 nogroup.id现在设置为false. 这是为了避免污染使用者协调器缓存,因为自动生成的组不太可能被其他使用者使用。
  3. 生产者retriesconfig 已更改为Integer.MAX_VALUE,正如我们介绍delivery.timeout.msKIP-91 中, 它为发送记录和从 broker 接收确认之间的总时间设置上限。默认情况下, 传输超时设置为 2 分钟。
  4. 默认情况下,MirrorMaker 现在会覆盖delivery.timeout.msInteger.MAX_VALUE什么时候 配置 Producer。如果您已覆盖retries为了更快地失败, 您将需要重写delivery.timeout.ms.
  5. ListGroupAPI 现在期望作为推荐的替代方案Describe Group对用户应能够列出的组的访问权限。 即使旧的Describe Cluster为了向后兼容,仍然支持 access,不建议将其用于此 API。
  6. KIP-336 弃用了 ExtendedSerializer 和 ExtendedDeserializer 接口以及 传播 Serializer 和 Deserializer 的用法。ExtendedSerializer 和 ExtendedDeserializer 随 KIP-82 一起引入,用于为序列化器和反序列化程序提供记录标头 以 Java 7 兼容的方式。现在,我们整合了这些接口,因为 Java 7 支持已经被放弃了。
2.1.0 中的显著更改
  • Jetty 已升级到 9.4.12,默认情况下不包括 TLS_RSA_* 密码,因为它们不支持转发 保密性,请参阅 https://github.com/eclipse/jetty.project/issues/2807 了解更多信息。
  • 在以下情况下,控制器会自动启用 Unclean leader 选举unclean.leader.election.enableconfig 使用按主题的 config override 动态更新。
  • AdminClient添加了一个方法AdminClient#metrics().现在,任何使用AdminClient可以获取更多信息 和 insight 通过查看从AdminClient.了解更多信息 参见 KIP-324
  • Kafka 现在支持从 KIP-110 开始的 Zstandard 压缩。 您必须升级代理和客户端才能使用它。2.1.0 之前的使用者将无法从使用 Z标准压缩,因此在所有下游使用者都升级之前,您不应为主题启用它。有关更多详细信息,请参阅 KIP。

从 0.8.x、0.9.x、0.10.0.x、0.10.1.x、0.10.2.x、0.11.0.x、1.0.x 或 1.1.x 升级到 2.0.0

Kafka 2.0.0 引入了有线协议更改。通过遵循下面推荐的滚动升级计划, 您保证在升级期间不会出现停机时间。但是,请在升级之前查看 2.0.0 中的显著更改

对于滚动升级:

  1. 更新所有代理上的 server.properties 并添加以下属性。CURRENT_KAFKA_VERSION 是指您 正在升级。CURRENT_MESSAGE_FORMAT_VERSION 是指当前正在使用的消息格式版本。如果您之前有 覆盖了 Message Format version,则应保留其当前值。或者,如果您要从之前的版本升级 设置为 0.11.0.x,则CURRENT_MESSAGE_FORMAT_VERSION应设置为 MATCH CURRENT_KAFKA_VERSION。
    • inter.broker.protocol.version=CURRENT_KAFKA_VERSION(例如 0.8.2、0.9.0、0.10.0、0.10.1、0.10.2、0.11.0、1.0、1.1)。
    • log.message.format.version=CURRENT_MESSAGE_FORMAT_VERSION (查看潜在的性能影响) 有关此配置的作用的详细信息。
    如果要从 0.11.0.x、1.0.x 或 1.1.x 升级,并且尚未覆盖消息格式,则只需覆盖 Inter-Broker 协议格式。
    • inter.broker.protocol.version=CURRENT_KAFKA_VERSION (0.11.0, 1.0, 1.1).
  2. 一次升级一个代理:关闭代理,更新代码,然后重新启动它。
  3. 升级整个集群后,通过编辑来增加协议版本inter.broker.protocol.version并将其设置为 2.0。
  4. 逐个重启 broker,新协议版本才能生效。
  5. 如果您已按照上述说明覆盖了消息格式版本,则需要再执行一次滚动重启,以 将其升级到最新版本。所有(或大多数)消费者都升级到 0.11.0 或更高版本后, 将 log.message.format.version 修改为 2.0,然后逐个重启。请注意,较旧的 Scala 使用者 不支持 0.11 中引入的新消息格式,因此为了避免下转换(或 利用 Exactly Once 语义),则必须使用较新的 Java 使用者。

其他升级说明:

  1. 如果您愿意接受停机,您可以简单地关闭所有代理,更新代码并重新启动它们。他们将开始 默认使用新协议。
  2. 升级 broker 后,可以随时更新协议版本并重新启动。它不必紧随其后。 消息格式版本也是如此。
  3. 如果您在 Kafka Streams 代码中使用 Java8 方法引用,则可能需要更新代码以解决方法歧义。 仅热交换 jar 文件可能不起作用。
  4. 不应将 ACL 添加到带前缀的资源中, (在 KIP-290 中添加), 直到集群中的所有代理都已更新。

    注意:如果集群再次降级,则即使在集群完全升级后,添加到集群的任何带前缀的 ACL 也将被忽略。

2.0.0 中的显著更改
  • KIP-186 将默认偏移保留时间从 1 天增加到 7 天。这使得在不经常提交的应用程序中 “丢失” 偏移量的可能性较小。它还会增加活动的偏移量集,因此会增加代理的内存使用量。请注意,控制台使用者目前默认启用偏移量提交,并且可能是大量偏移量的来源,此更改现在将保留 7 天,而不是 1 天。您可以通过设置 broker config 来保留现有行为offsets.retention.minutes到 1440 年。
  • 已删除对 Java 7 的支持,Java 8 现在是所需的最低版本。
  • 的默认值ssl.endpoint.identification.algorithm已更改为https执行主机名验证(否则可能会发生中间人攻击)。设置ssl.endpoint.identification.algorithm转换为空字符串以恢复之前的行为。
  • KAFKA-5674 延长了max.connections.per.ipminimum 到 0,因此允许对入站连接进行基于 IP 的筛选。
  • KIP-272 向指标添加了 API 版本标签kafka.network:type=RequestMetrics,name=RequestsPerSec,request={Produce|FetchConsumer|FetchFollower|...}. 此指标现在变为kafka.network:type=RequestMetrics,name=RequestsPerSec,request={Produce|FetchConsumer|FetchFollower|...},version={0|1|2|3|...}.这将影响 JMX 监控工具,这些工具不会自动聚合。要获取特定请求类型的总数,该工具需要为 更新为跨不同版本聚合。
  • KIP-225 更改了指标“records.lag”,以使用主题和分区的标签。名称格式为 “{topic}-{partition}.records-lag” 的原始版本已被删除。
  • 自 0.11.0.0 起已弃用的 Scala 使用者已被删除。Java 使用者是推荐的选项 从 0.10.0.0 开始。请注意,即使代理升级到 2.0.0,1.1.0(及更早版本)中的 Scala 使用者也将继续工作。
  • 自 0.10.0.0 起已弃用的 Scala 生产者已被删除。Java 生产者是推荐选项 从 0.9.0.0 开始。请注意,Java 生产者中默认分区程序的行为与默认分区程序不同 在 Scala 生产者中。迁移的用户应考虑配置一个保留先前行为的自定义分区程序。 请注意,即使代理升级到 2.0.0,1.1.0(及更早版本)中的 Scala 创建者也将继续工作。
  • MirrorMaker 和 ConsoleConsumer 不再支持 Scala 使用者,它们始终使用 Java 使用者。
  • ConsoleProducer 不再支持 Scala 生产者,它始终使用 Java 生产者。
  • 许多依赖于 Scala 客户端的已弃用工具已被删除:ReplayLogProducer、SimpleConsumerPerformance、SimpleConsumerShell、ExportZkOffsets、ImportZkOffsets、UpdateOffsetsInZK、VerifyConsumerRebalance。
  • 已弃用的 kafka.tools.ProducerPerformance 已被删除,请使用 org.apache.kafka.tools.ProducerPerformance。
  • 新的 Kafka Streams 配置参数upgrade.from添加了允许从旧版本进行滚动弹跳升级的功能。
  • KIP-284 通过将 Kafka Streams 重新分区主题的默认值设置为Long.MAX_VALUE.
  • 更新ProcessorStateManagerKafka Streams 中用于将状态存储注册到处理器拓扑的 API。有关更多详细信息,请阅读 Streams 升级指南
  • 在早期版本中,Connect 的工作程序配置需要internal.key.converterinternal.value.converter性能。 在 2.0 中,这些不再是必需的,并且默认为 JSON 转换器。 您可以安全地从 Connect 独立和分布式工作程序配置中删除这些属性:
    internal.key.converter=org.apache.kafka.connect.json.JsonConverter internal.key.converter.schemas.enable=false internal.value.converter=org.apache.kafka.connect.json.JsonConverter internal.value.converter.schemas.enable=false
  • KIP-266 添加了新的使用者配置default.api.timeout.ms指定要用于的默认超时KafkaConsumer可能阻止的 API。KIP 还为此类阻塞添加了重载 API 支持指定用于每个 API 的特定超时,而不是使用default.api.timeout.ms. 特别是,新的poll(Duration)添加了 API,它不会阻止动态分区分配。 旧的poll(long)API 已弃用,并将在未来版本中删除。还添加了重载 对于其他KafkaConsumer方法,如partitionsFor,listTopics,offsetsForTimes,beginningOffsets,endOffsetsclose那 take in aDuration.
  • 此外,作为 KIP-266 的一部分,默认值request.timeout.ms已更改为 30 秒。 之前的值略高于 5 分钟,以考虑再平衡所需的最长时间。 现在,我们将再平衡中的 JoinGroup 请求视为特殊情况,并使用从max.poll.interval.ms对于请求超时。所有其他请求类型都使用定义的超时 由request.timeout.ms
  • 内部方法kafka.admin.AdminClient.deleteRecordsBefore已被删除。鼓励用户迁移到org.apache.kafka.clients.admin.AdminClient.deleteRecords.
  • AclCommand 工具--producerconvenience 选项在给定主题上使用 KIP-277 更细粒度的 ACL。
  • KIP-176 去除 这--new-consumer所有基于消费者的工具的选项。此选项是多余的,因为新使用者会自动 如果定义了 --bootstrap-server,则使用。
  • KIP-290 增加了能力 在带前缀的资源上定义 ACL,例如任何以 'foo' 开头的主题。
  • KIP-283 改进了消息下转换 处理,这通常是一项占用大量内存的作。KIP 添加了一种机制,通过该机制,作将变得不那么占用内存 通过一次向下转换分区数据块,这有助于设置内存消耗的上限。随着这一改进,发生了FetchResponse协议行为,其中代理可能会在响应末尾发送具有无效偏移量的超大消息批次。 使用者客户端必须忽略此类超大消息,就像KafkaConsumer.

    KIP-283 还添加了新的主题和代理配置message.downconversion.enablelog.message.downconversion.enable分别 以控制是否启用下转换。禁用后,broker 不会执行任何下转换,而是发送UNSUPPORTED_VERSION错误。

  • 动态代理配置选项可以在启动代理之前使用 kafka-configs.sh 存储在 ZooKeeper 中。 此选项可用于避免在 server.properties 中存储明文密码,因为所有密码配置都可以加密存储在 ZooKeeper 中。
  • 现在,如果连接尝试失败,将重新解析 ZooKeeper 主机。但是,如果您的 ZooKeeper 主机名解析 添加到多个地址,并且其中一些地址无法访问,那么您可能需要增加连接超时zookeeper.connection.timeout.ms.
新协议版本
  • KIP-279:OffsetsForLeaderEpochResponse v1 引入了分区级别leader_epoch田。
  • KIP-219:提高因违反配额而受到限制的非集群作请求和响应的协议版本。
  • KIP-290:提高 ACL 创建、描述和删除请求和响应的协议版本。
升级 1.1 Kafka Streams 应用程序
  • 将 Streams 应用程序从 1.1 升级到 2.0 不需要升级代理。 Kafka Streams 2.0 应用程序可以连接到 2.0、1.1、1.0、0.11.0、0.10.2 和 0.10.1 代理(但无法连接到 0.10.0 代理)。
  • 请注意,在 2.0 中,我们删除了 1.0 之前已弃用的公共 API;利用这些已弃用的 API 的用户需要相应地更改代码。 有关更多详细信息,请参阅 2.0.0 中的 Streams API 更改

从 0.8.x、0.9.x、0.10.0.x、0.10.1.x、0.10.2.x、0.11.0.x 或 1.0.x 升级到 1.1.x

Kafka 1.1.0 引入了有线协议更改。通过遵循下面推荐的滚动升级计划, 您保证在升级期间不会出现停机时间。但是,请在升级之前查看 1.1.0 中的显著更改

对于滚动升级:

  1. 更新所有代理上的 server.properties 并添加以下属性。CURRENT_KAFKA_VERSION 是指您 正在升级。CURRENT_MESSAGE_FORMAT_VERSION 是指当前正在使用的消息格式版本。如果您之前有 覆盖了 Message Format version,则应保留其当前值。或者,如果您要从之前的版本升级 设置为 0.11.0.x,则CURRENT_MESSAGE_FORMAT_VERSION应设置为 MATCH CURRENT_KAFKA_VERSION。
    • inter.broker.protocol.version=CURRENT_KAFKA_VERSION (例如 0.8.2、0.9.0、0.10.0、0.10.1、0.10.2、0.11.0、1.0)。
    • log.message.format.version=CURRENT_MESSAGE_FORMAT_VERSION (查看潜在的性能影响) 有关此配置的作用的详细信息。
    如果要从 0.11.0.x 或 1.0.x 升级,并且尚未覆盖消息格式,则只需覆盖 Inter-Broker 协议格式。
    • inter.broker.protocol.version=CURRENT_KAFKA_VERSION(0.11.0 或 1.0)。
  2. 一次升级一个代理:关闭代理,更新代码,然后重新启动它。
  3. 升级整个集群后,通过编辑来增加协议版本inter.broker.protocol.version并将其设置为 1.1。
  4. 逐个重启 broker,新协议版本才能生效。
  5. 如果您已按照上述说明覆盖了消息格式版本,则需要再执行一次滚动重启,以 将其升级到最新版本。所有(或大多数)消费者都升级到 0.11.0 或更高版本后, 将 log.message.format.version 修改为 1.1,然后逐个重启。请注意,较旧的 Scala 使用者 不支持 0.11 中引入的新消息格式,因此为了避免下转换(或 利用 Exactly Once 语义),则必须使用较新的 Java 使用者。

其他升级说明:

  1. 如果您愿意接受停机,您可以简单地关闭所有代理,更新代码并重新启动它们。他们将开始 默认使用新协议。
  2. 升级 broker 后,可以随时更新协议版本并重新启动。它不必紧随其后。 消息格式版本也是如此。
  3. 如果您在 Kafka Streams 代码中使用 Java8 方法引用,则可能需要更新代码以解决方法歧义。 仅热交换 jar 文件可能不起作用。
1.1.1 中的显著变化
  • 新的 Kafka Streams 配置参数upgrade.from添加了允许从版本 0.10.0.x 进行滚动弹跳升级的功能
  • 请参阅 Kafka Streams 升级指南 有关此新配置的详细信息。
1.1.0 中的显著变化
  • Maven 中的 kafka 工件不再依赖于 log4j 或 slf4j-log4j12。与 kafka-clients 工件类似,用户 现在,可以通过包含适当的 SLF4j 模块(SLF4J-Log4J12、LOGBack 等)来选择日志记录后端。发布 tarball 仍然包括 log4j 和 slf4j-log4j12。
  • KIP-225 更改了指标“records.lag”,以使用主题和分区的标签。名称格式为“{topic}-{partition}.records-lag”的原始版本已弃用,并将在 2.0.0 中删除。
  • Kafka Streams 在防止代理通信错误方面更健壮。而不是停止 Kafka Streams 客户端并显示致命异常, Kafka Streams 会尝试自我修复并重新连接到集群。使用新的AdminClient您可以更好地控制频率 Kafka Streams 重试,并且可以配置精细超时(而不是旧版本中的硬编码重试)。
  • Kafka Streams 再平衡时间进一步缩短,使 Kafka Streams 的响应速度更快。
  • Kafka Connect 现在支持 Sink 和 Source Connector 中的消息标头,并通过简单的消息转换对其进行作。必须更改连接器才能显式使用它们。新的HeaderConverter用于控制 Headers 的 (反) 序列化方式,并且默认使用新的 “SimpleHeaderConverter” 来使用值的字符串表示形式。
  • 如果启用了 print-data-log,kafka.tools.DumpLogSegments 现在会自动设置 deep-iteration 选项 显式或隐式地由于任何其他选项(如 decoder)而显式或隐式地使用。
新协议版本
  • KIP-226 引入了 DescribeConfigs 请求/响应 v1。
  • KIP-227 引入了 Fetch Request/Response v7。
升级 1.0 Kafka Streams 应用程序
  • 将 Streams 应用程序从 1.0 升级到 1.1 不需要升级代理。 Kafka Streams 1.1 应用程序可以连接到 1.0、0.11.0、0.10.2 和 0.10.1 代理(但无法连接到 0.10.0 代理)。
  • 有关更多详细信息,请参阅 1.1.0 中的 Streams API 更改

从 0.8.x、0.9.x、0.10.0.x、0.10.1.x、0.10.2.x 或 0.11.0.x 升级到 1.0.0

Kafka 1.0.0 引入了有线协议更改。通过遵循下面推荐的滚动升级计划, 您保证在升级期间不会出现停机时间。但是,请在升级之前查看 1.0.0 中的显著更改

对于滚动升级:

  1. 更新所有代理上的 server.properties 并添加以下属性。CURRENT_KAFKA_VERSION 是指您 正在升级。CURRENT_MESSAGE_FORMAT_VERSION 是指当前正在使用的消息格式版本。如果您之前有 覆盖了 Message Format version,则应保留其当前值。或者,如果您要从之前的版本升级 设置为 0.11.0.x,则CURRENT_MESSAGE_FORMAT_VERSION应设置为 MATCH CURRENT_KAFKA_VERSION。
    • inter.broker.protocol.version=CURRENT_KAFKA_VERSION (例如 0.8.2、0.9.0、0.10.0、0.10.1、0.10.2、0.11.0)。
    • log.message.format.version=CURRENT_MESSAGE_FORMAT_VERSION (查看潜在的性能影响) 有关此配置的作用的详细信息。
    如果要从 0.11.0.x 升级,并且尚未覆盖消息格式,则必须将 消息格式版本和 Inter-Broker 协议版本都设置为 0.11.0。
    • inter.broker.protocol.version=0.11.0
    • log.message.format.version=0.11.0
  2. 一次升级一个代理:关闭代理,更新代码,然后重新启动它。
  3. 升级整个集群后,通过编辑来增加协议版本inter.broker.protocol.version并将其设置为 1.0。
  4. 逐个重启 broker,新协议版本才能生效。
  5. 如果您已按照上述说明覆盖了消息格式版本,则需要再执行一次滚动重启,以 将其升级到最新版本。所有(或大多数)消费者都升级到 0.11.0 或更高版本后, 将每个 broker 上的 log.message.format.version 更改为 1.0,然后逐个重新启动它们。如果要从 0.11.0 且 log.message.format.version 设置为 0.11.0,则可以更新配置并跳过滚动重启。 请注意,较旧的 Scala consumer 不支持 0.11 中引入的新消息格式,因此为了避免 下转换的性能成本(或利用 Exactly Once 语义), 必须使用较新的 Java 使用者。

其他升级说明:

  1. 如果您愿意接受停机,您可以简单地关闭所有代理,更新代码并重新启动它们。他们将开始 默认使用新协议。
  2. 升级 broker 后,可以随时更新协议版本并重新启动。它不必紧随其后。 消息格式版本也是如此。
1.0.2 中的显著变化
  • 新的 Kafka Streams 配置参数upgrade.from添加了允许从版本 0.10.0.x 进行滚动弹跳升级的功能
  • 请参阅 Kafka Streams 升级指南 有关此新配置的详细信息。
1.0.1 中的显著变化
  • 恢复了 AdminClient 的 Options 类(例如 CreateTopicsOptions、DeleteTopicsOptions 等)与 0.11.0.x 的二进制(但不是源)兼容性在 1.0.0 中被无意中破坏了。
1.0.0 中的显著更改
  • 主题删除现在默认启用,因为该功能现在很稳定。希望 要保留之前的行为,应将 broker configdelete.topic.enablefalse.请记住,主题删除会删除数据,并且该作是不可逆的(即没有“取消删除”作)
  • 对于支持时间戳搜索的主题,如果找不到分区的偏移量,则该分区现在包含在搜索结果中,并带有 null 偏移值。以前,分区不包括在 map 中。 进行此更改是为了使搜索行为与不支持时间戳搜索的主题的情况一致。
  • 如果inter.broker.protocol.version是 1.0 或更高版本,代理现在将保持联机以提供副本 在实时日志目录上,即使存在离线日志目录。日志目录可能会因 IOException 而脱机 由硬件故障引起。用户需要监控每个代理的指标offlineLogDirectoryCount检查 是否有离线日志目录。
  • 添加了 KafkaStorageException,这是一个可重试的异常。KafkaStorageException 将在响应中转换为 NotLeaderForPartitionException 如果客户端的 FetchRequest 或 ProducerRequest 版本不支持 KafkaStorageException。
  • 在默认 JVM 设置中,-XX:+DisableExplicitGC 已替换为 -XX:+ExplicitGCInvokesConcurrent。这有助于 在某些情况下,避免在直接缓冲区分配本机内存期间出现内存不足异常。
  • 被覆盖的handleError方法实现已从 这kafka.api包:FetchRequest,GroupCoordinatorRequest,OffsetCommitRequest,OffsetFetchRequest,OffsetRequest,ProducerRequestTopicMetadataRequest. 这仅用于代理,但已不再使用,并且尚未维护实现。 为了二进制兼容性,保留了存根实现。
  • Java 客户端和工具现在接受任何字符串作为 client-id。
  • 已弃用的工具kafka-consumer-offset-checker.sh已被删除。用kafka-consumer-groups.sh以获取 Consumer Group 详细信息。
  • 现在,默认情况下,SimpleAclAuthorizer 会将访问拒绝记录到授权方日志中。
  • 身份验证失败现在作为 的子类之一报告给客户端AuthenticationException. 如果客户端连接身份验证失败,则不会执行重试。
  • 习惯SaslServerimplementations 可能会抛出SaslAuthenticationException提供错误 消息返回给客户端,指示身份验证失败的原因。实现者应注意不要包含 异常消息中不应泄露给未经身份验证的客户端的任何安全关键信息。
  • app-info向 JMX 注册以提供版本和提交 ID 的 mbean 将被弃用并替换为 提供这些属性的指标。
  • Kafka 指标现在可能包含非数字值。org.apache.kafka.common.Metric#value()已被弃用,并且 将返回0.0在这种情况下,为了最大限度地降低打破读取每个客户端值的用户的可能性 度量(通过MetricsReporter实现或通过调用metrics()方法)。org.apache.kafka.common.Metric#metricValue()可用于检索数字和非数字度量值。
  • 现在,每个 Kafka 速率指标都有一个相应的累积计数指标,其后缀为-total简化下游处理。例如records-consumed-rate具有相应的 名为records-consumed-total.
  • Mx4j 仅在 system 属性kafka_mx4jenable设置为true.由于逻辑 inversion 错误,它之前默认启用,如果kafka_mx4jenable设置为true.
  • 包装org.apache.kafka.common.security.auth在 clients 中,jar 已公开并添加到 JavaDocs 中。 以前位于此包中的 Internal 类已移至其他位置。
  • 当使用 Authorizer 并且用户对主题没有所需的权限时,代理 将TOPIC_AUTHORIZATION_FAILED错误返回给请求,而不管 broker 上是否存在主题。 如果用户具有所需的权限,但主题不存在,则 UNKNOWN_TOPIC_OR_PARTITION 将返回错误代码。
  • config/consumer.properties 文件已更新为使用新的 Consumer Config 属性。
新协议版本
  • KIP-112:LeaderAndIsrRequest v1 引入了分区级别is_new田。
  • KIP-112:UpdateMetadataRequest v4 引入了分区级别offline_replicas田。
  • KIP-112:MetadataResponse v5 引入了分区级offline_replicas田。
  • KIP-112:ProduceResponse v4 引入了 KafkaStorageException 的错误代码。
  • KIP-112:FetchResponse v6 引入了 KafkaStorageException 的错误代码。
  • KIP-152: 添加了 SaslAuthenticate 请求,以启用身份验证失败的报告。此请求将 如果 SaslHandshake 请求版本大于 0,则使用。
升级 0.11.0 Kafka Streams 应用程序
  • 将 Streams 应用程序从 0.11.0 升级到 1.0 不需要代理升级。 Kafka Streams 1.0 应用程序可以连接到 0.11.0、0.10.2 和 0.10.1 代理(但无法连接到 0.10.0 代理)。 但是,Kafka Streams 1.0 需要 0.10 或更新的消息格式,并且不适用于较旧的消息格式。
  • 如果您正在监控流指标,则需要对报告和监控代码中的指标名称进行一些更改,因为指标传感器层次结构已更改。
  • 有一些公共 API,包括ProcessorContext#schedule(),Processor#punctuate()KStreamBuilder,TopologyBuilder正在被新的 API 弃用。 我们建议您在升级时进行相应的代码更改,这些更改应该非常小,因为新 API 看起来非常相似。
  • 有关更多详细信息,请参阅 1.0.0 中的 Streams API 更改
升级 0.10.2 Kafka Streams 应用程序
  • 将 Streams 应用程序从 0.10.2 升级到 1.0 不需要升级代理。 Kafka Streams 1.0 应用程序可以连接到 1.0、0.11.0、0.10.2 和 0.10.1 代理(但无法连接到 0.10.0 代理)。
  • 如果您正在监控流指标,则需要对报告和监控代码中的指标名称进行一些更改,因为指标传感器层次结构已更改。
  • 有一些公共 API,包括ProcessorContext#schedule(),Processor#punctuate()KStreamBuilder,TopologyBuilder正在被新的 API 弃用。 我们建议您在升级时进行相应的代码更改,这些更改应该非常小,因为新 API 看起来非常相似。
  • 如果指定 customizedkey.serde,value.serdetimestamp.extractor在 Config 中,建议使用其替换的 configure 参数,因为这些配置已被弃用。
  • 有关更多详细信息,请参阅 0.11.0 中的 Streams API 更改
升级 0.10.1 Kafka Streams 应用程序
  • 将 Streams 应用程序从 0.10.1 升级到 1.0 不需要代理升级。 Kafka Streams 1.0 应用程序可以连接到 1.0、0.11.0、0.10.2 和 0.10.1 代理(但无法连接到 0.10.0 代理)。
  • 您需要重新编译代码。仅交换 Kafka Streams 库 jar 文件将不起作用,并且会破坏您的应用程序。
  • 如果您正在监控流指标,则需要对报告和监控代码中的指标名称进行一些更改,因为指标传感器层次结构已更改。
  • 有一些公共 API,包括ProcessorContext#schedule(),Processor#punctuate()KStreamBuilder,TopologyBuilder正在被新的 API 弃用。 我们建议您在升级时进行相应的代码更改,这些更改应该非常小,因为新 API 看起来非常相似。
  • 如果指定 customizedkey.serde,value.serdetimestamp.extractor在 Config 中,建议使用其替换的 configure 参数,因为这些配置已被弃用。
  • 如果您使用自定义(即用户实现的)时间戳提取器,则需要更新此代码,因为TimestampExtractor界面已更改。
  • 如果您注册自定义指标,则需要更新此代码,因为StreamsMetric界面已更改。
  • 有关更多详细信息,请参阅 1.0.0 中的 Streams API 更改0.11.0 中的 Streams API 更改0.10.2 中的 Streams API 更改
升级 0.10.0 Kafka Streams 应用程序
  • 将 Streams 应用程序从 0.10.0 升级到 1.0 确实需要升级代理,因为 Kafka Streams 1.0 应用程序只能连接到 0.1、0.11.0、0.10.2 或 0.10.1 代理。
  • 有一些 API 更改不向后兼容(有关更多详细信息,请参阅 1.0.0 中的 Streams API 更改0.11.0 中的 Streams API 更改0.10.2 中的 Streams API 更改0.10.1 中的 Streams API 更改)。 因此,您需要更新并重新编译您的代码。仅交换 Kafka Streams 库 jar 文件将不起作用,并且会破坏您的应用程序。
  • 从 0.10.0.x 升级到 1.0.2 需要使用 config 进行两次滚动退回upgrade.from="0.10.0"设置为第一个升级阶段 (参见 KIP-268)。 作为替代方案,也可以进行离线升级。
    • 为滚动退回准备应用程序实例,并确保 configupgrade.from设置为"0.10.0"新版本 0.11.0.3
    • 退回应用程序的每个实例一次
    • 为新部署的 1.0.2 应用程序实例准备第二轮滚动退回;确保删除 config 的值upgrade.from
    • 再次退回应用程序的每个实例以完成升级
  • 从 0.10.0.x 升级到 1.0.0 或 1.0.1 需要离线升级(不支持滚动弹跳升级)
    • 停止所有旧的 (0.10.0.x) 应用程序实例
    • 更新您的代码,并将旧代码和 JAR 文件替换为新代码和新 JAR 文件
    • 重新启动所有新的(1.0.0 或 1.0.1)应用程序实例

从 0.8.x、0.9.x、0.10.0.x、0.10.1.x 或 0.10.2.x 升级到 0.11.0.0

Kafka 0.11.0.0 引入了新的消息格式版本以及有线协议更改。通过遵循下面推荐的滚动升级计划, 您保证在升级期间不会出现停机时间。但是,请在升级之前查看 0.11.0.0 中的显著更改

从版本 0.10.2 开始,Java 客户端(生产者和使用者)已获得与旧代理通信的能力。版本 0.11.0 客户端可以与 0.10.0 或更高版本的代理通信。但是,如果您的代理版本低于 0.10.0,则必须升级 Kafka 集群。版本 0.11.0 代理支持 0.8.x 和更新的客户端。

对于滚动升级:

  1. 更新所有代理上的 server.properties 并添加以下属性。CURRENT_KAFKA_VERSION 是指您 正在升级。CURRENT_MESSAGE_FORMAT_VERSION 是指当前正在使用的消息格式版本。如果你有 之前未覆盖消息格式,则应将 CURRENT_MESSAGE_FORMAT_VERSION 设置为 MATCH CURRENT_KAFKA_VERSION。
    • inter.broker.protocol.version=CURRENT_KAFKA_VERSION (例如 0.8.2、0.9.0、0.10.0、0.10.1 或 0.10.2)。
    • log.message.format.version=CURRENT_MESSAGE_FORMAT_VERSION (查看潜在的性能影响) 有关此配置的作用的详细信息。
  2. 一次升级一个代理:关闭代理,更新代码,然后重新启动它。
  3. 升级整个集群后,通过编辑来增加协议版本inter.broker.protocol.version并将其设置为 0.11.0,但 不更改log.message.format.version还。
  4. 逐个重启 broker,新协议版本才能生效。
  5. 将所有(或大多数)使用者升级到 0.11.0 或更高版本后,将每个使用者的 log.message.format.version 更改为 0.11.0 broker 并逐个重新启动它们。请注意,较旧的 Scala 使用者不支持新的 message 格式,因此要避免 下转换的性能成本(或利用 Exactly once 语义), 必须使用新的 Java 使用者。

其他升级说明:

  1. 如果您愿意接受停机,您可以简单地关闭所有代理,更新代码并重新启动它们。他们将开始 默认使用新协议。
  2. 升级 broker 后,可以随时更新协议版本并重新启动。它不必紧随其后。 消息格式版本也是如此。
  3. 也可以使用主题管理工具 (bin/kafka-topics.sh) 更新全局设置之前log.message.format.version.
  4. 如果您从 0.10.0 之前的版本升级,则无需先将消息格式更新为 0.10.0 在切换到 0.11.0 之前。
升级 0.10.2 Kafka Streams 应用程序
  • 将 Streams 应用程序从 0.10.2 升级到 0.11.0 不需要升级代理。 Kafka Streams 0.11.0 应用程序可以连接到 0.11.0、0.10.2 和 0.10.1 代理(但无法连接到 0.10.0 代理)。
  • 如果指定 customizedkey.serde,value.serdetimestamp.extractor在 Config 中,建议使用其替换的 configure 参数,因为这些配置已被弃用。
  • 有关更多详细信息,请参阅 0.11.0 中的 Streams API 更改
升级 0.10.1 Kafka Streams 应用程序
  • 将 Streams 应用程序从 0.10.1 升级到 0.11.0 不需要代理升级。 Kafka Streams 0.11.0 应用程序可以连接到 0.11.0、0.10.2 和 0.10.1 代理(但无法连接到 0.10.0 代理)。
  • 您需要重新编译代码。仅交换 Kafka Streams 库 jar 文件将不起作用,并且会破坏您的应用程序。
  • 如果指定 customizedkey.serde,value.serdetimestamp.extractor在 Config 中,建议使用其替换的 configure 参数,因为这些配置已被弃用。
  • 如果您使用自定义(即用户实现的)时间戳提取器,则需要更新此代码,因为TimestampExtractor界面已更改。
  • 如果您注册自定义指标,则需要更新此代码,因为StreamsMetric界面已更改。
  • 有关更多详细信息,请参阅 0.11.0 中的 Streams API 更改0.10.2 中的 Streams API 更改
升级 0.10.0 Kafka Streams 应用程序
  • 将 Streams 应用程序从 0.10.0 升级到 0.11.0 确实需要升级代理,因为 Kafka Streams 0.11.0 应用程序只能连接到 0.11.0、0.10.2 或 0.10.1 代理。
  • 有几个 API 更改不向后兼容(有关详细信息,请参阅 0.11.0 中的 Streams API 更改0.10.2 中的 Streams API 更改0.10.1 中的 Streams API 更改)。 因此,您需要更新并重新编译您的代码。仅交换 Kafka Streams 库 jar 文件将不起作用,并且会破坏您的应用程序。
  • 从 0.10.0.x 升级到 0.11.0.3 需要使用 config 进行两次滚动退回upgrade.from="0.10.0"设置为第一个升级阶段 (参见 KIP-268)。 作为替代方案,也可以进行离线升级。
    • 为滚动退回准备应用程序实例,并确保 configupgrade.from设置为"0.10.0"新版本 0.11.0.3
    • 退回应用程序的每个实例一次
    • 为新部署的 0.11.0.3 应用程序实例准备第二轮滚动退回;确保删除 config 的值upgrade.from
    • 再次退回应用程序的每个实例以完成升级
  • 从 0.10.0.x 升级到 0.11.0.0、0.11.0.1 或 0.11.0.2 需要离线升级(不支持滚动退回升级)
    • 停止所有旧的 (0.10.0.x) 应用程序实例
    • 更新您的代码,并将旧代码和 JAR 文件替换为新代码和新 JAR 文件
    • 重新启动所有新的(0.11.0.0、0.11.0.1 或 0.11.0.2)应用程序实例
0.11.0.3 中的显著变化
  • 新的 Kafka Streams 配置参数upgrade.from添加了允许从版本 0.10.0.x 进行滚动弹跳升级的功能
  • 请参阅 Kafka Streams 升级指南 有关此新配置的详细信息。
0.11.0.0 中的显著变化
  • Unclean leader 选举现在默认处于禁用状态。新的默认值更倾向于持久性而不是可用性。希望 要保留之前的行为,应将 broker configunclean.leader.election.enabletrue.
  • 生产者配置block.on.buffer.full,metadata.fetch.timeout.mstimeout.ms一直 删除。它们最初在 Kafka 0.9.0.0 中被弃用。
  • offsets.topic.replication.factor现在,在自动创建主题时强制执行 Broker Config。内部 自动主题创建将失败并显示 GROUP_COORDINATOR_NOT_AVAILABLE 错误,直到集群大小满足此错误 复制因子要求。
  • 使用 snappy 压缩数据时,创建者和代理将使用压缩方案的默认块大小 (2 x 32 KB) 而不是 1 KB,以提高压缩率。有报道称,使用较小的 块大小比使用较大块大小压缩时大 50%。对于快速的情况,具有 5000 个 分区将需要额外的 315 MB JVM 堆。
  • 同样,当使用 gzip 压缩数据时,创建者和代理将使用 8 KB 而不是 1 KB 作为缓冲区大小。默认的 因为 gzip 过低(512 字节)。
  • 代理配置max.message.bytes现在适用于一批消息的总大小。 以前,该设置应用于批量压缩消息,或单独应用于非压缩消息。 消息批次可能仅包含一条消息,因此在大多数情况下, 单个消息仅因批处理格式的开销而减少。然而,也有一些微妙的含义 对于消息格式转换(有关更多详细信息,请参阅下文)。另请注意 虽然以前 broker 会确保每个 fetch 请求中至少返回一条消息(无论 total 和分区级 fetch 大小),相同的行为现在适用于一个消息批次。
  • GC 日志轮换默认开启,详见 KAFKA-3754。
  • 已删除 RecordMetadata、MetricName 和 Cluster 类的已弃用构造函数。
  • 通过新的 Headers 界面添加了用户标头支持,从而提供用户标头读取和写入访问权限。
  • ProducerRecord 和 ConsumerRecord 通过Headers headers()方法调用。
  • 引入了 ExtendedSerializer 和 ExtendedDeserializer 接口以支持 Headers 的序列化和反序列化。如果配置的 serializer 和 deserializer 不是上述 class,则 Headers 将被忽略。
  • 新配置group.initial.rebalance.delay.ms。 此配置指定GroupCoordinator将延迟初始 Consumer 再平衡。 再平衡将进一步延迟group.initial.rebalance.delay.ms当新成员加入群组时,最多可添加max.poll.interval.ms. 默认值为 3 秒。 在开发和测试期间,可能需要将此设置为 0,以免延迟测试执行时间。
  • org.apache.kafka.common.Cluster#partitionsForTopic,partitionsForNodeavailablePartitionsForTopic方法 将返回一个空列表,而不是null(这被认为是一种不好的做法),以防所需主题的元数据不存在。
  • Streams API 配置参数timestamp.extractor,key.serdevalue.serde已弃用,并且 替换为default.timestamp.extractor,default.key.serdedefault.value.serde分别。
  • 对于 Java 使用者的commitAsyncAPI,我们不再暴露底层 cause 当RetriableCommitFailedException传递给提交回调。有关更多详细信息,请参阅 KAFKA-5052
新协议版本
  • KIP-107:FetchRequest v5 引入了分区级log_start_offset田。
  • KIP-107:FetchResponse v5 引入了分区级别log_start_offset田。
  • KIP-82:ProduceRequest v3 引入了一个header在 Message Protocol 中,包含keyfield 和value田。
  • KIP-82:FetchResponse v5 引入了一个header在 Message Protocol 中,包含keyfield 和value田。
关于 Exactly Once 语义的说明

Kafka 0.11.0 包括对创建者中的幂等和事务功能的支持。幂等交付 确保在单个创建者的生命周期内,消息只传送到特定主题分区一次。 事务性传输允许创建者将数据发送到多个分区,以便所有消息都成功 已交付,或者都没有。这些功能共同在 Kafka 中实现了“恰好一次语义”。有关这些的更多详细信息 用户指南中提供了这些功能,但下面我们添加了一些关于在升级后的集群中启用这些功能的具体说明。 请注意,启用 EoS 不是必需的,如果未使用,则不会对代理的行为产生影响。

  1. 只有新的 Java 生产者和使用者支持 Exactly once 语义。
  2. 这些功能主要依赖于 0.11.0 消息格式。尝试使用它们 使用较旧的格式将导致不支持的版本错误。
  3. 交易状态存储在新的内部主题__transaction_state.此主题在 第一次尝试使用事务请求 API。与使用者偏移量主题类似,有几个设置 以控制主题的配置。例如transaction.state.log.min.isr控制 本主题。有关选项的完整列表,请参阅用户指南中的配置部分。
  4. 对于安全集群,事务性 API 需要新的 ACL,可以使用bin/kafka-acls.sh. 工具。
  5. Kafka 中的 EoS 引入了新的请求 API 并修改了几个现有的 API。有关详细信息,请参阅 KIP-98
关于 0.11.0 中新消息格式的说明

0.11.0 消息格式包括几项主要增强功能,以便为创建者提供更好的传递语义 (见 KIP-98) 和改进的复制容错能力 (参见 KIP-101)。 尽管新格式包含更多信息以使这些改进成为可能,但我们对批处理格式进行了大幅度的改进 更高效。只要每批的消息数大于 2,就可以降低总体开销。对于较小的 但是,可能会对性能产生较小的影响。请在此处查看我们的结果 新消息格式的初始性能分析。您还可以在 KIP-98 提案中找到有关消息格式的更多详细信息。

新消息格式的一个显著区别是,即使是未压缩的消息也作为单个批处理一起存储。 这对代理配置有一些影响max.message.bytes,这会限制单个批次的大小。第一 如果较旧的客户端使用旧格式向主题分区生成消息,并且消息单独小于max.message.bytes,在上转换过程中将它们合并为单个批次后,代理可能仍会拒绝它们。 通常,当单个消息的聚合大小大于max.message.bytes.有类似的 对从新格式向下转换的读取消息的老年使用者的影响:如果 fetch 大小未设置为至少与max.message.bytes,即使单个未压缩的消息较小,使用者也可能无法取得进展 比配置的 fetch 大小。此行为不会影响 0.10.1.0 及更高版本的 Java 客户端,因为它使用更新的 fetch 协议 这可确保至少可以返回一条消息,即使它超过了 fetch 大小。要解决这些问题,您应该确保 1) 生产者的批量大小未设置为大于max.message.bytes,以及 2) 消费者的 fetch size 设置为 最小max.message.bytes.

关于升级到 0.10.0 消息格式对性能影响的大多数讨论仍然与 0.11.0 升级相关。这主要影响自 “零拷贝” 传输以来未使用 TLS 保护的集群 在这种情况下已经不可能了。为了避免下转换的成本,您应该确保 Consumer 应用程序 已升级到最新的 0.11.0 客户端。值得注意的是,由于旧的 consumer 在 0.11.0.0 中已被弃用,因此它不支持 新的消息格式。您必须升级才能使用新使用者才能使用新的消息格式,而无需进行向下转换。 请注意,0.11.0 消费者支持向后兼容 0.10.0 代理及更高版本,因此可以升级 客户先到经纪人。

从 0.8.x、0.9.x、0.10.0.x 或 0.10.1.x 升级到 0.10.2.0

0.10.2.0 的有线协议发生了变化。通过遵循下面建议的滚动升级计划,您可以保证升级期间不会出现停机时间。 但是,请在升级之前查看 0.10.2.0 中的显著变化

从版本 0.10.2 开始,Java 客户端(生产者和使用者)已获得与旧代理通信的能力。版本 0.10.2 客户端可以与 0.10.0 或更高版本的代理通信。但是,如果您的代理版本低于 0.10.0,则必须升级 Kafka 集群。版本 0.10.2 代理支持 0.8.x 和更新的客户端。

对于滚动升级:

  1. 更新所有代理上的 server.properties 文件并添加以下属性:
    • inter.broker.protocol.version=CURRENT_KAFKA_VERSION (例如 0.8.2、0.9.0、0.10.0 或 0.10.1)。
    • log.message.format.version=CURRENT_KAFKA_VERSION (有关此配置的作用的详细信息,请参阅升级后的潜在性能影响
  2. 一次升级一个代理:关闭代理,更新代码,然后重新启动它。
  3. 升级整个集群后,通过编辑 inter.broker.protocol.version 并将其设置为 0.10.2 来增加协议版本。
  4. 如果您以前的消息格式为 0.10.0,请将 log.message.format.version 更改为 0.10.2(这是一个无作,因为 0.10.0、0.10.1 和 0.10.2 的消息格式相同)。 如果您以前的消息格式版本低于 0.10.0,请不要更改 log.message.format.version - 只有在所有使用者都升级到 0.10.0.0 或更高版本后,此参数才应更改。
  5. 逐个重启 broker,新协议版本才能生效。
  6. 如果此时 log.message.format.version 仍然低于 0.10.0,请等待所有消费者都升级到 0.10.0 或更高版本, 然后将每个代理上的 log.message.format.version 更改为 0.10.2,并逐个重新启动它们。

注意:如果您愿意接受停机,您可以简单地关闭所有代理,更新代码并启动所有代理。默认情况下,他们将从新协议开始。

注意:升级 broker 后,可以随时更新协议版本并重新启动。它不必紧随其后。

升级 0.10.1 Kafka Streams 应用程序
  • 将 Streams 应用程序从 0.10.1 升级到 0.10.2 不需要升级代理。 Kafka Streams 0.10.2 应用程序可以连接到 0.10.2 和 0.10.1 代理(但无法连接到 0.10.0 代理)。
  • 您需要重新编译代码。仅交换 Kafka Streams 库 jar 文件将不起作用,并且会破坏您的应用程序。
  • 如果您使用自定义(即用户实现的)时间戳提取器,则需要更新此代码,因为TimestampExtractor界面已更改。
  • 如果您注册自定义指标,则需要更新此代码,因为StreamsMetric界面已更改。
  • 有关更多详细信息,请参阅 0.10.2 中的 Streams API 更改
升级 0.10.0 Kafka Streams 应用程序
  • 将 Streams 应用程序从 0.10.0 升级到 0.10.2 确实需要升级代理,因为 Kafka Streams 0.10.2 应用程序只能连接到 0.10.2 或 0.10.1 代理。
  • 有一些 API 更改,不向后兼容(有关更多详细信息,请参阅 0.10.2 中的 Streams API 更改)。 因此,您需要更新并重新编译您的代码。仅交换 Kafka Streams 库 jar 文件将不起作用,并且会破坏您的应用程序。
  • 从 0.10.0.x 升级到 0.10.2.2 需要两次带有 config 的滚动退回upgrade.from="0.10.0"设置为第一个升级阶段 (参见 KIP-268)。 作为替代方案,也可以进行离线升级。
    • 为滚动退回准备应用程序实例,并确保 configupgrade.from设置为"0.10.0"新版本 0.10.2.2
    • 退回应用程序的每个实例一次
    • 为新部署的 0.10.2.2 应用程序实例准备第二轮滚动退回;确保删除 config 的值upgrade.from
    • 再次退回应用程序的每个实例以完成升级
  • 从 0.10.0.x 升级到 0.10.2.0 或 0.10.2.1 需要离线升级(不支持滚动退回升级)
    • 停止所有旧的 (0.10.0.x) 应用程序实例
    • 更新您的代码,并将旧代码和 JAR 文件替换为新代码和新 JAR 文件
    • 重新启动所有新的(0.10.2.0 或 0.10.2.1)应用程序实例
0.10.2.2 中的显著变化
  • 新的配置参数upgrade.from添加了允许从版本 0.10.0.x 进行滚动弹跳升级的功能
0.10.2.1 中的显著变化
  • 更改了 StreamsConfig 类的两个配置的默认值,以提高 Kafka Streams 应用程序的弹性。内部 Kafka Streams 创建者retries默认值已从 0 更改为 10。内部 Kafka Streams 使用者max.poll.interval.ms默认值已从 300000 更改为Integer.MAX_VALUE.
0.10.2.0 中的显著变化
  • Java 客户端(生产者和使用者)已经获得了与旧代理通信的能力。版本 0.10.2 客户端 可以与版本 0.10.0 或更高版本的代理通信。请注意,某些功能在较旧的经纪人时不可用或受到限制 使用。
  • Java 使用者上的几个方法现在可能会抛出InterruptException如果调用线程被中断。 请参阅KafkaConsumerJavadoc 中提供了有关此更改的更深入说明。
  • Java 使用者现在可以正常关闭。默认情况下,使用者最多等待 30 秒才能完成待处理请求。 已向KafkaConsumer以控制最长等待时间。
  • 可以通过 --whitelist 选项将多个以逗号分隔的正则表达式传递给具有新 Java 使用者的 MirrorMaker。这 使行为与使用旧 Scala 使用者时的 MirrorMaker 一致。
  • 将 Streams 应用程序从 0.10.1 升级到 0.10.2 不需要升级代理。 Kafka Streams 0.10.2 应用程序可以连接到 0.10.2 和 0.10.1 代理(但无法连接到 0.10.0 代理)。
  • Zookeeper 依赖项已从 Streams API 中删除。Streams API 现在使用 Kafka 协议来管理内部主题,而不是 直接修改 Zookeeper。这消除了直接访问 Zookeeper 和“StreamsConfig.ZOOKEEPER_CONFIG”的权限 不应再在 Streams 应用程序中设置。如果 Kafka 集群是安全的,则 Streams 应用程序必须具有创建新主题所需的安全权限。
  • 添加了几个新字段,包括 “security.protocol”、“connections.max.idle.ms”、“retry.backoff.ms”、“reconnect.backoff.ms” 和 “request.timeout.ms” StreamsConfig 类。用户应注意默认值,并根据需要进行设置。更多细节请参考 3.5 Kafka Streams 配置
新协议版本
  • KIP-88:如果topicsarray 设置为null.
  • KIP-88:OffsetFetchResponse v2 引入了顶级error_code田。
  • KIP-103:UpdateMetadataRequest v3 引入了listener_namefield 添加到end_points数组。
  • KIP-108:CreateTopicsRequest v1 引入了validate_only田。
  • KIP-108:CreateTopicsResponse v1 引入了error_messagefield 添加到topic_errors数组。

从 0.8.x、0.9.x 或 0.10.0.X 升级到 0.10.1.0

0.10.1.0 有有线协议更改。通过遵循下面建议的滚动升级计划,您可以保证升级期间不会出现停机时间。 但是,请在升级前注意 0.10.1.0 中的潜在重大更改
注意:由于引入了新协议,因此在升级客户端(即 0.10.1.x 客户端)之前升级 Kafka 集群非常重要 仅支持 0.10.1.x 或更高版本的 broker,而 0.10.1.x 的 broker 也支持较旧的客户端)。

对于滚动升级:

  1. 更新所有代理上的 server.properties 文件并添加以下属性:
    • inter.broker.protocol.version=CURRENT_KAFKA_VERSION (例如 0.8.2.0、0.9.0.0 或 0.10.0.0)。
    • log.message.format.version=CURRENT_KAFKA_VERSION (有关此配置的作用的详细信息,请参阅升级后的潜在性能影响
  2. 一次升级一个代理:关闭代理,更新代码,然后重新启动它。
  3. 升级整个集群后,通过编辑 inter.broker.protocol.version 并将其设置为 0.10.1.0 来增加协议版本。
  4. 如果您以前的消息格式是 0.10.0,请将 log.message.format.version 更改为 0.10.1(这是一个无作,因为 0.10.0 和 0.10.1 的消息格式相同)。 如果您以前的消息格式版本低于 0.10.0,请不要更改 log.message.format.version - 只有在所有使用者都升级到 0.10.0.0 或更高版本后,此参数才应更改。
  5. 逐个重启 broker,新协议版本才能生效。
  6. 如果此时 log.message.format.version 仍然低于 0.10.0,请等待所有消费者都升级到 0.10.0 或更高版本, 然后将每个代理上的 log.message.format.version 更改为 0.10.1,并逐个重新启动它们。

注意:如果您愿意接受停机,您可以简单地关闭所有代理,更新代码并启动所有代理。默认情况下,他们将从新协议开始。

注意:升级 broker 后,可以随时更新协议版本并重新启动。它不必紧随其后。

0.10.1.2 中的显著变化
  • 新的配置参数upgrade.from添加了允许从版本 0.10.0.x 进行滚动弹跳升级的功能
0.10.1.0 中的潜在重大变化
  • 日志保留时间不再基于日志分段的上次修改时间。相反,它将基于日志分段中消息的最大时间戳。
  • 日志滚动时间不再取决于日志分段创建时间。相反,它现在基于消息中的时间戳。更具体地说。如果分段中第一条消息的时间戳为 T,则当新消息的时间戳大于或等于 T + log.roll.ms 时,将转出日志
  • 由于为每个分段添加了时间索引文件,0.10.0 的打开文件处理程序将增加 ~33%。
  • time index 和 offset index 共享相同的索引大小配置。由于每个 time 索引条目的大小是偏移索引条目大小的 1.5 倍。用户可能需要增加 log.index.size.max.bytes 以避免潜在的频繁日志滚动。
  • 由于索引文件数量的增加,在一些日志段量较大的 broker 上(例如 >15K),broker 启动期间的日志加载过程可能会更长。根据我们的实验,将 num.recovery.threads.per.data.dir 设置为 1 可能会减少日志加载时间。
升级 0.10.0 Kafka Streams 应用程序
  • 将 Streams 应用程序从 0.10.0 升级到 0.10.1 确实需要升级代理,因为 Kafka Streams 0.10.1 应用程序只能连接到 0.10.1 代理。
  • 有一些 API 更改,不向后兼容(有关更多详细信息,请参阅 0.10.1 中的 Streams API 更改)。 因此,您需要更新并重新编译您的代码。仅交换 Kafka Streams 库 jar 文件将不起作用,并且会破坏您的应用程序。
  • 从 0.10.0.x 升级到 0.10.1.2 需要使用 config 进行两次滚动退回upgrade.from="0.10.0"设置为第一个升级阶段 (参见 KIP-268)。 作为替代方案,也可以进行离线升级。
    • 为滚动退回准备应用程序实例,并确保 configupgrade.from设置为"0.10.0"新版本 0.10.1.2
    • 退回应用程序的每个实例一次
    • 为新部署的 0.10.1.2 应用程序实例准备第二轮滚动退回;确保删除 config 的值upgrade.from
    • 再次退回应用程序的每个实例以完成升级
  • 从 0.10.0.x 升级到 0.10.1.0 或 0.10.1.1 需要离线升级(不支持滚动退回升级)
    • 停止所有旧的 (0.10.0.x) 应用程序实例
    • 更新您的代码,并将旧代码和 JAR 文件替换为新代码和新 JAR 文件
    • 重新启动所有新的(0.10.1.0 或 0.10.1.1)应用程序实例
0.10.1.0 中的显著变化
  • 新的 Java 使用者不再处于 beta 阶段,我们建议将其用于所有新的开发。旧的 Scala 使用者仍然受支持,但它们将在下一个版本中被弃用 ,并将在未来的主要版本中删除。
  • --new-consumer/--new.consumerswitch 不再需要将 MirrorMaker 和 Console Consumer 等工具与新使用者一起使用;一个简单 需要传递一个 Kafka 代理来连接,而不是 ZooKeeper ensemble。此外,已弃用 Console Consumer 与旧 Consumer 的使用,它将 在将来的主要版本中删除。
  • Kafka 集群现在可以通过集群 ID 进行唯一标识。当 broker 升级到 0.10.1.0 时,将自动生成它。集群 ID 可通过 kafka.server:type=KafkaServer,name=ClusterId 指标获得,它是元数据响应的一部分。序列化器、客户端拦截器和指标报告器可以通过实现 ClusterResourceListener 接口来接收集群 ID。
  • 已删除 BrokerState “RunningAsController” (值 4)。由于错误,代理在转换出此状态之前只会短暂地处于此状态,因此删除的影响应该很小。检测给定代理是否为控制器的推荐方法是通过 kafka.controller:type=KafkaController,name=ActiveControllerCount 指标。
  • 新的 Java Consumer 现在允许用户按时间戳搜索分区上的偏移量。
  • 新的 Java Consumer 现在支持从后台线程进行检测信号。有一个新的配置max.poll.interval.ms它控制使用者之前轮询调用之间的最长时间 将主动离开组(默认为 5 分钟)。配置的值request.timeout.ms(默认为 30 秒)必须始终小于max.poll.interval.ms(默认为 5 分钟)、 因为这是 JoinGroup 请求在使用者再平衡时可以在服务器上阻止的最长时间。 最后,默认值session.timeout.ms已下调至 10 秒,默认值max.poll.records已更改为 500。
  • 当使用 Authorizer 并且用户没有对主题的 Describe 授权时,代理将不会 longer 将 TOPIC_AUTHORIZATION_FAILED 错误返回给请求,因为这会泄露主题名称。相反,UNKNOWN_TOPIC_OR_PARTITION 将返回错误代码。这可能会导致在使用 producer 和 consumer 时出现意外的超时或延迟,因为 Kafka 客户端通常会在出现未知主题错误时自动重试。如果您 怀疑这可能正在发生。
  • 默认情况下,Fetch 响应具有大小限制(使用者为 50 MB,复制为 10 MB)。现有的每个分区限制也适用(使用者为 1 MB) 和复制)。请注意,这些限制都不是绝对最大值,如下一点所述。
  • 如果找到大于响应/分区大小限制的消息,使用者和副本可以继续前进。更具体地说,如果 FETCH 的第一个非空 partition 大于其中一个或两个限制,则仍将返回该消息。
  • 重载构造函数已添加到kafka.api.FetchRequestkafka.javaapi.FetchRequest以允许调用方指定 分区的顺序(因为 V3 中的顺序很重要)。以前存在的构造函数已被弃用,分区之前被随机排序 发送请求以避免匮乏问题。
新协议版本
  • ListOffsetRequest v1 支持基于时间戳的精确偏移搜索。
  • MetadataResponse v2 引入了一个新字段:“cluster_id”。
  • FetchRequest v3 支持限制响应大小(除了现有的每个分区限制之外),它会返回消息 大于限制(如果需要)才能取得进展,并且请求中的分区顺序现在很重要。
  • JoinGroup v1 引入了一个新字段:“rebalance_timeout”。

从 0.8.x 或 0.9.x 升级到 0.10.0.0

0.10.0.0 具有潜在的重大更改(请在升级前查看)以及升级后可能的性能影响。通过遵循下面建议的滚动升级计划,您可以保证在升级期间和之后不会出现停机时间,也不会对性能产生影响。
注意:由于引入了新协议,因此在升级客户端之前升级 Kafka 集群非常重要。

版本 0.9.0.0 的客户端说明: 由于 0.9.0.0 中引入的一个错误, 依赖于 ZooKeeper(旧的 Scala 高级 Consumer 和 MirrorMaker,如果与旧的 Consumer 一起使用)的客户端将不会 使用 0.10.0.x 代理。因此,在将 broker 升级到 0.9.0.1 之前,应将 0.9.0.0 客户端升级到 0.9.0.1 0.10.0.x 的对于 0.8.X 或 0.9.0.1 客户端,此步骤不是必需的。

对于滚动升级:

  1. 更新所有代理上的 server.properties 文件并添加以下属性:
    • inter.broker.protocol.version=CURRENT_KAFKA_VERSION (例如 0.8.2 或 0.9.0.0)。
    • log.message.format.version=CURRENT_KAFKA_VERSION (有关此配置的作用的详细信息,请参阅升级后的潜在性能影响
  2. 升级代理。这可以一次完成一个 broker作,只需将其关闭、更新代码并重新启动即可。
  3. 升级整个集群后,通过编辑 inter.broker.protocol.version 并将其设置为 0.10.0.0 来增加协议版本。注意:您暂时不应该接触 log.message.format.version - 只有在所有消费者都升级到 0.10.0.0 后,此参数才应该更改
  4. 逐个重启 broker,新协议版本才能生效。
  5. 将所有 Consumer 升级到 0.10.0 后,将每个 Broker 的 log.message.format.version 更改为 0.10.0,然后逐个重启。

注意:如果您愿意接受停机,您可以简单地关闭所有代理,更新代码并启动所有代理。默认情况下,他们将从新协议开始。

注意:升级 broker 后,可以随时更新协议版本并重新启动。它不必紧随其后。

升级到 0.10.0.0 后的潜在性能影响

0.10.0 中的消息格式包括一个新的 timestamp 字段,并对压缩的消息使用相对偏移量。 可以通过 server.properties 文件中的 log.message.format.version 配置磁盘消息格式。 默认的磁盘消息格式为 0.10.0。如果 Consumer 客户端使用的是 0.10.0.0 之前的版本,则它只能理解 0.10.0 之前的 message 格式。在这种情况下,代理能够将消息从 0.10.0 格式转换为早期格式 在将响应发送给旧版本上的使用者之前。但是,在这种情况下,代理不能使用零副本传输。 来自 Kafka 社区的有关性能影响的报告显示,CPU 利用率从升级前的 20% 上升到升级后的 100%,这迫使所有客户端立即升级以使性能恢复正常。 为避免在消费者升级到 0.10.0.0 之前进行此类消息转换,可以在将 broker 升级到 0.10.0.0 时将 log.message.format.version 设置为 0.8.2 或 0.9.0。这样,代理仍然可以使用 Zero Copy Transfer 将数据发送给老消费者。升级使用者后,可以在代理上将消息格式更改为 0.10.0,并享受包含新时间戳和改进压缩的新消息格式。 支持转换以确保兼容性,并且可用于支持一些尚未更新到较新客户端的应用程序,但即使在过度预置的集群上支持所有使用者流量也是不切实际的。因此,当代理已升级但大多数客户端尚未升级时,尽可能避免消息转换至关重要。

对于升级到 0.10.0.0 的客户端,性能不会受到影响。

注意:通过设置消息格式版本,可以证明所有现有消息都位于或低于该版本。 消息格式版本。否则,0.10.0.0 之前的使用者可能会中断。特别是,在消息格式 设置为 0.10.0,则不应将其改回以前的格式,因为它可能会破坏 0.10.0.0 之前版本的使用者。

注意:由于每条消息中引入了额外的时间戳,发送短消息的创建者可能会看到 由于开销增加,消息吞吐量下降。 同样,复制现在每条消息额外传输 8 个字节。 如果您的运行接近集群的网络容量,则可能会使网卡不堪重负 并查看由于过载而导致的故障和性能问题。

注意:如果您在 producer 上启用了压缩,您可能会注意到 producer 吞吐量降低和/或 在某些情况下,代理上的压缩率较低。接收压缩消息时,0.10.0 代理避免重新压缩消息,这通常可以减少延迟并提高吞吐量。在 但是,在某些情况下,这可能会减小生产者上的批处理大小,从而导致吞吐量变差。如果此 发生时,用户可以调整 producer 的 linger.ms 和 batch.size 以获得更好的吞吐量。此外,producer 缓冲区 用于使用 snappy 压缩消息的 值 小于 broker 使用的 值,后者可能具有负数 对磁盘上消息的压缩率的影响。我们打算在未来的 Kafka 中实现可配置 释放。

0.10.0.0 中的潜在重大更改
  • 从 Kafka 0.10.0.0 开始,Kafka 中的消息格式版本表示为 Kafka 版本。例如,消息格式 0.9.0 是指 Kafka 0.9.0 支持的最高消息版本。
  • 引入了消息格式 0.10.0,并默认使用。它在消息中包括一个时间戳字段,相对偏移量用于压缩的消息。
  • 引入了 ProduceRequest/Response v2,默认情况下使用它来支持消息格式 0.10.0
  • 引入了 FetchRequest/Response v2,默认情况下使用它来支持消息格式 0.10.0
  • MessageFormatter 接口已从def writeTo(key: Array[Byte], value: Array[Byte], output: PrintStream)def writeTo(consumerRecord: ConsumerRecord[Array[Byte], Array[Byte]], output: PrintStream)
  • MessageReader 接口已从def readMessage(): KeyedMessage[Array[Byte], Array[Byte]]def readMessage(): ProducerRecord[Array[Byte], Array[Byte]]
  • MessageFormatter 的包已从kafka.toolskafka.common
  • MessageReader 的包已从kafka.toolskafka.common
  • MirrorMakerMessageHandler 不再公开handle(record: MessageAndMetadata[Array[Byte], Array[Byte]])方法,因为它从未被调用过。
  • 0.7 KafkaMigrationTool 不再与 Kafka 打包在一起。如果您需要从 0.7 迁移到 0.10.0,请先迁移到 0.8,然后按照记录的升级过程从 0.8 升级到 0.10.0。
  • 新使用者已将其 API 标准化以接受java.util.Collection作为方法参数的序列类型。可能需要更新现有代码才能使用 0.10.0 客户端库。
  • LZ4 压缩的消息处理已更改为使用可互作的成帧规范 (LZ4f v1.5.1)。 为了保持与旧客户端的兼容性,此更改仅适用于 Message 格式 0.10.0 及更高版本。 使用 v0/v1(消息格式 0.9.0)生成/获取 LZ4 压缩消息的客户端应继续 使用 0.9.0 成帧实现。使用 Produce/Fetch 协议 v2 或更高版本的客户端 应使用可互作的 LZ4f 帧。可互作的 LZ4 库的列表可在 https://www.lz4.org/
0.10.0.0 中的显著变化
  • 从 Kafka 0.10.0.0 开始,名为 Kafka Streams 的新客户端库可用于对存储在 Kafka 主题中的数据进行流处理。由于上述消息格式更改,这个新的客户端库仅适用于 0.10.x 及更高版本的代理。有关更多信息,请阅读 Streams 文档
  • 配置参数的默认值receive.buffer.bytes现在对于新使用者来说是 64K。
  • 新的使用者现在公开了 configuration 参数exclude.internal.topics限制内部主题(例如 Consumer Offsets 主题)意外包含在正则表达式订阅中。默认情况下,它是启用的。
  • 旧的 Scala 生产者已被弃用。用户应尽快将其代码迁移到 kafka-clients JAR 中包含的 Java 生产者。
  • 新的使用者 API 已标记为稳定。

从 0.8.0、0.8.1.X 或 0.8.2.X 升级到 0.9.0.0

0.9.0.0 与以前的版本相比,存在潜在的重大更改(请在升级前查看)和代理间协议更改。这意味着升级后的经纪商和客户端可能与旧版本不兼容。在升级客户端之前,请务必先升级 Kafka 集群。如果您使用的是 MirrorMaker,则还应首先升级下游集群。

对于滚动升级:

  1. 更新所有代理上的 server.properties 文件并添加以下属性:inter.broker.protocol.version=0.8.2.X
  2. 升级代理。这可以一次完成一个 broker作,只需将其关闭、更新代码并重新启动即可。
  3. 升级整个集群后,通过编辑 inter.broker.protocol.version 并将其设置为 0.9.0.0 来增加协议版本。
  4. 逐个重启 broker 以使新协议版本生效

注意:如果您愿意接受停机,您可以简单地关闭所有代理,更新代码并启动所有代理。默认情况下,他们将从新协议开始。

注意:升级 broker 后,可以随时更新协议版本并重新启动。它不必紧随其后。

0.9.0.0 中的潜在重大更改
  • Java 1.6 不再受支持。
  • 不再支持 Scala 2.9。
  • 现在,默认情况下,超过 1000 的代理 ID 将保留给自动分配的代理 ID。如果您的集群的现有代理 ID 高于该阈值,请确保相应地增加 reserved.broker.max.id 代理配置属性。
  • 删除了配置参数 replica.lag.max.messages。分区领导在决定哪些副本同步时将不再考虑滞后消息的数量。
  • 配置参数 replica.lag.time.max.ms 现在不仅指自上次从副本获取请求以来经过的时间,还指自上次副本赶上以来的时间。仍在从领导处获取消息但未赶上 replica.lag.time.max.ms 中最新消息的副本将被视为不同步。
  • 压缩的主题不再接受没有键的消息,如果尝试这样做,创建者将引发异常。在 0.8.x 中,没有 key 的消息会导致日志压缩线程随后抱怨并退出(并停止压缩所有压缩的主题)。
  • MirrorMaker 不再支持多个目标集群。因此,它只接受一个 --consumer.config 参数。要镜像多个源集群,每个源集群至少需要一个 MirrorMaker 实例,每个实例都有自己的使用者配置。
  • org.apache.kafka.clients.tools.* 下打包的工具已移至 org.apache.kafka.tools.*。所有包含的脚本仍将照常运行,只有直接导入这些类的自定义代码会受到影响。
  • 默认的 Kafka JVM 性能选项 (KAFKA_JVM_PERFORMANCE_OPTS) 已在 kafka-run-class.sh 中更改。
  • 现在,kafka-topics.sh 脚本 (kafka.admin.TopicCommand) 在失败时退出时,退出代码为非零。
  • 现在,kafka-topics.sh 脚本 (kafka.admin.TopicCommand) 将在主题名称中打印警告,因为在主题名称中使用了 '.' 或 '_' 而存在指标冲突风险,并且在实际冲突的情况下会出现错误。
  • kafka-console-producer.sh 脚本 (kafka.tools.ConsoleProducer) 将使用 Java 生产者,而不是默认使用的旧 Scala 生产者,用户必须指定 'old-producer' 才能使用旧的生产者。
  • 默认情况下,所有命令行工具都会将所有日志记录消息打印到 stderr 而不是 stdout。
0.9.0.1 中的显著变化
  • 可以通过将 broker.id.generation.enable 设置为 false 来禁用新的代理 ID 生成功能。
  • 配置参数 log.cleaner.enable 现在默认为 true。这意味着现在将默认压缩具有 cleanup.policy=compact 的主题,并且将通过 log.cleaner.dedupe.buffer.size 将 128 MB 的堆分配给清理进程。您可能希望根据您对压缩主题的使用情况查看 log.cleaner.dedupe.buffer.size 和其他 log.cleaner 配置值。
  • 默认情况下,新使用者的配置参数 fetch.min.bytes 的默认值现在为 1。
0.9.0.0 中的废弃
  • 已弃用从 kafka-topics.sh 脚本 (kafka.admin.TopicCommand) 更改主题配置的功能。今后,请使用 kafka-configs.sh 脚本 (kafka.admin.ConfigCommand) 来实现此功能。
  • kafka-consumer-offset-checker.sh (kafka.tools.ConsumerOffsetChecker) 已弃用。今后,请使用 kafka-consumer-groups.sh (kafka.admin.ConsumerGroupCommand) 来实现此功能。
  • kafka.tools.ProducerPerformance 类已弃用。今后,请使用 org.apache.kafka.tools.ProducerPerformance 来实现此功能(kafka-producer-perf-test.sh 也将更改为使用新类)。
  • 生产者配置 block.on.buffer.full 已被弃用,并将在未来版本中删除。目前,其默认值已更改为 false。KafkaProducer 将不再抛出 BufferExhaustedException,而是使用 max.block.ms 值进行 block,之后它将抛出 TimeoutException。如果 block.on.buffer.full 属性显式设置为 true,它会将 max.block.ms 设置为 Long.MAX_VALUE,并且不会遵循 metadata.fetch.timeout.ms

从 0.8.1 升级到 0.8.2

0.8.2 与 0.8.1 完全兼容。升级可以一次完成一个代理,只需将其关闭、更新代码并重新启动即可。

从 0.8.0 升级到 0.8.1

0.8.1 与 0.8 完全兼容。升级可以一次完成一个代理,只需将其关闭、更新代码并重新启动即可。

从 0.7 升级

版本 0.7 与较新版本不兼容。对 API、ZooKeeper 数据结构和协议以及配置进行了重大更改,以添加复制(在 0.7 中缺少)。从 0.7 升级到更高版本需要一个特殊的迁移工具。此迁移可以在不停机的情况下完成。
Kafka 包括 5 个核心 API:
  1. 创建者 API 允许应用程序将数据流发送到 Kafka 集群中的主题。
  2. Consumer API 允许应用程序从 Kafka 集群中的主题读取数据流。
  3. Streams API 允许将数据流从输入主题转换为输出主题。
  4. Connect API 允许实施连接器,这些连接器不断从某个源系统或应用程序拉取到 Kafka 中,或从 Kafka 推送到某个接收器系统或应用程序。
  5. Admin API 允许管理和检查主题、代理和其他 Kafka 对象。
Kafka 通过独立于语言的协议公开其所有功能,该协议具有多种编程语言的客户端。但是,只有 Java 客户端作为主 Kafka 项目的一部分进行维护,其他客户端作为独立的开源项目提供。非 Java 客户端的列表可在此处获得。

2.1 生产者 API

创建者 API 允许应用程序将数据流发送到 Kafka 集群中的主题。

javadocs 中给出了如何使用生产者的示例。

要使用 producer,您可以使用以下 maven 依赖项:

<dependency>
	<groupId>org.apache.kafka</groupId>
	<artifactId>kafka-clients</artifactId>
	<version>3.5.2</version>
</dependency>

2.2 消费者 API

Consumer API 允许应用程序从 Kafka 集群中的主题读取数据流。

javadocs 中给出了如何使用使用者的示例。

要使用 consumer,您可以使用以下 maven 依赖项:

<dependency>
	<groupId>org.apache.kafka</groupId>
	<artifactId>kafka-clients</artifactId>
	<version>3.5.2</version>
</dependency>

2.3 流 API

Streams API 允许将数据流从输入主题转换为输出主题。

javadocs 中给出了如何使用此库的示例

有关使用 Streams API 的其他文档,请参阅此处

要使用 Kafka Streams,您可以使用以下 maven 依赖项:

<dependency>
	<groupId>org.apache.kafka</groupId>
	<artifactId>kafka-streams</artifactId>
	<version>3.5.2</version>
</dependency>

使用 Scala 时,您可以选择包含kafka-streams-scala图书馆。开发人员指南中提供了有关使用 Kafka Streams DSL for Scala 的其他文档。

要使用 Kafka Streams DSL for Scala for Scala 2.13,您可以使用以下 maven 依赖项:

<dependency>
	<groupId>org.apache.kafka</groupId>
	<artifactId>kafka-streams-scala_2.13</artifactId>
	<version>3.5.2</version>
</dependency>

2.4 连接 API

Connect API 允许实现连接器,这些连接器不断从某个源数据系统拉取到 Kafka 或从 Kafka 推送到某个接收器数据系统。

许多 Connect 用户不需要直接使用此 API,但是,他们可以使用预构建的连接器,而无需编写任何代码。有关使用 Connect 的其他信息,请点击此处

想要实现自定义连接器的用户可查看 javadoc

2.5 管理 API

Admin API 支持管理和检查主题、代理、ACL 和其他 Kafka 对象。

要使用 Admin API,请添加以下 Maven 依赖项:

<dependency>
	<groupId>org.apache.kafka</groupId>
	<artifactId>kafka-clients</artifactId>
	<version>3.5.2</version>
</dependency>
有关 Admin API 的更多信息,请参阅 javadoc

Kafka 使用 property 文件格式的键值对进行配置。这些值可以从文件中提供,也可以以编程方式提供。

3.1 代理配置

基本配置如下:
  • broker.id
  • log.dirs
  • zookeeper.connect
下面将更详细地讨论主题级配置和默认值。
  • advertised.listeners

    要发布到 ZooKeeper 供客户端使用的侦听器(如果与listenersconfig 属性。在 IaaS 环境中,这可能需要与代理绑定到的接口不同。如果未设置,则listeners将被使用。与listeners,则通告 0.0.0.0 元地址无效。
    也不同
    listeners,则此属性中可以有重复的端口,以便可以将一个侦听器配置为通告另一个侦听器的地址。这在使用外部负载均衡器的某些情况下可能很有用。

    类型:字符串
    默认值:
    取值:
    重要性:
    更新模式:每个代理
  • 自动创建主题启用功能

    在服务器上启用主题的自动创建

    类型:布尔
    默认值:
    取值:
    重要性:
    更新模式:只读
  • auto.leader.rebalance.enable

    启用自动导引均衡。后台线程定期检查分区领导者的分布,可通过 'leader.imbalance.check.interval.seconds' 进行配置。如果 leader 不平衡超过 'leader.imbalance.per.broker.percentage',则会触发 leader 再平衡到分区的首选 leader。

    类型:布尔
    默认值:
    取值:
    重要性:
    更新模式:只读
  • background.threads

    用于各种后台处理任务的线程数

    类型:int
    默认值:10
    取值:[1,...]
    重要性:
    更新模式:集群范围
  • broker.id

    此服务器的代理 ID。如果未设置,将生成唯一的代理 ID。为避免 zookeeper 生成的代理 ID 与用户配置的代理 ID 之间发生冲突,生成的代理 ID 从 reserved.broker.max.id + 1 开始。

    类型:int
    默认值:-1
    取值:
    重要性:
    更新模式:只读
  • compression.type

    指定给定主题的最终压缩类型。此配置接受标准压缩编解码器('gzip'、'snappy'、'lz4'、'zstd')。它还接受 'uncompressed',这相当于没有压缩;以及 'producer',表示保留 producer 设置的原始压缩编解码器。

    类型:字符串
    默认值:制作人
    取值:[未压缩、zstd、lz4、snappy、gzip、生产者]
    重要性:
    更新模式:集群范围
  • control.plane.listener.name

    用于控制器和 broker 之间通信的侦听器名称。Broker 将使用 control.plane.listener.name 在 listeners 列表中查找终端节点,以侦听来自控制器的连接。例如,如果代理的配置是 :
    listeners = INTERNAL://192.1.1.8:9092, EXTERNAL://10.1.1.5:9093, CONTROLLER://192.1.1.8:9094
    listener.security.protocol.map = INTERNAL:PLAINTEXT, EXTERNAL:SSL, CONTROLLER:SSL
    control.plane.listener.name = CONTROLLER
    启动时,代理将开始监听安全协议为 “SSL” 的 “192.1.1.8:9094”。
    在控制器端,当它通过 zookeeper 发现代理的已发布端点时,它将使用 control.plane.listener.name 查找端点,并使用该端点建立与代理的连接。
    例如,如果代理在 zookeeper 上发布的端点是 :
    “endpoints” : [“INTERNAL://broker1.example.com:9092”,“EXTERNAL://broker1.example.com:9093”,“CONTROLLER://broker1.example.com:9094”]
    并且控制器的配置是 :
    listener.security.protocol.map = INTERNAL:PLAINTEXT, EXTERNAL:SSL, CONTROLLER:SSL
    control.plane.listener.name = 控制器
    然后控制器将使用 “broker1.example.com:9094” 和安全协议 “SSL” 连接到代理。
    如果未显式配置,则默认值将为 null,并且没有用于控制器连接的专用终结点。
    如果显式配置,则该值不能与
    inter.broker.listener.name.

    类型:字符串
    默认值:
    取值:
    重要性:
    更新模式:只读
  • Controller.listener.names

    控制器使用的侦听器名称的逗号分隔列表。如果在 KRaft 模式下运行,这是必需的。与控制器 quorum 通信时,代理将始终使用此列表中的第一个侦听器。
    注意:基于 ZK 的控制器不应设置此配置。

    类型:字符串
    默认值:
    取值:
    重要性:
    更新模式:只读
  • controller.quorum.election.backoff.max.ms

    开始新选举之前的最长时间(以毫秒为单位)。这用于二进制指数退避机制,有助于防止选举陷入僵局

    类型:int
    默认值:1000(1 秒)
    取值:
    重要性:
    更新模式:只读
  • controller.quorum.election.timeout.ms

    在触发新选举之前等待而无法从 leader 获取的最长时间(以毫秒为单位)

    类型:int
    默认值:1000(1 秒)
    取值:
    重要性:
    更新模式:只读
  • controller.quorum.fetch.timeout.ms

    在成为候选人并触发选民选举之前,没有从当前领导者那里成功获取的最长时间;在四处询问以查看是否有新的 leader 纪元之前,没有从 quorum 的大多数收到 fetch 的最长时间

    类型:int
    默认值:2000 (2 秒)
    取值:
    重要性:
    更新模式:只读
  • Controller.quorum.voters

    以逗号分隔的 '{id}@{host}:{port}' 条目列表中的选民集的 ID/终端节点信息映射。例如:'1@localhost:9092,2@localhost:9093,3@localhost:9094'

    类型:列表
    默认值:""
    取值:非空列表
    重要性:
    更新模式:只读
  • 删除.topic.enable

    启用 delete topic。如果关闭此配置,则通过管理工具删除主题将不起作用

    类型:布尔
    默认值:
    取值:
    重要性:
    更新模式:只读
  • early.start.listeners

    一个逗号分隔的侦听器名称列表,可以在授权方完成初始化之前启动。当授权方依赖集群本身进行引导时,这非常有用,StandardAuthorizer(将 ACL 存储在元数据日志中)也是如此。默认情况下,controller.listener.names 中包含的所有侦听器也将是提前启动的侦听器。如果侦听器接受外部流量,则不应显示在此列表中。

    类型:字符串
    默认值:
    取值:
    重要性:
    更新模式:只读
  • leader.imbalance.check.interval.seconds

    控制器触发分区再平衡检查的频率

    类型:长整型
    默认值:300
    取值:[1,...]
    重要性:
    更新模式:只读
  • leader.imbalance.per.broker.percentage

    每个经纪商允许的领先不平衡比率。如果每个 broker 的余额超过此值,则控制器将触发 leader balance。该值以百分比指定。

    类型:int
    默认值:10
    取值:
    重要性:
    更新模式:只读
  • 监听者

    侦听器列表 - 我们将侦听的 URI 和侦听器名称的逗号分隔列表。如果侦听器名称不是安全协议,listener.security.protocol.map也必须设置。
    侦听器名称和端口号必须唯一。
    指定 hostname 为 0.0.0.0 以绑定到所有接口。
    将 hostname 留空以绑定到 default 接口。
    合法侦听器列表示例:
    PLAINTEXT://myhost:9092,SSL://:9091
    CLIENT://0.0.0.0:9092,REPLICATION://localhost:9093

    类型:字符串
    默认值:PLAINTEXT://:9092
    取值:
    重要性:
    更新模式:每个代理
  • 日志目录

    保存日志数据的目录(log.dirs 属性的补充)

    类型:字符串
    默认值:/tmp/kafka-logs 中
    取值:
    重要性:
    更新模式:只读
  • log.dirs

    存储日志数据的目录的逗号分隔列表。如果未设置,则使用 log.dir 中的值。

    类型:字符串
    默认值:
    取值:
    重要性:
    更新模式:只读
  • log.flush.interval.messages

    在将消息刷新到磁盘之前,日志分区上累积的消息数

    类型:长整型
    默认值:9223372036854775807
    取值:[1,...]
    重要性:
    更新模式:集群范围
  • log.flush.interval.ms

    任何主题中的消息在刷新到磁盘之前在内存中保留的最长时间(以毫秒为单位)。如果未设置,则使用 log.flush.scheduler.interval.ms 中的值

    类型:长整型
    默认值:
    取值:
    重要性:
    更新模式:集群范围
  • log.flush.offset.checkpoint.interval.ms

    我们更新上次刷新的持久记录的频率,该记录充当日志恢复点

    类型:int
    默认值:60000 (1 分钟)
    取值:[0,...]
    重要性:
    更新模式:只读
  • log.flush.scheduler.interval.ms

    日志刷新程序检查是否需要将任何日志刷新到磁盘的频率(以毫秒为单位)

    类型:长整型
    默认值:9223372036854775807
    取值:
    重要性:
    更新模式:只读
  • log.flush.start.offset.checkpoint.interval.ms

    我们更新日志开始偏移量的持久记录的频率

    类型:int
    默认值:60000 (1 分钟)
    取值:[0,...]
    重要性:
    更新模式:只读
  • log.retention.bytes

    删除日志前的最大大小

    类型:长整型
    默认值:-1
    取值:
    重要性:
    更新模式:集群范围
  • log.retention.hours

    在删除日志文件之前保留日志文件的小时数(以小时为单位),log.retention.ms 属性的第三级

    类型:int
    默认值:168
    取值:
    重要性:
    更新模式:只读
  • 日志 retention.minutes

    在删除日志文件之前保留日志文件的分钟数(以分钟为单位),仅次于 log.retention.ms 属性。如果未设置,则使用 log.retention.hours 中的值

    类型:int
    默认值:
    取值:
    重要性:
    更新模式:只读
  • log.retention.ms

    在删除日志文件之前保留日志文件的毫秒数(以毫秒为单位),如果未设置,则使用 log.retention.minutes 中的值。如果设置为 -1,则不应用时间限制。

    类型:长整型
    默认值:
    取值:
    重要性:
    更新模式:集群范围
  • log.roll.hours

    转出新日志段之前的最长时间(以小时为单位),仅次于 log.roll.ms 属性

    类型:int
    默认值:168
    取值:[1,...]
    重要性:
    更新模式:只读
  • log.roll.jitter.hours

    要从 logRollTimeMillis 中减去的最大抖动(以小时为单位),仅次于 log.roll.jitter.ms 属性

    类型:int
    默认值:0
    取值:[0,...]
    重要性:
    更新模式:只读
  • log.roll.jitter.ms

    要从 logRollTimeMillis 中减去的最大抖动(以毫秒为单位)。如果未设置,则使用 log.roll.jitter.hours 中的值

    类型:长整型
    默认值:
    取值:
    重要性:
    更新模式:集群范围
  • log.roll.ms

    转出新日志段之前的最长时间(以毫秒为单位)。如果未设置,则使用 log.roll.hours 中的值

    类型:长整型
    默认值:
    取值:
    重要性:
    更新模式:集群范围
  • log.segment.bytes

    单个日志文件的最大大小

    类型:int
    默认值:1073741824 (1 GB)
    取值:[14,...]
    重要性:
    更新模式:集群范围
  • log.segment.delete.delay.ms

    从文件系统中删除文件之前等待的时间

    类型:长整型
    默认值:60000 (1 分钟)
    取值:[0,...]
    重要性:
    更新模式:集群范围
  • message.max.bytes

    Kafka 允许的最大记录批量大小(如果启用了压缩,则在压缩后)。如果此数量增加,并且存在低于 0.10.2 的使用者,则还必须增加使用者的获取大小,以便他们可以获取如此大的记录批次。在最新的消息格式版本中,为了提高效率,记录始终被分组为多个批次。在以前的消息格式版本中,未压缩的记录不会分组为批次,在这种情况下,此限制仅适用于单个记录。这可以通过主题级别为每个主题设置max.message.bytesconfig。

    类型:int
    默认值:1048588
    取值:[0,...]
    重要性:
    更新模式:集群范围
  • metadata.log.dir

    此配置决定了我们将 KRaft 模式下集群的元数据日志放在何处。如果未设置,则元数据日志将放置在 log.dirs 的第一个日志目录中。

    类型:字符串
    默认值:
    取值:
    重要性:
    更新模式:只读
  • metadata.log.max.record.bytes.between.snapshots

    这是在生成新快照之前,日志中最新快照和高水印之间所需的最大字节数。默认值为 20971520。要根据经过的时间生成快照,请参阅metadata.log.max.snapshot.interval.ms配置。当达到最大时间间隔或达到最大字节限制时,Kafka 节点将生成快照。

    类型:长整型
    默认值:20971520
    取值:[1,...]
    重要性:
    更新模式:只读
  • metadata.log.max.snapshot.interval.ms

    如果日志中存在未包含在最新快照中的已提交记录,则这是等待生成快照的最大毫秒数。值为零将禁用基于时间的快照生成。默认值为 3600000。要根据元数据字节数生成快照,请参阅metadata.log.max.record.bytes.between.snapshots配置。当达到最大时间间隔或达到最大字节限制时,Kafka 节点将生成快照。

    类型:长整型
    默认值:3600000 (1 小时)
    取值:[0,...]
    重要性:
    更新模式:只读
  • metadata.log.segment.bytes

    单个元数据日志文件的最大大小。

    类型:int
    默认值:1073741824 (1 GB)
    取值:[12,...]
    重要性:
    更新模式:只读
  • metadata.log.segment.ms

    转出新元数据日志文件之前的最长时间(以毫秒为单位)。

    类型:长整型
    默认值:604800000 (7 天)
    取值:
    重要性:
    更新模式:只读
  • metadata.max.retention.bytes

    删除旧快照和日志文件之前元数据日志和快照的最大组合大小。由于在删除任何日志之前必须至少存在一个快照,因此这是一个软限制。

    类型:长整型
    默认值:104857600 (100 MB)
    取值:
    重要性:
    更新模式:只读
  • metadata.max.retention.ms

    在删除元数据日志文件或快照之前保留元数据日志文件或快照的毫秒数。由于在删除任何日志之前必须至少存在一个快照,因此这是一个软限制。

    类型:长整型
    默认值:604800000 (7 天)
    取值:
    重要性:
    更新模式:只读
  • min.insync.replicas

    当创建者将 acks 设置为 “all” (或 “-1”) 时, min.insync.replicas 指定必须确认写入才能将写入视为成功的最小副本数。如果无法满足此最小值,则创建器将引发异常(NotEnoughReplicas 或 NotEnoughReplicasAfterAppend)。
    一起使用时,min.insync.replicas 和 acks 允许您实施更高的持久性保证。一个典型的场景是创建一个复制因子为 3 的主题,将 min.insync.replicas 设置为 2,并使用 “all” 的 acks 进行生成。这将确保在大多数副本未收到写入时,创建器会引发异常。

    类型:int
    默认值:1
    取值:[1,...]
    重要性:
    更新模式:集群范围
  • node.id

    当 'process.roles' 非空时,与此进程所扮演的角色关联的节点 ID。这是在 KRaft 模式下运行时的必需配置。

    类型:int
    默认值:-1
    取值:
    重要性:
    更新模式:只读
  • num.io.threads

    服务器用于处理请求的线程数,其中可能包括磁盘 I/O

    类型:int
    默认值:8
    取值:[1,...]
    重要性:
    更新模式:集群范围
  • num.network.threads

    服务器用于从网络接收请求并向网络发送响应的线程数。注意:每个侦听器(控制器侦听器除外)都会创建自己的线程池。

    类型:int
    默认值:3
    取值:[1,...]
    重要性:
    更新模式:集群范围
  • num.recovery.threads.per.data.dir

    每个数据目录用于启动时的日志恢复和关闭时的刷新的线程数

    类型:int
    默认值:1
    取值:[1,...]
    重要性:
    更新模式:集群范围
  • num.replica.alter.log.dirs.threads

    可以在日志目录之间移动副本的线程数,其中可能包括磁盘 I/O

    类型:int
    默认值:
    取值:
    重要性:
    更新模式:只读
  • num.replica.fetchers

    用于从每个源 broker 复制记录的 fetcher 线程数。每个 broker 上的 fetcher 总数受num.replica.fetchers乘以群集中的代理数。增加此值可以提高 follower 和 leader broker 中的 I/O 并行度,但代价是 CPU 和内存利用率更高。

    类型:int
    默认值:1
    取值:
    重要性:
    更新模式:集群范围
  • offset.metadata.max.bytes

    与偏移提交关联的元数据条目的最大大小

    类型:int
    默认值:4096 (4 千字节)
    取值:
    重要性:
    更新模式:只读
  • offsets.commit.required.acks

    可以接受提交之前所需的 acks。通常,不应覆盖默认值 (-1)

    类型:
    默认值:-1
    取值:
    重要性:
    更新模式:只读
  • offsets.commit.timeout.ms

    偏移量提交将延迟,直到偏移量主题的所有副本都收到提交或达到此超时。这类似于生产者请求超时。

    类型:int
    默认值:5000(5 秒)
    取值:[1,...]
    重要性:
    更新模式:只读
  • offsets.load.buffer.size

    将偏移量加载到缓存中时,用于从 offset 段读取的批处理大小(软限制,如果记录太大,则覆盖)。

    类型:int
    默认值:5242880
    取值:[1,...]
    重要性:
    更新模式:只读
  • offsets.retention.check.interval.ms

    检查过时偏移的频率

    类型:长整型
    默认值:600000 (10 分钟)
    取值:[1,...]
    重要性:
    更新模式:只读
  • offsets.retention.minutes

    对于已订阅的消费者,特定分区的 commit offset 将在以下情况下过期并丢弃:1) 在消费者组失去所有消费者(即变为空)后,此保留期已过;2) 自上次为分区提交偏移量并且该组不再订阅相应的主题以来,此保留期已过。对于独立使用者(使用手动分配),偏移量将在自上次提交时间以来的此保留期过后过期。请注意,当通过 delete-group 请求删除组时,其提交的偏移量也将被删除,而不会有额外的保留期;此外,当通过 delete-topic 请求删除主题时,在传播元数据更新时,该主题的任何组提交的偏移量也将被删除,而无需额外的保留期。

    类型:int
    默认值:10080
    取值:[1,...]
    重要性:
    更新模式:只读
  • offsets.topic.compression.codec

    offsets 主题的压缩编解码器 - 压缩可用于实现“原子”提交

    类型:int
    默认值:0
    取值:
    重要性:
    更新模式:只读
  • offsets.topic.num.partitions

    偏移提交主题的分区数(部署后不应更改)

    类型:int
    默认值:50
    取值:[1,...]
    重要性:
    更新模式:只读
  • offsets.topic.replication.factor

    offsets 主题的复制因子(设置得更高以确保可用性)。内部主题创建将失败,直到集群大小满足此复制因子要求。

    类型:
    默认值:3
    取值:[1,...]
    重要性:
    更新模式:只读
  • offsets.topic.segment.bytes

    offsets 主题段字节应保持相对较小,以便于更快地进行日志压缩和缓存加载

    类型:int
    默认值:104857600 (100 MB)
    取值:[1,...]
    重要性:
    更新模式:只读
  • 进程角色

    此过程扮演的角色: 'broker', 'controller' 或 'broker,controller' (如果两者兼而有之)。此配置仅适用于 KRaft (Kafka Raft) 模式(而不是 ZooKeeper)的集群。对于 Zookeeper 集群,将此配置保留为 undefined 或 empty。

    类型:列表
    默认值:""
    取值:[经纪人、控制者]
    重要性:
    更新模式:只读
  • queued.max.requests

    在阻止网络线程之前,数据层面允许的排队请求数

    类型:int
    默认值:500
    取值:[1,...]
    重要性:
    更新模式:只读
  • replica.fetch.min.bytes

    每个 fetch 响应所需的最小字节数。如果字节数不足,请等待replica.fetch.wait.max.ms(代理配置)。

    类型:int
    默认值:1
    取值:
    重要性:
    更新模式:只读
  • replica.fetch.wait.max.ms

    follower 副本发出的每个 fetcher 请求的最长等待时间。此值应始终小于 replica.lag.time.max.ms,以防止低吞吐量主题的 ISR 频繁收缩

    类型:int
    默认值:500
    取值:
    重要性:
    更新模式:只读
  • replica.high.watermark.checkpoint.interval.ms

    将高水印保存到磁盘的频率

    类型:长整型
    默认值:5000(5 秒)
    取值:
    重要性:
    更新模式:只读
  • replica.lag.time.max.ms

    如果 follower 没有发送任何 fetch 请求或至少在这段时间内没有消耗到 leader log end offset,则 leader 将从 isr 中删除 follower

    类型:长整型
    默认值:30000 (30 秒)
    取值:
    重要性:
    更新模式:只读
  • replica.socket.receive.buffer.bytes

    套接字接收缓冲区,用于向 leader 发出网络请求以复制数据

    类型:int
    默认值:65536 (64 千字节)
    取值:
    重要性:
    更新模式:只读
  • replica.socket.timeout.ms

    网络请求的套接字超时。其值应至少为 replica.fetch.wait.max.ms

    类型:int
    默认值:30000 (30 秒)
    取值:
    重要性:
    更新模式:只读
  • request.timeout.ms

    该配置控制客户端等待请求响应的最长时间。如果在超时之前未收到响应,则客户端将在必要时重新发送请求,如果重试次数已用尽,则请求失败。

    类型:int
    默认值:30000 (30 秒)
    取值:
    重要性:
    更新模式:只读
  • sasl.mechanism.controller.protocol

    用于与控制器通信的 SASL 机制。默认值为 GSSAPI。

    类型:字符串
    默认值:GSSAPI
    取值:
    重要性:
    更新模式:只读
  • socket.receive.buffer.bytes

    套接字服务器套接字的 SO_RCVBUF 缓冲区。如果值为 -1,则将使用 OS 默认值。

    类型:int
    默认值:102400 (100 千字节)
    取值:
    重要性:
    更新模式:只读
  • socket.request.max.bytes

    套接字请求中的最大字节数

    类型:int
    默认值:104857600 (100 MB)
    取值:[1,...]
    重要性:
    更新模式:只读
  • 套接字.send.buffer.bytes

    套接字服务器套接字的 SO_SNDBUF 缓冲区。如果值为 -1,则将使用 OS 默认值。

    类型:int
    默认值:102400 (100 千字节)
    取值:
    重要性:
    更新模式:只读
  • transaction.max.timeout.ms

    事务允许的最大超时。如果客户端请求的事务时间超过此时间,则代理将在 InitProducerIdRequest 中返回错误。这可以防止客户端超时过大,这可能会使使用者停止从事务中包含的主题中读取。

    类型:int
    默认值:900000 (15 分钟)
    取值:[1,...]
    重要性:
    更新模式:只读
  • transaction.state.log.load.buffer.size

    将创建者 ID 和事务加载到缓存中时,用于从事务日志段读取的批处理大小(软限制,如果记录太大,则覆盖)。

    类型:int
    默认值:5242880
    取值:[1,...]
    重要性:
    更新模式:只读
  • transaction.state.log.min.isr

    覆盖了事务主题的 min.insync.replicas 配置。

    类型:int
    默认值:2
    取值:[1,...]
    重要性:
    更新模式:只读
  • transaction.state.log.num.partitions

    事务主题的分区数(部署后不应更改)。

    类型:int
    默认值:50
    取值:[1,...]
    重要性:
    更新模式:只读
  • transaction.state.log.replication.factor

    事务主题的复制因子(设置得更高以确保可用性)。内部主题创建将失败,直到集群大小满足此复制因子要求。

    类型:
    默认值:3
    取值:[1,...]
    重要性:
    更新模式:只读
  • transaction.state.log.segment.bytes

    事务主题段字节应保持相对较小,以便于更快地进行日志压缩和缓存加载

    类型:int
    默认值:104857600 (100 MB)
    取值:[1,...]
    重要性:
    更新模式:只读
  • transactional.id.expiration.ms

    事务协调器在过期其事务 ID 之前,在未收到当前事务的任何事务状态更新的情况下等待的时间(以毫秒为单位)。当事务仍在进行时,事务 ID 不会过期。

    类型:int
    默认值:604800000 (7 天)
    取值:[1,...]
    重要性:
    更新模式:只读
  • unclean.leader.election.enable

    指示是否将不在 ISR 集中的副本选为领导者作为最后手段,即使这样做可能会导致数据丢失

    类型:布尔
    默认值:
    取值:
    重要性:
    更新模式:集群范围
  • 动物园守护者.connect

    在格式中指定 ZooKeeper 连接字符串hostname:port其中 host 和 port 是 ZooKeeper 服务器的主机和端口。要允许在 ZooKeeper 计算机关闭时通过其他 ZooKeeper 节点进行连接,您还可以在表单中指定多个主机hostname1:port1,hostname2:port2,hostname3:port3.
    服务器还可以将 ZooKeeper chroot 路径作为其 ZooKeeper 连接字符串的一部分,该字符串将其数据置于全局 ZooKeeper 命名空间中的某个路径下。例如,要为 chroot 路径
    /chroot/path您可以将连接字符串指定为hostname1:port1,hostname2:port2,hostname3:port3/chroot/path.

    类型:字符串
    默认值:
    取值:
    重要性:
    更新模式:只读
  • zookeeper.connection.timeout.ms

    客户端等待与 zookeeper 建立连接的最大时间。如果未设置,则使用 zookeeper.session.timeout.ms 中的值

    类型:int
    默认值:
    取值:
    重要性:
    更新模式:只读
  • zookeeper.max.in.flight.requests

    客户端在阻止之前将发送到 Zookeeper 的最大未确认请求数。

    类型:int
    默认值:10
    取值:[1,...]
    重要性:
    更新模式:只读
  • zookeeper.metadata.migration.enable

    启用 ZK 到 KRaft 的迁移

    类型:布尔
    默认值:
    取值:
    重要性:
    更新模式:只读
  • zookeeper.session.timeout.ms

    Zookeeper 会话超时

    类型:int
    默认值:18000(18 秒)
    取值:
    重要性:
    更新模式:只读
  • zookeeper.set.acl

    将客户端设置为使用安全 ACL

    类型:布尔
    默认值:
    取值:
    重要性:
    更新模式:只读
  • broker.heartbeat.interval.ms

    代理检测信号之间的时间长度(以毫秒为单位)。在 KRaft 模式下运行时使用。

    类型:int
    默认值:2000 (2 秒)
    取值:
    重要性:中等
    更新模式:只读
  • broker.id.generation.enable

    在服务器上启用自动代理 ID 生成。启用后,应查看为 reserved.broker.max.id 配置的值。

    类型:布尔
    默认值:
    取值:
    重要性:中等
    更新模式:只读
  • broker.rack

    代理的机架。这将用于机架感知复制分配以实现容错。示例:'RACK1'、'us-east-1d'

    类型:字符串
    默认值:
    取值:
    重要性:中等
    更新模式:只读
  • broker.session.timeout.ms

    如果未进行检测信号,则代理租约持续的时间长度(以毫秒为单位)。在 KRaft 模式下运行时使用。

    类型:int
    默认值:9000(9 秒)
    取值:
    重要性:中等
    更新模式:只读
  • connections.max.idle.ms

    空闲连接超时:服务器套接字处理器线程关闭空闲时间超过此时间的连接

    类型:长整型
    默认值:600000 (10 分钟)
    取值:
    重要性:中等
    更新模式:只读
  • connections.max.reauth.ms

    当显式设置为正数(默认值为 0,而不是正数)时,不会超过配置值的会话生命周期将在客户端进行身份验证时传达给 v2.2.0 或更高版本的客户端。代理将断开在会话生命周期内未重新验证的任何此类连接,然后将其用于除重新验证以外的任何目的。可以选择在配置名称前加上小写的侦听器前缀和 SASL 机制名称。例如,listener.name.sasl_ssl.oauthbearer.connections.max.reauth.ms=3600000

    类型:长整型
    默认值:0
    取值:
    重要性:中等
    更新模式:只读
  • 受控.shutdown.enable

    启用 服务器的受控关闭

    类型:布尔
    默认值:
    取值:
    重要性:中等
    更新模式:只读
  • controlled.shutdown.max.retries

    受控关闭可能由于多种原因而失败。这决定了发生此类失败时的重试次数

    类型:int
    默认值:3
    取值:
    重要性:中等
    更新模式:只读
  • controlled.shutdown.retry.backoff.ms

    在每次重试之前,系统需要时间从导致上一次故障的状态(控制器故障转移、副本滞后等)中恢复。此配置确定重试前要等待的时间。

    类型:长整型
    默认值:5000(5 秒)
    取值:
    重要性:中等
    更新模式:只读
  • controller.quorum.append.linger.ms

    领导在将写入刷新到磁盘之前等待写入累积的持续时间(以毫秒为单位)。

    类型:int
    默认值:25
    取值:
    重要性:中等
    更新模式:只读
  • controller.quorum.request.timeout.ms

    该配置控制客户端等待请求响应的最长时间。如果在超时之前未收到响应,则客户端将在必要时重新发送请求,如果重试次数已用尽,则请求失败。

    类型:int
    默认值:2000 (2 秒)
    取值:
    重要性:中等
    更新模式:只读
  • controller.socket.timeout.ms

    控制器到代理通道的套接字超时

    类型:int
    默认值:30000 (30 秒)
    取值:
    重要性:中等
    更新模式:只读
  • default.replication.factor

    自动创建的主题的默认复制因子

    类型:int
    默认值:1
    取值:
    重要性:中等
    更新模式:只读
  • delegation.token.expiry.time.ms

    需要续订 Token 之前的 Token 有效期(以毫秒为单位)。默认值 1 天。

    类型:长整型
    默认值:86400000 (1 天)
    取值:[1,...]
    重要性:中等
    更新模式:只读
  • delegation.token.master.key

    DEPRECATED: delegation.token.secret.key 的别名,应该使用它来代替此配置。

    类型:密码
    默认值:
    取值:
    重要性:中等
    更新模式:只读
  • delegation.token.max.lifetime.ms

    令牌具有最长生存期,超过此生存期后,将无法再续订。默认值 7 天。

    类型:长整型
    默认值:604800000 (7 天)
    取值:[1,...]
    重要性:中等
    更新模式:只读
  • delegation.token.secret.key

    用于生成和验证委托令牌的密钥。必须在所有代理中配置相同的密钥。如果密钥未设置或设置为空字符串,则代理将禁用委派令牌支持。

    类型:密码
    默认值:
    取值:
    重要性:中等
    更新模式:只读
  • delete.records.purgatory.purge.interval.requests

    删除记录请求炼狱的清除间隔(以请求数为单位)

    类型:int
    默认值:1
    取值:
    重要性:中等
    更新模式:只读
  • fetch.max.bytes

    我们将为 fetch 请求返回的最大字节数。必须至少为 1024。

    类型:int
    默认值:57671680 (55 MB)
    取值:[1024,...]
    重要性:中等
    更新模式:只读
  • fetch.purgatory.purge.interval.requests

    fetch 请求 purgatory 的清除间隔(以请求数为单位)

    类型:int
    默认值:1000
    取值:
    重要性:中等
    更新模式:只读
  • group.initial.rebalance.delay.ms

    组协调器在执行第一次重新平衡之前等待更多使用者加入新组的时间。较长的延迟意味着重新平衡可能较少,但会增加处理开始之前的时间。

    类型:int
    默认值:3000(3 秒)
    取值:
    重要性:中等
    更新模式:只读
  • group.max.session.timeout.ms

    已注册使用者允许的最大会话超时。较长的超时时间使使用者有更多时间在两次检测信号之间处理消息,但代价是检测故障的时间更长。

    类型:int
    默认值:1800000 (30 分钟)
    取值:
    重要性:中等
    更新模式:只读
  • group.max.size

    单个使用者组可以容纳的最大使用者数。

    类型:int
    默认值:2147483647
    取值:[1,...]
    重要性:中等
    更新模式:只读
  • group.min.session.timeout.ms

    已注册使用者允许的最小会话超时。更短的超时可以更快地进行故障检测,但代价是使用者的心跳频率更高,这可能会使代理资源不堪重负。

    类型:int
    默认值:6000(6 秒)
    取值:
    重要性:中等
    更新模式:只读
  • initial.broker.registration.timeout.ms

    最初向控制器仲裁注册时,在声明失败并退出代理进程之前等待的毫秒数。

    类型:int
    默认值:60000 (1 分钟)
    取值:
    重要性:中等
    更新模式:只读
  • inter.broker.listener.name

    用于 broker 之间通信的侦听器名称。如果未设置,则侦听器名称由 security.inter.broker.protocol 定义。同时设置 this 和 security.inter.broker.protocol 属性是错误的。

    类型:字符串
    默认值:
    取值:
    重要性:中等
    更新模式:只读
  • inter.broker.protocol.version

    指定将使用哪个版本的代理间协议。
    这通常在所有代理都升级到新版本后发生。
    一些有效值的示例包括:0.8.0、0.8.1、0.8.1.1、0.8.2、0.8.2.0、0.8.2.1、0.9.0.0、0.9.0.1 检查 MetadataVersion 以获取完整列表。
    此配置仅适用于 Zookeeper 模式。

    类型:字符串
    默认值:3.5-静脉2
    取值:[0.8.0, 0.0. 8.1, 0.8.2, 0.9.0, 0.10.0-IV0, 0.10.0-IV1, 0.10.1-IV0, 0.10.1-IV1, 0.10.1-IV2, 0.10.2-IV0, 0.11.0-IV0, 0.11.0-IV1, 0.11.0-IV2, 1.0-IV0, 1.1-IV0, 2.0-IV0, 2.0-IV1, 2.1-IV0, 2.1-IV1, 2.1-IV2, 2.2-IV0, 2.2-IV1, 2.3-IV0, 2.3-IV1, 2.4-IV0, 2.4-IV1, 2.5-IV0, 2.6-IV0, 2.7-IV0, 2.7-IV1, 2.7-IV2, 2.8-IV0, 2.8-IV1, 3.0-IV0, 3.0-IV1, 3.1-IV0, 3.2-IV0, 3.3-IV0, 3.3-IV1, 3.3-IV2, 3.3-IV3, 3.4-IV0, 3.5-IV0, 3.5-IV1, 3.5-IV2]
    重要性:中等
    更新模式:只读
  • log.cleaner.backoff.ms

    没有要清理的日志时休眠的时间

    类型:长整型
    默认值:15000(15 秒)
    取值:[0,...]
    重要性:中等
    更新模式:集群范围
  • log.cleaner.dedupe.buffer.size

    用于所有清理线程中的日志重复数据删除的总内存

    类型:长整型
    默认值:134217728
    取值:
    重要性:中等
    更新模式:集群范围
  • log.cleaner.delete.retention.ms

    为日志压缩主题保留删除逻辑删除标记的时间。如果使用者从偏移量 0 开始,则此设置还规定了使用者必须完成读取的时间限制,以确保他们获得最终阶段的有效快照(否则,可能会在完成扫描之前收集删除逻辑删除)。

    类型:长整型
    默认值:86400000 (1 天)
    取值:[0,...]
    重要性:中等
    更新模式:集群范围
  • log.cleaner.enable

    启用要在服务器上运行的日志清理进程。如果使用任何带有 cleanup.policy=compact 的主题(包括内部偏移量主题),则应启用。如果禁用,这些主题将不会被压缩,并且大小会不断增加。

    类型:布尔
    默认值:
    取值:
    重要性:中等
    更新模式:只读
  • log.cleaner.io.buffer.load.factor

    Log Cleaner 重复数据删除缓冲区负载因子。重复数据删除缓冲区可以达到的已满百分比。较高的值将允许一次清理更多的日志,但会导致更多的哈希冲突

    类型:双整型
    默认值:0.9
    取值:
    重要性:中等
    更新模式:集群范围
  • log.cleaner.io.buffer.size

    用于所有清理器线程的日志清理器 I/O 缓冲区的总内存

    类型:int
    默认值:524288
    取值:[0,...]
    重要性:中等
    更新模式:集群范围
  • log.cleaner.io.max.bytes.per.second

    日志清理程序将受到限制,以便其读取和写入 I/O 之和平均小于此值

    类型:双整型
    默认值:1.7976931348623157E308
    取值:
    重要性:中等
    更新模式:集群范围
  • log.cleaner.max.compaction.lag.ms

    消息在日志中保持不符合压缩条件的最长时间。仅适用于正在压缩的日志。

    类型:长整型
    默认值:9223372036854775807
    取值:[1,...]
    重要性:中等
    更新模式:集群范围
  • log.cleaner.min.cleanable.ratio

    符合清理条件的日志的脏日志与总日志的最小比率。如果还指定了 log.cleaner.max.compaction.lag.ms 或 log.cleaner.min.compaction.lag.ms 配置,则日志压缩器会在以下任一情况下立即认为日志符合压缩条件:(i) 已达到脏比率阈值,并且日志至少在 log.cleaner.min.compaction.lag.ms 持续时间内具有脏(未压缩)记录,或者 (ii) 如果日志最多在 log.cleaner.max.compaction.lag.ms 时间段内具有脏(未压缩)记录。

    类型:双整型
    默认值:0.5
    取值:[0,...,1]
    重要性:中等
    更新模式:集群范围
  • log.cleaner.min.compaction.lag.ms

    消息在日志中保持未压缩状态的最短时间。仅适用于正在压缩的日志。

    类型:长整型
    默认值:0
    取值:[0,...]
    重要性:中等
    更新模式:集群范围
  • log.cleaner.threads

    用于日志清理的后台线程数

    类型:int
    默认值:1
    取值:[0,...]
    重要性:中等
    更新模式:集群范围
  • 日志清理策略

    保留时段之外的 Segment 的默认清理策略。以逗号分隔的有效策略列表。有效策略包括:“delete”和“compact”

    类型:列表
    默认值:删除
    取值:[压缩,删除]
    重要性:中等
    更新模式:集群范围
  • log.index.interval.bytes

    我们向偏移索引添加条目的间隔

    类型:int
    默认值:4096 (4 千字节)
    取值:[0,...]
    重要性:中等
    更新模式:集群范围
  • log.index.size.max.bytes

    偏移索引的最大大小(以字节为单位)

    类型:int
    默认值:10485760 (10 MB)
    取值:[4,...]
    重要性:中等
    更新模式:集群范围
  • log.message.format.version

    指定代理将用于将消息附加到日志的消息格式版本。该值应为有效的 MetadataVersion。一些示例包括:0.8.2、0.9.0.0、0.10.0,有关详细信息,请查看 MetadataVersion。通过设置特定的消息格式版本,用户将证明磁盘上的所有现有消息都小于或等于指定的版本。错误地设置此值将导致使用旧版本的使用者中断,因为他们将收到格式不正确的消息。

    类型:字符串
    默认值:3.0-IV1
    取值:[0.8.0, 0.0. 8.1, 0.8.2, 0.9.0, 0.10.0-IV0, 0.10.0-IV1, 0.10.1-IV0, 0.10.1-IV1, 0.10.1-IV2, 0.10.2-IV0, 0.11.0-IV0, 0.11.0-IV1, 0.11.0-IV2, 1.0-IV0, 1.1-IV0, 2.0-IV0, 2.0-IV1, 2.1-IV0, 2.1-IV1, 2.1-IV2, 2.2-IV0, 2.2-IV1, 2.3-IV0, 2.3-IV1, 2.4-IV0, 2.4-IV1, 2.5-IV0, 2.6-IV0, 2.7-IV0, 2.7-IV1, 2.7-IV2, 2.8-IV0, 2.8-IV1, 3.0-IV0, 3.0-IV1, 3.1-IV0, 3.2-IV0, 3.3-IV0, 3.3-IV1, 3.3-IV2, 3.3-IV3, 3.4-IV0, 3.5-IV0, 3.5-IV1, 3.5-IV2]
    重要性:中等
    更新模式:只读
  • log.message.timestamp.difference.max.ms

    代理收到消息时的时间戳与消息中指定的时间戳之间允许的最大差值。如果 log.message.timestamp.type=CreateTime,则如果时间戳的差异超过此阈值,则消息将被拒绝。如果 log.message.timestamp.type=LogAppendTime.允许的最大时间戳差异不应大于 log.retention.ms,则忽略此配置,以避免不必要的频繁日志滚动。

    类型:长整型
    默认值:9223372036854775807
    取值:[0,...]
    重要性:中等
    更新模式:集群范围
  • log.message.timestamp.type

    定义消息中的时间戳是消息创建时间还是日志附加时间。该值应为 'CreateTime' 或 'LogAppendTime'

    类型:字符串
    默认值:创建时间
    取值:[创建时间、LogAppendTime]
    重要性:中等
    更新模式:集群范围
  • log.preallocate

    创建新区段时是否应该预先分配文件?如果您在 Windows 上使用 Kafka,则可能需要将其设置为 true。

    类型:布尔
    默认值:
    取值:
    重要性:中等
    更新模式:集群范围
  • log.retention.check.interval.ms

    日志清理程序检查是否有任何日志符合删除条件的频率(以毫秒为单位)

    类型:长整型
    默认值:300000 (5 分钟)
    取值:[1,...]
    重要性:中等
    更新模式:只读
  • max.connection.creation.rate

    我们在任何时候允许在 broker 中创建的最大连接创建速率。侦听器级别的限制也可以通过在配置名称前加上侦听器前缀来配置,例如,listener.name.internal.max.connection.creation.rate.应根据代理容量配置代理范围的连接速率限制,而应根据应用程序要求配置侦听器限制。如果达到侦听器或代理限制,则新连接将受到限制,但代理间侦听器除外。仅当达到侦听器级别的速率限制时,代理间侦听器上的连接才会受到限制。

    类型:int
    默认值:2147483647
    取值:[0,...]
    重要性:中等
    更新模式:集群范围
  • max.connections (最大连接数)

    我们在任何时候允许在 broker 中的最大连接数。除了使用 max.connections.per.ip 配置的任何每 IP 限制之外,还会应用此限制。侦听器级别的限制也可以通过在配置名称前加上侦听器前缀来配置,例如,listener.name.internal.max.connections.应根据代理容量配置代理范围的限制,而应根据应用程序要求配置侦听器限制。如果达到侦听器或代理限制,则会阻止新连接。即使达到代理范围的限制,也允许代理间侦听器上的连接。在这种情况下,另一个侦听器上最近最少使用的连接将被关闭。

    类型:int
    默认值:2147483647
    取值:[0,...]
    重要性:中等
    更新模式:集群范围
  • max.connections.per.ip

    我们允许来自每个 IP 地址的最大连接数。如果存在使用 max.connections.per.ip.overrides 属性配置的覆盖,则可以将其设置为 0。如果达到限制,则来自 IP 地址的新连接将被丢弃。

    类型:int
    默认值:2147483647
    取值:[0,...]
    重要性:中等
    更新模式:集群范围
  • max.connections.per.ip.overrides

    以逗号分隔的每 IP 或主机名列表覆盖默认的最大连接数。示例值为“hostName:100,127.0.0.1:200”

    类型:字符串
    默认值:""
    取值:
    重要性:中等
    更新模式:集群范围
  • max.incremental.fetch.session.cache.slots

    我们将维护的增量获取会话的最大数量。

    类型:int
    默认值:1000
    取值:[0,...]
    重要性:中等
    更新模式:只读
  • num.partitions

    每个主题的默认日志分区数

    类型:int
    默认值:1
    取值:[1,...]
    重要性:中等
    更新模式:只读
  • 密码.encoder.old.secret

    用于对动态配置的密码进行编码的旧密钥。仅当更新密钥时,才需要此密钥。如果指定,则所有动态编码的密码都使用这个旧密钥进行解码,并在代理启动时使用 password.encoder.secret 重新编码。

    类型:密码
    默认值:
    取值:
    重要性:中等
    更新模式:只读
  • 密码.encoder.secret

    用于对此代理的动态配置密码进行编码的密钥。

    类型:密码
    默认值:
    取值:
    重要性:中等
    更新模式:只读
  • principal.builder.class

    实现 KafkaPrincipalBuilder 接口的类的完全限定名称,该接口用于构建授权期间使用的 KafkaPrincipal 对象。如果未定义主体生成器,则默认行为取决于所使用的安全协议。对于 SSL 身份验证,将使用ssl.principal.mapping.rules应用于客户端证书中的可分辨名称(如果已提供);否则,如果不需要客户端身份验证,则主体名称将为 ANONYMOUS。对于 SASL 身份验证,将使用sasl.kerberos.principal.to.local.rules如果正在使用 GSSAPI,以及其他机制的 SASL 身份验证 ID。对于 PLAINTEXT,主体将为 ANONYMOUS。

    类型:
    默认值:org.apache.kafka.common.security.authenticator.DefaultKafkaPrincipalBuilder
    取值:
    重要性:中等
    更新模式:每个代理
  • producer.purgatory.purge.interval.requests

    生产者请求 purgatory 的清除间隔(以请求数为单位)

    类型:int
    默认值:1000
    取值:
    重要性:中等
    更新模式:只读
  • queued.max.request.bytes

    在不再读取请求之前允许的排队字节数

    类型:长整型
    默认值:-1
    取值:
    重要性:中等
    更新模式:只读
  • replica.fetch.backoff.ms

    发生 fetch partition 错误时休眠的时间。

    类型:int
    默认值:1000(1 秒)
    取值:[0,...]
    重要性:中等
    更新模式:只读
  • replica.fetch.max.bytes

    尝试为每个分区提取的消息字节数。这不是绝对最大值,如果 fetch 的第一个非空分区中的第一个记录批次大于此值,则仍将返回记录批次以确保可以取得进展。代理接受的最大记录批量大小是通过message.max.bytes(broker config) 或max.message.bytes(主题配置)。

    类型:int
    默认值:1048576 (1 MB)
    取值:[0,...]
    重要性:中等
    更新模式:只读
  • replica.fetch.response.max.bytes

    整个 fetch 响应所需的最大字节数。记录是分批获取的,如果 fetch 的第一个非空分区中的第一个记录批次大于此值,则仍将返回记录批次以确保可以进行。因此,这不是绝对最大值。代理接受的最大记录批量大小是通过message.max.bytes(broker config) 或max.message.bytes(主题配置)。

    类型:int
    默认值:10485760 (10 MB)
    取值:[0,...]
    重要性:中等
    更新模式:只读
  • replica.selector.class

    实现 ReplicaSelector 的完全限定类名。代理使用它来查找首选只读副本。默认情况下,我们使用返回 leader 的实现。

    类型:字符串
    默认值:
    取值:
    重要性:中等
    更新模式:只读
  • reserved.broker.max.id

    可用于 broker.id 的最大数量

    类型:int
    默认值:1000
    取值:[0,...]
    重要性:中等
    更新模式:只读
  • sasl.client.callback.handler.class

    实现 AuthenticateCallbackHandler 接口的 SASL 客户端回调处理程序类的完全限定名称。

    类型:
    默认值:
    取值:
    重要性:中等
    更新模式:只读
  • sasl.enabled.mechanisms

    在 Kafka 服务器中启用的 SASL 机制的列表。该列表可以包含安全提供程序可用的任何机制。默认情况下,仅启用 GSSAPI。

    类型:列表
    默认值:GSSAPI
    取值:
    重要性:中等
    更新模式:每个代理
  • sasl.jaas.config

    SASL 连接的 JAAS 登录上下文参数,采用 JAAS 配置文件使用的格式。此处描述了 JAAS 配置文件格式。该值的格式为:loginModuleClass controlFlag (optionName=optionValue)*;.对于代理,配置必须以小写的侦听器前缀和 SASL 机制名称为前缀。例如,listener.name.sasl_ssl.scram-sha-256.sasl.jaas.config=com.example.ScramLoginModule required;

    类型:密码
    默认值:
    取值:
    重要性:中等
    更新模式:每个代理
  • sasl.kerberos.kinit.cmd

    Kerberos kinit 命令路径。

    类型:字符串
    默认值:/usr/bin/kinit 中
    取值:
    重要性:中等
    更新模式:每个代理
  • sasl.kerberos.min.time.before.relogin

    刷新尝试之间的登录线程休眠时间。

    类型:长整型
    默认值:60000
    取值:
    重要性:中等
    更新模式:每个代理
  • sasl.kerberos.principal.to.local.rules

    从主体名称映射到短名称(通常是作系统用户名)的规则列表。规则按顺序进行评估,并与委托人名称匹配的第一个规则用于将其映射到短名称。列表中任何后续的规则都将被忽略。默认情况下,表单的主体名称{username}/{hostname}@{REALM}映射到{username}.有关格式的更多详细信息,请参阅 安全授权和 ACLS。请注意,如果KafkaPrincipalBuilderprincipal.builder.class配置。

    类型:列表
    默认值:违约
    取值:
    重要性:中等
    更新模式:每个代理
  • sasl.kerberos.service.name

    Kafka 运行的 Kerberos 主体名称。这可以在 Kafka 的 JAAS 配置或 Kafka 的配置中定义。

    类型:字符串
    默认值:
    取值:
    重要性:中等
    更新模式:每个代理
  • sasl.kerberos.ticket.renew.jitter

    添加到续订时间的随机抖动的百分比。

    类型:双整型
    默认值:0.05
    取值:
    重要性:中等
    更新模式:每个代理
  • sasl.kerberos.ticket.renew.window.factor

    登录线程将休眠,直到达到从上次刷新到票证到期的指定窗口时间因子,此时它将尝试续订票证。

    类型:双整型
    默认值:0.8
    取值:
    重要性:中等
    更新模式:每个代理
  • sasl.login.callback.handler.class

    实现 AuthenticateCallbackHandler 接口的 SASL 登录回调处理程序类的完全限定名称。对于 broker,登录回调处理程序 config 必须以侦听器前缀和小写的 SASL 机制名称为前缀。例如,listener.name.sasl_ssl.scram-sha-256.sasl.login.callback.handler.class=com.example.CustomScramLoginCallbackHandler

    类型:
    默认值:
    取值:
    重要性:中等
    更新模式:只读
  • sasl.login.class

    实现 Login 接口的类的完全限定名称。对于 broker,登录配置必须以 listener prefix 和小写的 SASL 机制名称为前缀。例如,listener.name.sasl_ssl.scram-sha-256.sasl.login.class=com.example.CustomScramLogin

    类型:
    默认值:
    取值:
    重要性:中等
    更新模式:只读
  • sasl.login.refresh.buffer.seconds

    刷新凭证时要保持的凭证过期前要保持的缓冲时间(以秒为单位)。如果刷新时间比缓冲秒数更接近过期时间,则刷新将上移以保持尽可能多的缓冲时间。合法值介于 0 和 3600 之间(1 小时);如果未指定值,则使用默认值 300(5 分钟)。如果此值和 sasl.login.refresh.min.period.seconds 的总和超过凭证的剩余生命周期,则它们都将被忽略。当前仅适用于 OAUTHBEARER。

    类型:
    默认值:300
    取值:
    重要性:中等
    更新模式:每个代理
  • sasl.login.refresh.min.period.seconds

    登录刷新线程在刷新凭证之前等待的所需最短时间(以秒为单位)。合法值介于 0 到 900 之间(15 分钟);如果未指定值,则使用默认值 60(1 分钟)。如果此值和 sasl.login.refresh.buffer.seconds 的总和超过凭证的剩余生命周期,则它们都将被忽略。当前仅适用于 OAUTHBEARER。

    类型:
    默认值:60
    取值:
    重要性:中等
    更新模式:每个代理
  • sasl.login.refresh.window.factor

    登录刷新线程将休眠,直到达到相对于凭证生命周期的指定窗口因子,此时它将尝试刷新凭证。合法值介于 0.5 (50%) 和 1.0 (100%) 之间(含);如果未指定值,则使用默认值 0.8 (80%)。当前仅适用于 OAUTHBEARER。

    类型:双整型
    默认值:0.8
    取值:
    重要性:中等
    更新模式:每个代理
  • sasl.login.refresh.window.jitter

    相对于凭证生命周期的最大随机抖动量,该抖动量添加到登录刷新线程的休眠时间中。合法值介于 0 和 0.25 (25%) 之间(含 0 和 0.25 年);如果未指定值,则使用默认值 0.05 (5%)。当前仅适用于 OAUTHBEARER。

    类型:双整型
    默认值:0.05
    取值:
    重要性:中等
    更新模式:每个代理
  • sasl.mechanism.inter.broker.protocol

    用于代理间通信的 SASL 机制。默认值为 GSSAPI。

    类型:字符串
    默认值:GSSAPI
    取值:
    重要性:中等
    更新模式:每个代理
  • sasl.oauthbearer.jwks.endpoint.url

    OAuth/OIDC 提供者 URL,可从中检索提供者的 JWKS(JSON Web 密钥集)。URL 可以基于 HTTP(S) 或基于文件。如果 URL 基于 HTTP(S),则在代理启动时,将通过配置的 URL 从 OAuth/OIDC 提供程序检索 JWKS 数据。所有当时的密钥都将缓存在 broker 上,用于传入请求。如果收到对 JWT 的身份验证请求,该请求包含尚未在缓存中的“kid”标头声明值,则将按需再次查询 JWKS 终端节点。但是,代理每 sasl.oauthbearer.jwks.endpoint.refresh.ms 毫秒轮询一次 URL,以便在收到包含任何 URL 的 JWT 请求之前使用任何即将到来的密钥刷新缓存。如果 URL 是基于文件的,则代理将在启动时从配置的位置加载 JWKS 文件。如果 JWT 包含的 “kid” 标头值不在 JWKS 文件中,则代理将拒绝 JWT,并且身份验证将失败。

    类型:字符串
    默认值:
    取值:
    重要性:中等
    更新模式:只读
  • sasl.oauthbearer.token.endpoint.url

    OAuth/OIDC 身份提供商的 URL。如果 URL 基于 HTTP(S),则它是颁发者的令牌端点 URL,将根据 sasl.jaas.config 中的配置向其发出登录请求。如果 URL 是基于文件的,则它会指定一个文件,其中包含由 OAuth/OIDC 身份提供者颁发的用于授权的访问令牌(JWT 序列化格式)。

    类型:字符串
    默认值:
    取值:
    重要性:中等
    更新模式:只读
  • sasl.server.callback.handler.class

    实现 AuthenticateCallbackHandler 接口的 SASL 服务器回调处理程序类的完全限定名称。服务器回调处理程序必须以侦听器前缀和小写的 SASL 机制名称为前缀。例如,listener.name.sasl_ssl.plain.sasl.server.callback.handler.class=com.example.CustomPlainCallbackHandler。

    类型:
    默认值:
    取值:
    重要性:中等
    更新模式:只读
  • sasl.server.max.receive.size

    初始 SASL 身份验证之前和期间允许的最大接收大小。默认接收大小为 512KB。GSSAPI 将请求限制为 64K,但默认情况下,对于自定义 SASL 机制,我们允许最大 512KB。在实践中,PLAIN、SCRAM 和 OAUTH 机制可以使用小得多的限制。

    类型:int
    默认值:524288
    取值:
    重要性:中等
    更新模式:只读
  • security.inter.broker.protocol 协议

    用于在 broker 之间通信的安全协议。有效值为:PLAINTEXT、SSL、SASL_PLAINTEXT、SASL_SSL。同时设置 this 和 inter.broker.listener.name 属性是错误的。

    类型:字符串
    默认值:明文
    取值:[纯文本、SSL、SASL_PLAINTEXT、SASL_SSL]
    重要性:中等
    更新模式:只读
  • socket.connection.setup.timeout.max.ms

    客户端等待建立套接字连接的最长时间。对于每个连续的连接失败,连接设置超时将呈指数级增长,直到达到此最大值。为避免连接风暴,将对超时应用随机化因子 0.2,从而产生低于计算值 20% 到高于计算值 20% 的随机范围。

    类型:长整型
    默认值:30000 (30 秒)
    取值:
    重要性:中等
    更新模式:只读
  • socket.connection.setup.timeout.ms

    客户端等待建立套接字连接的时间。如果在超时时间之前未建立连接,则 Client 端将关闭套接字通道。

    类型:长整型
    默认值:10000 (10 秒)
    取值:
    重要性:中等
    更新模式:只读
  • socket.listen.backlog.size

    套接字上的最大待处理连接数。在 Linux 中,你可能还需要相应地配置 'somaxconn' 和 'tcp_max_syn_backlog' 内核参数才能使配置生效。

    类型:int
    默认值:50
    取值:[1,...]
    重要性:中等
    更新模式:只读
  • ssl.cipher.suites

    密码套件列表。这是身份验证、加密、MAC 和密钥交换算法的命名组合,用于协商使用 TLS 或 SSL 网络协议的网络连接的安全设置。默认情况下,支持所有可用的密码套件。

    类型:列表
    默认值:""
    取值:
    重要性:中等
    更新模式:每个代理
  • ssl.client.auth

    配置 kafka 代理以请求客户端身份验证。以下设置是常见的:

    • ssl.client.auth=required如果设置为 required,则需要客户端身份验证。
    • ssl.client.auth=requested这意味着客户端身份验证是可选的。与 required 不同,如果设置了此选项,则客户端可以选择不提供有关自身的身份验证信息
    • ssl.client.auth=none这意味着不需要客户端身份验证。

    类型:字符串
    默认值:没有
    取值:[必需、已请求、无]
    重要性:中等
    更新模式:每个代理
  • ssl.enabled.protocols 协议

    为 SSL 连接启用的协议列表。使用 Java 11 或更高版本运行时,默认值为 'TLSv1.2,TLSv1.3',否则为 'TLSv1.2'。使用 Java 11 的默认值,如果客户端和服务器都支持 TLSv1.3,则客户端和服务器将首选 TLSv1.3,否则将回退到 TLSv1.2(假设两者都至少支持 TLSv1.2)。在大多数情况下,此默认值应该很好。另请参阅 'ssl.protocol' 的配置文档。

    类型:列表
    默认值:TLSv1.2、TLSv1.3
    取值:
    重要性:中等
    更新模式:每个代理
  • ssl.key.password

    密钥存储文件中私钥的密码或 'ssl.keystore.key' 中指定的 PEM 密钥。

    类型:密码
    默认值:
    取值:
    重要性:中等
    更新模式:每个代理
  • ssl.keymanager.algorithm

    密钥管理器工厂用于 SSL 连接的算法。默认值是为 Java 虚拟机配置的密钥管理器工厂算法。

    类型:字符串
    默认值:SunX509 系列
    取值:
    重要性:中等
    更新模式:每个代理
  • ssl.keystore.certificate.chain

    由 'ssl.keystore.type' 指定的格式的证书链。默认 SSL 引擎工厂仅支持带有 X.509 证书列表的 PEM 格式

    类型:密码
    默认值:
    取值:
    重要性:中等
    更新模式:每个代理
  • ssl.keystore.key

    由 'ssl.keystore.type' 指定的格式的私钥。默认 SSL 引擎工厂仅支持带有 PKCS#8 密钥的 PEM 格式。如果密钥已加密,则必须使用 'ssl.key.password' 指定密钥密码

    类型:密码
    默认值:
    取值:
    重要性:中等
    更新模式:每个代理
  • ssl.keystore.location

    密钥存储文件的位置。这对于客户端是可选的,可用于客户端的双向身份验证。

    类型:字符串
    默认值:
    取值:
    重要性:中等
    更新模式:每个代理
  • ssl.keystore.password

    密钥存储文件的存储密码。这对于客户端来说是可选的,只有在配置了 'ssl.keystore.location' 时才需要。PEM 格式不支持密钥存储密码。

    类型:密码
    默认值:
    取值:
    重要性:中等
    更新模式:每个代理
  • ssl.keystore.type

    密钥存储文件的文件格式。这对客户端来说是可选的。默认 'ssl.engine.factory.class' 当前支持的值为 [JKS, PKCS12, PEM]。

    类型:字符串
    默认值:JKS
    取值:
    重要性:中等
    更新模式:每个代理
  • ssl.protocol 协议

    用于生成 SSLContext 的 SSL 协议。使用 Java 11 或更高版本运行时,默认值为 'TLSv1.3',否则为 'TLSv1.2'。对于大多数用例,此值应该很好。最近的 JVM 中允许的值为 'TLSv1.2' 和 'TLSv1.3'。较旧的 JVM 可能支持“TLS”、“TLSv1.1”、“SSL”、“SSLv2”和“SSLv3”,但由于已知的安全漏洞,不鼓励使用它们。使用此配置的默认值和 'ssl.enabled.protocols',如果服务器不支持 'TLSv1.3',则客户端将降级到 'TLSv1.2'。如果此配置设置为 'TLSv1.2',则客户端将不会使用 'TLSv1.3',即使它是 ssl.enabled.protocols 中的值之一,并且服务器仅支持 'TLSv1.3'。

    类型:字符串
    默认值:TLSv1.3 版本
    取值:
    重要性:中等
    更新模式:每个代理
  • ssl.provider

    用于 SSL 连接的安全提供程序的名称。默认值是 JVM 的默认安全提供程序。

    类型:字符串
    默认值:
    取值:
    重要性:中等
    更新模式:每个代理
  • ssl.trustmanager.algorithm

    信任管理器工厂用于 SSL 连接的算法。默认值是为 Java 虚拟机配置的信任管理器工厂算法。

    类型:字符串
    默认值:PKIX
    取值:
    重要性:中等
    更新模式:每个代理
  • ssl.truststore.certificates 证书

    由 'ssl.truststore.type' 指定格式的受信任证书。默认 SSL 引擎工厂仅支持具有 X.509 证书的 PEM 格式。

    类型:密码
    默认值:
    取值:
    重要性:中等
    更新模式:每个代理
  • ssl.truststore.location

    信任存储文件的位置。

    类型:字符串
    默认值:
    取值:
    重要性:中等
    更新模式:每个代理
  • ssl.truststore.password

    信任存储文件的密码。如果未设置密码,则仍将使用配置的信任存储文件,但会禁用完整性检查。PEM 格式不支持信任存储密码。

    类型:密码
    默认值:
    取值:
    重要性:中等
    更新模式:每个代理
  • ssl.truststore.type

    信任存储文件的文件格式。默认 'ssl.engine.factory.class' 当前支持的值为 [JKS, PKCS12, PEM]。

    类型:字符串
    默认值:JKS
    取值:
    重要性:中等
    更新模式:每个代理
  • zookeeper.clientCnxnSocket

    通常设置为org.apache.zookeeper.ClientCnxnSocketNetty使用 TLS 连接到 ZooKeeper 时。覆盖通过同名zookeeper.clientCnxnSocketsystem 属性。

    类型:字符串
    默认值:
    取值:
    重要性:中等
    更新模式:只读
  • zookeeper.ssl.client.enable

    将 client 设置为在连接到 ZooKeeper 时使用 TLS。显式值会覆盖通过zookeeper.client.securesystem 属性(注意不同的名称)。如果未设置,则默认为 false;如果为 true,则zookeeper.clientCnxnSocket必须设置为 (通常为org.apache.zookeeper.ClientCnxnSocketNetty);要设置的其他值可能包括zookeeper.ssl.cipher.suites,zookeeper.ssl.crl.enable,zookeeper.ssl.enabled.protocols,zookeeper.ssl.endpoint.identification.algorithm,zookeeper.ssl.keystore.location,zookeeper.ssl.keystore.password,zookeeper.ssl.keystore.type,zookeeper.ssl.ocsp.enable,zookeeper.ssl.protocol,zookeeper.ssl.truststore.location,zookeeper.ssl.truststore.password,zookeeper.ssl.truststore.type

    类型:布尔
    默认值:
    取值:
    重要性:中等
    更新模式:只读
  • zookeeper.ssl.keystore.location

    密钥库位置。覆盖通过zookeeper.ssl.keyStore.locationsystem 属性(注意 camelCase)。

    类型:字符串
    默认值:
    取值:
    重要性:中等
    更新模式:只读
  • zookeeper.ssl.keystore.password

    使用与 ZooKeeper 的 TLS 连接的客户端证书时的密钥库密码。覆盖通过zookeeper.ssl.keyStore.passwordsystem 属性(注意 camelCase)。请注意,ZooKeeper 不支持与密钥库密码不同的密钥密码,因此请务必将密钥库中的密钥密码设置为与密钥库密码相同;否则,与 Zookeeper 的连接尝试将失败。

    类型:密码
    默认值:
    取值:
    重要性:中等
    更新模式:只读
  • zookeeper.ssl.keystore.type

    密钥库类型。覆盖通过zookeeper.ssl.keyStore.typesystem 属性(注意 camelCase)。默认值null表示将根据密钥库的文件扩展名自动检测该类型。

    类型:字符串
    默认值:
    取值:
    重要性:中等
    更新模式:只读
  • zookeeper.ssl.truststore.location

    使用 TLS 连接到 ZooKeeper 时的信任存储位置。覆盖通过zookeeper.ssl.trustStore.locationsystem 属性(注意 camelCase)。

    类型:字符串
    默认值:
    取值:
    重要性:中等
    更新模式:只读
  • zookeeper.ssl.truststore.password

    使用 TLS 连接到 ZooKeeper 时的信任库密码。覆盖通过zookeeper.ssl.trustStore.passwordsystem 属性(注意 camelCase)。

    类型:密码
    默认值:
    取值:
    重要性:中等
    更新模式:只读
  • zookeeper.ssl.truststore.type

    使用 TLS 连接到 ZooKeeper 时的信任库类型。覆盖通过zookeeper.ssl.trustStore.typesystem 属性(注意 camelCase)。默认值null表示将根据信任库的文件扩展名自动检测该类型。

    类型:字符串
    默认值:
    取值:
    重要性:中等
    更新模式:只读
  • alter.config.policy.class.name

    应该用于验证的 alter configs 策略类。该类应实现org.apache.kafka.server.policy.AlterConfigPolicy接口。

    类型:
    默认值:
    取值:
    重要性:
    更新模式:只读
  • alter.log.dirs.replication.quota.window.num

    要在内存中保留的样本数,用于 alter log dirs 复制配额

    类型:int
    默认值:11
    取值:[1,...]
    重要性:
    更新模式:只读
  • alter.log.dirs.replication.quota.window.size.seconds

    alter log dirs 复制配额的每个样本的时间跨度

    类型:int
    默认值:1
    取值:[1,...]
    重要性:
    更新模式:只读
  • authorizer.class.name

    实现org.apache.kafka.server.authorizer.Authorizer接口,代理使用该接口进行授权。

    类型:字符串
    默认值:""
    取值:非 null 字符串
    重要性:
    更新模式:只读
  • auto.include.jmx.reporter

    荒废的。是否自动包含 JmxReporter,即使它未在metric.reporters.此配置将在 Kafka 4.0 中删除,用户应包含org.apache.kafka.common.metrics.JmxReportermetric.reporters以启用 JmxReporter。

    类型:布尔
    默认值:
    取值:
    重要性:
    更新模式:只读
  • client.quota.callback.class

    实现 ClientQuotaCallback 接口的类的完全限定名称,用于确定应用于客户端请求的配额限制。默认情况下,将应用 ZooKeeper 中存储的 <user> 和 <client-id> 配额。对于任何给定的请求,将应用与会话的用户主体和请求的 client-id 匹配的最具体配额。

    类型:
    默认值:
    取值:
    重要性:
    更新模式:只读
  • connection.failed.authentication.delay.ms

    身份验证失败时连接关闭延迟:这是身份验证失败时连接关闭延迟的时间(以毫秒为单位)。必须将其配置为小于 connections.max.idle.ms 以防止连接超时。

    类型:int
    默认值:100
    取值:[0,...]
    重要性:
    更新模式:只读
  • controller.quorum.retry.backoff.ms

    在尝试重试对给定主题分区的失败请求之前等待的时间。这避免了在某些故障情况下以紧密循环的形式重复发送请求。

    类型:int
    默认值:20
    取值:
    重要性:
    更新模式:只读
  • controller.quota.window.num

    要在内存中保留的 controller 更改配额的样本数

    类型:int
    默认值:11
    取值:[1,...]
    重要性:
    更新模式:只读
  • Controller.quota.window.size.seconds

    控制器更改配额的每个样本的时间跨度

    类型:int
    默认值:1
    取值:[1,...]
    重要性:
    更新模式:只读
  • create.topic.policy.class.name

    应该用于验证的 create topic 策略类。该类应实现org.apache.kafka.server.policy.CreateTopicPolicy接口。

    类型:
    默认值:
    取值:
    重要性:
    更新模式:只读
  • delegation.token.expiry.check.interval.ms

    扫描间隔以删除过期的委托令牌。

    类型:长整型
    默认值:3600000 (1 小时)
    取值:[1,...]
    重要性:
    更新模式:只读
  • kafka.metrics.polling.interval.secs

    可用于 kafka.metrics.reporters 实施的度量标准轮询间隔(以秒为单位)。

    类型:int
    默认值:10
    取值:[1,...]
    重要性:
    更新模式:只读
  • kafka.metrics.reporters

    要用作 Yammer 指标自定义报告器的类列表。报告者应实施kafka.metrics.KafkaMetricsReporter特性。如果客户端想要在自定义报告器上公开 JMX作,则自定义报告器需要额外实现一个扩展kafka.metrics.KafkaMetricsReporterMBeantrait 的 MBean 中,以便注册的 MBean 符合标准 MBean 约定。

    类型:列表
    默认值:""
    取值:
    重要性:
    更新模式:只读
  • listener.security.protocol.map

    侦听器名称和安全协议之间的映射。必须定义此项,才能在多个端口或 IP 中使用同一安全协议。例如,即使内部和外部流量都需要 SSL,也可以将内部和外部流量分开。具体来说,用户可以定义名称为 INTERNAL 和 EXTERNAL 的侦听器,并将此属性定义为:'INTERNAL:SSL,EXTERNAL:SSL'。如图所示,key 和 value 用冒号分隔,map entries 用逗号分隔。每个侦听器名称在映射中只应出现一次。可以通过在配置名称中添加标准化前缀(侦听器名称为小写)来为每个侦听器配置不同的安全性(SSL 和 SASL)设置。例如,要为 INTERNAL 侦听器设置不同的密钥库,名称为listener.name.internal.ssl.keystore.location将设置。如果未设置侦听器名称的配置,则配置将回退到通用配置(即ssl.keystore.location).请注意,在 KRaft 中,由controller.listener.names如果未提供显式映射且未使用其他安全协议,则假定为 PLAINTEXT。

    类型:字符串
    默认值:纯文本:PLAINTEXT,SSL:SSL,SASL_PLAINTEXT:SASL_PLAINTEXT,SASL_SSL:SASL_SSL
    取值:
    重要性:
    更新模式:每个代理
  • log.message.downconversion.enable

    此配置控制是否启用消息格式的向下转换以满足 consume 请求。当设置为false,broker 不会为需要较旧消息格式的使用者执行向下转换。代理使用UNSUPPORTED_VERSION来自此类旧客户端的 consume 请求的错误。此配置不适用于复制到追随者可能需要的任何消息格式转换。

    类型:布尔
    默认值:
    取值:
    重要性:
    更新模式:集群范围
  • metadata.max.idle.interval.ms

    此配置控制活动控制器应将 no-op records 写入元数据分区的频率。如果值为 0,则不会将 no-op 记录附加到元数据分区。默认值为 500

    类型:int
    默认值:500
    取值:[0,...]
    重要性:
    更新模式:只读
  • metric.reporters

    要用作指标报告器的类列表。实施org.apache.kafka.common.metrics.MetricsReporterinterface 允许插入类,这些类将在创建新指标时收到通知。JmxReporter 始终包含在内以注册 JMX 统计信息。

    类型:列表
    默认值:""
    取值:
    重要性:
    更新模式:集群范围
  • metrics.num.samples

    为计算指标而维护的样本数。

    类型:int
    默认值:2
    取值:[1,...]
    重要性:
    更新模式:只读
  • metrics.recording.level

    指标的最高记录级别。

    类型:字符串
    默认值:信息
    取值:
    重要性:
    更新模式:只读
  • metrics.sample.window.ms

    计算指标样本的时间窗口。

    类型:长整型
    默认值:30000 (30 秒)
    取值:[1,...]
    重要性:
    更新模式:只读
  • 密码.encoder.cipher.algorithm

    用于对动态配置的密码进行编码的 Cipher 算法。

    类型:字符串
    默认值:AES/CBC/PKCS5填充
    取值:
    重要性:
    更新模式:只读
  • password.encoder.iterations

    用于对动态配置的密码进行编码的迭代计数。

    类型:int
    默认值:4096
    取值:[1024,...]
    重要性:
    更新模式:只读
  • password.encoder.key.length

    用于对动态配置的密码进行编码的密钥长度。

    类型:int
    默认值:128
    取值:[8,...]
    重要性:
    更新模式:只读
  • 密码.encoder.keyfactory.algorithm

    用于对动态配置的密码进行编码的 SecretKeyFactory 算法。默认值为 PBKDF2WithHmacSHA512(如果可用)和 PBKDF2WithHmacSHA1(否则)。

    类型:字符串
    默认值:
    取值:
    重要性:
    更新模式:只读
  • producer.id.expiration.ms

    主题分区领导者在生产者 ID 过期之前将等待的时间(以毫秒为单位)。当与其关联的事务仍在进行时,生产者 ID 不会过期。请注意,如果由于主题的保留设置而删除了创建者 ID 的最后一次写入,则创建者 ID 可能会提前过期。将此值设置为等于或高于delivery.timeout.ms可以帮助防止重试期间过期并防止消息重复,但对于大多数使用案例,默认值应该是合理的。

    类型:int
    默认值:86400000 (1 天)
    取值:[1,...]
    重要性:
    更新模式:集群范围
  • quota.window.num

    要在内存中保留的样本数,用于客户端配额

    类型:int
    默认值:11
    取值:[1,...]
    重要性:
    更新模式:只读
  • quota.window.size.seconds

    客户端配额的每个样本的时间跨度

    类型:int
    默认值:1
    取值:[1,...]
    重要性:
    更新模式:只读
  • replication.quota.window.num

    要在内存中保留用于复制配额的样本数

    类型:int
    默认值:11
    取值:[1,...]
    重要性:
    更新模式:只读
  • replication.quota.window.size.seconds

    复制配额的每个样本的时间跨度

    类型:int
    默认值:1
    取值:[1,...]
    重要性:
    更新模式:只读
  • sasl.login.connect.timeout.ms

    外部身份验证提供程序连接超时的(可选)值(以毫秒为单位)。当前仅适用于 OAUTHBEARER。

    类型:int
    默认值:
    取值:
    重要性:
    更新模式:只读
  • sasl.login.read.timeout.ms

    外部身份验证提供程序读取超时的(可选)值(以毫秒为单位)。当前仅适用于 OAUTHBEARER。

    类型:int
    默认值:
    取值:
    重要性:
    更新模式:只读
  • sasl.login.retry.backoff.max.ms

    (可选)值(以毫秒为单位),表示尝试登录外部身份验证提供程序之间的最大等待时间。Login 使用指数退避算法,初始等待基于 sasl.login.retry.backoff.ms 设置,并且将在两次尝试之间将等待长度增加一倍,直到达到 sasl.login.retry.backoff.max.ms 设置指定的最大等待长度。当前仅适用于 OAUTHBEARER。

    类型:长整型
    默认值:10000 (10 秒)
    取值:
    重要性:
    更新模式:只读
  • sasl.login.retry.backoff.ms

    尝试登录外部身份验证提供程序之间的初始等待时间的(可选)值(以毫秒为单位)。Login 使用指数退避算法,初始等待基于 sasl.login.retry.backoff.ms 设置,并且将在两次尝试之间将等待长度增加一倍,直到达到 sasl.login.retry.backoff.max.ms 设置指定的最大等待长度。当前仅适用于 OAUTHBEARER。

    类型:长整型
    默认值:100
    取值:
    重要性:
    更新模式:只读
  • sasl.oauthbearer.clock.skew.seconds

    (可选)值(以秒为单位),以允许 OAuth/OIDC 身份提供者和代理的时间之间存在差异。

    类型:int
    默认值:30
    取值:
    重要性:
    更新模式:只读
  • sasl.oauthbearer.expected.audience

    代理使用的(可选)逗号分隔设置,用于验证 JWT 是否是针对预期受众之一颁发的。将检查 JWT 的标准 OAuth “aud” 声明,如果设置了此值,代理将匹配 JWT 的 “aud” 声明中的值,以查看是否存在完全匹配。如果没有匹配项,代理将拒绝 JWT,并且身份验证将失败。

    类型:列表
    默认值:
    取值:
    重要性:
    更新模式:只读
  • sasl.oauthbearer.expected.issuer

    代理用于验证 JWT 是否由预期颁发者创建的(可选)设置。将检查 JWT 中的标准 OAuth “iss” 声明,如果设置了此值,代理会将其与 JWT 的 “iss” 声明中的内容完全匹配。如果没有匹配项,代理将拒绝 JWT,并且身份验证将失败。

    类型:字符串
    默认值:
    取值:
    重要性:
    更新模式:只读
  • sasl.oauthbearer.jwks.endpoint.refresh.ms

    代理在刷新其 JWKS(JSON Web 密钥集)缓存(包含密钥以验证 JWT 签名)之间等待的(可选)值(以毫秒为单位)。

    类型:长整型
    默认值:3600000 (1 小时)
    取值:
    重要性:
    更新模式:只读
  • sasl.oauthbearer.jwks.endpoint.retry.backoff.max.ms

    尝试从外部身份验证提供程序检索 JWKS(JSON Web 密钥集)之间的最大等待时间的(可选)值(以毫秒为单位)。JWKS 检索使用指数退避算法,初始等待基于 sasl.oauthbearer.jwks.endpoint.retry.backoff.ms 设置,并且将两次尝试之间的等待长度增加一倍,直到达到 sasl.oauthbearer.jwks.endpoint.retry.backoff.max.ms 设置指定的最大等待长度。

    类型:长整型
    默认值:10000 (10 秒)
    取值:
    重要性:
    更新模式:只读
  • sasl.oauthbearer.jwks.endpoint.retry.backoff.ms

    来自外部身份验证提供程序的 JWKS(JSON Web 密钥集)检索尝试之间的初始等待的(可选)值(以毫秒为单位)。JWKS 检索使用指数退避算法,初始等待基于 sasl.oauthbearer.jwks.endpoint.retry.backoff.ms 设置,并且将两次尝试之间的等待长度增加一倍,直到达到 sasl.oauthbearer.jwks.endpoint.retry.backoff.max.ms 设置指定的最大等待长度。

    类型:长整型
    默认值:100
    取值:
    重要性:
    更新模式:只读
  • sasl.oauthbearer.scope.claim.name

    范围的 OAuth 声明通常命名为“范围”,但如果 OAuth/OIDC 提供商对该声明使用不同的名称,则此(可选)设置可以提供不同的名称,以用于 JWT 负载声明中包含的范围。

    类型:字符串
    默认值:范围
    取值:
    重要性:
    更新模式:只读
  • sasl.oauthbearer.sub.claim.name

    主题的 OAuth 声明通常命名为“sub”,但如果 OAuth/OIDC 提供商对该声明使用不同的名称,则此(可选)设置可以提供不同的名称,以用于 JWT 负载声明中包含的主题。

    类型:字符串
    默认值:
    取值:
    重要性:
    更新模式:只读
  • security.providers

    可配置的 creator 类的列表,每个类返回一个实现安全算法的提供程序。这些类应该实现org.apache.kafka.common.security.auth.SecurityProviderCreator接口。

    类型:字符串
    默认值:
    取值:
    重要性:
    更新模式:只读
  • ssl.endpoint.identification.algorithm

    终端节点识别算法,用于使用服务器证书验证服务器主机名。

    类型:字符串
    默认值:https
    取值:
    重要性:
    更新模式:每个代理
  • ssl.engine.factory.class

    org.apache.kafka.common.security.auth.SslEngineFactory 类型的类,用于提供 SSLEngine 对象。默认值为 org.apache.kafka.common.security.ssl.DefaultSslEngineFactory

    类型:
    默认值:
    取值:
    重要性:
    更新模式:每个代理
  • ssl.principal.mapping.rules

    从客户端证书中的可分辨名称映射到短名称的规则列表。规则按顺序进行评估,并与委托人名称匹配的第一个规则用于将其映射到短名称。列表中任何后续的规则都将被忽略。默认情况下,X.500 证书的专有名称将是主体。有关格式的更多详细信息,请参阅 安全授权和 ACLS。请注意,如果 KafkaPrincipalBuilder 的扩展由principal.builder.class配置。

    类型:字符串
    默认值:违约
    取值:
    重要性:
    更新模式:只读
  • ssl.secure.random.implementation

    用于 SSL 加密作的 SecureRandom PRNG 实现。

    类型:字符串
    默认值:
    取值:
    重要性:
    更新模式:每个代理
  • transaction.abort.timed.out.transaction.cleanup.interval.ms

    回滚已超时的事务的间隔

    类型:int
    默认值:10000 (10 秒)
    取值:[1,...]
    重要性:
    更新模式:只读
  • transaction.remove.expired.transaction.cleanup.interval.ms

    删除因transactional.id.expiration.ms通过

    类型:int
    默认值:3600000 (1 小时)
    取值:[1,...]
    重要性:
    更新模式:只读
  • zookeeper.ssl.cipher.suites

    指定要在 ZooKeeper TLS 协商 (csv) 中使用的已启用密码套件。覆盖通过zookeeper.ssl.ciphersuitessystem 属性(请注意单个单词 “ciphersuites”)。默认值null表示启用的密码套件列表由所使用的 Java 运行时确定。

    类型:列表
    默认值:
    取值:
    重要性:
    更新模式:只读
  • zookeeper.ssl.crl.enable

    指定是否在 ZooKeeper TLS 协议中启用证书吊销列表。覆盖通过zookeeper.ssl.crlsystem 属性(注意较短的名称)。

    类型:布尔
    默认值:
    取值:
    重要性:
    更新模式:只读
  • zookeeper.ssl.enabled.protocols

    指定 ZooKeeper TLS 协商 (csv) 中启用的协议。覆盖通过zookeeper.ssl.enabledProtocolssystem 属性(注意 camelCase)。默认值null表示启用的协议将是zookeeper.ssl.protocolconfiguration 属性。

    类型:列表
    默认值:
    取值:
    重要性:
    更新模式:只读
  • zookeeper.ssl.endpoint.identification.algorithm

    指定是否在 ZooKeeper TLS 协商过程中启用主机名验证,其中(不区分大小写)“https”表示启用 ZooKeeper 主机名验证,显式空白值表示禁用(仅建议出于测试目的禁用它)。显式值会覆盖通过zookeeper.ssl.hostnameVerificationsystem 属性(请注意不同的名称和值;true 表示 https,false 表示为空)。

    类型:字符串
    默认值:HTTPS 协议
    取值:
    重要性:
    更新模式:只读
  • zookeeper.ssl.ocsp.enable

    指定 ZooKeeper TLS 协议中是否开启在线证书状态协议。覆盖通过zookeeper.ssl.ocspsystem 属性(注意较短的名称)。

    类型:布尔
    默认值:
    取值:
    重要性:
    更新模式:只读
  • zookeeper.ssl.protocol 协议

    指定要在 ZooKeeper TLS 协商中使用的协议。显式值会覆盖通过同名zookeeper.ssl.protocolsystem 属性。

    类型:字符串
    默认值:TLSv1.2 版本
    取值:
    重要性:
    更新模式:只读

有关 broker 配置的更多详细信息可以在 scala 类中找到kafka.server.KafkaConfig.

3.1.1 更新 Broker 配置

从 Kafka 版本 1.1 开始,可以在不重新启动代理的情况下更新某些代理配置。请参阅Dynamic Update Mode,了解每个 Broker 配置的更新模式。
  • read-only:需要重新启动代理才能更新
  • per-broker:可以为每个代理动态更新
  • cluster-wide:可以作为集群范围的默认值动态更新。也可以更新为每个代理的值以进行测试。
要更改代理 ID 0 的当前代理配置(例如,日志清理程序线程的数量):要描述代理 ID 0 的当前动态代理配置:要删除配置覆盖并恢复为代理 ID 0 的静态配置值或默认值(例如 日志清理线程数):某些配置可以配置为集群范围的默认值,以保持整个集群的一致值。所有经纪人 将处理 Cluster Default Update。例如,要更新所有 broker 上的日志清理线程:要描述当前配置的动态集群范围默认配置:所有可在集群级别配置的配置也可以在每个 broker 级别配置(例如,用于测试)。 如果 config 值在不同级别定义,则使用以下优先顺序:
> bin/kafka-configs.sh --bootstrap-server localhost:9092 --entity-type brokers --entity-name 0 --alter --add-config log.cleaner.threads=2
> bin/kafka-configs.sh --bootstrap-server localhost:9092 --entity-type brokers --entity-name 0 --describe
> bin/kafka-configs.sh --bootstrap-server localhost:9092 --entity-type brokers --entity-name 0 --alter --delete-config log.cleaner.threads
> bin/kafka-configs.sh --bootstrap-server localhost:9092 --entity-type brokers --entity-default --alter --add-config log.cleaner.threads=2
> bin/kafka-configs.sh --bootstrap-server localhost:9092 --entity-type brokers --entity-default --describe
  • 存储在 ZooKeeper 中的动态每个代理配置
  • 存储在 ZooKeeper 中的动态集群范围默认配置
  • 静态代理配置server.properties
  • Kafka 默认,参见 broker configs
动态更新密码配置

动态更新的密码配置值在存储到 ZooKeeper 之前会被加密。代理配置password.encoder.secret必须在server.properties启用动态更新 的密码配置。密钥在不同的代理上可能不同。

用于密码编码的密钥可以通过 broker 的滚动重启进行轮换。用于编码的旧密钥 当前在 ZooKeeper 中的密码必须在静态代理配置中提供password.encoder.old.secret和 新密钥必须在password.encoder.secret.所有动态密码配置都存储在 ZooKeeper 中 将在 broker 启动时使用新 secret 重新编码。

在 Kafka 1.1.x 中,更新配置时,必须在每个 alter 请求中提供所有动态更新的密码配置 用kafka-configs.sh即使密码配置未被更改。此约束将在 未来版本。

在启动 broker 之前在 ZooKeeper 中更新密码配置
从 Kafka 2.0.0 开始,kafka-configs.sh允许在 启动 broker 进行引导。这使得所有密码配置都可以以加密形式存储,从而避免了 清除密码server.properties.代理配置password.encoder.secret还必须指定 如果 ALTER 命令中包含任何密码配置。还可以指定其他加密参数。密码 编码器配置不会保留在 ZooKeeper 中。例如,要存储侦听器的 SSL 密钥密码INTERNAL在代理 0 上:配置
> bin/kafka-configs.sh --zookeeper localhost:2182 --zk-tls-config-file zk_tls_config.properties --entity-type brokers --entity-name 0 --alter --add-config
    'listener.name.internal.ssl.key.password=key-password,password.encoder.secret=secret,password.encoder.iterations=8192'
listener.name.internal.ssl.key.password将以加密方式保存在 ZooKeeper 中 表单。编码器密钥和迭代不会保留在 ZooKeeper 中。
更新现有侦听器的 SSL 密钥库
代理可以配置有效期较短的 SSL 密钥库,以降低证书泄露的风险。 密钥库可以动态更新,而无需重新启动代理。配置名称必须以侦听器前缀为前缀listener.name.{listenerName}.,以便仅更新特定侦听器的密钥库配置。 以下配置可以在每个代理级别的单个 alter 请求中更新:
  • ssl.keystore.type
  • ssl.keystore.location
  • ssl.keystore.password
  • ssl.key.password
如果侦听器是代理间侦听器,则仅当信任库信任新密钥库时,才允许更新 配置。对于其他侦听器,代理不会对密钥库执行信任验证。证书 必须由签署旧证书的同一证书颁发机构签名,以避免任何客户端身份验证失败。
更新现有侦听器的 SSL 信任库
代理信任库可以动态更新,而无需重新启动代理来添加或删除证书。 更新的信任库将用于验证新的客户端连接。配置名称必须以 侦听器前缀listener.name.{listenerName}.这样,只有特定侦听器的 truststore 配置 已更新。以下配置可以在每个代理级别的单个 alter 请求中更新:
  • ssl.truststore.type
  • ssl.truststore.location
  • ssl.truststore.password
如果侦听器是代理间侦听器,则仅当该侦听器的现有密钥库受 新的 truststore 中。对于其他侦听器,代理在更新之前不执行信任验证。删除 CA 证书 用于对来自新信任库的客户端证书进行签名可能会导致客户端身份验证失败。
更新默认 Topic 配置
代理使用的默认主题配置选项可以在不重新启动代理的情况下进行更新。配置应用于主题 没有等效的 per-topic 配置的主题配置覆盖。这些配置中的一个或多个可以在 cluster-default 级别。
  • log.segment.bytes
  • log.roll.ms
  • log.roll.hours
  • log.roll.jitter.ms
  • log.roll.jitter.hours
  • log.index.size.max.bytes
  • log.flush.interval.messages
  • log.flush.interval.ms
  • log.retention.bytes
  • log.retention.ms
  • log.retention.minutes
  • log.retention.hours
  • log.index.interval.bytes
  • log.cleaner.delete.retention.ms
  • log.cleaner.min.compaction.lag.ms
  • log.cleaner.max.compaction.lag.ms
  • log.cleaner.min.cleanable.ratio
  • log.cleanup.policy
  • log.segment.delete.delay.ms
  • unclean.leader.election.enable
  • min.insync.replicas
  • max.message.bytes
  • compression.type
  • log.preallocate
  • log.message.timestamp.type
  • log.message.timestamp.difference.max.ms
从 Kafka 版本 2.0.0 开始,控制器会在配置unclean.leader.election.enable将动态更新。 在 Kafka 版本 1.1.x 中,对unclean.leader.election.enable仅在选举新控制器时生效。 可以通过运行以下命令强制控制器重新选举:
> bin/zookeeper-shell.sh localhost
  rmr /controller
更新 Log Cleaner 配置
日志清理器配置可以在所有代理使用的 cluster-default 级别动态更新。更改将生效 在日志清理的下一次迭代中。可能会更新以下一个或多个配置:
  • log.cleaner.threads
  • log.cleaner.io.max.bytes.per.second
  • log.cleaner.dedupe.buffer.size
  • log.cleaner.io.buffer.size
  • log.cleaner.io.buffer.load.factor
  • log.cleaner.backoff.ms
更新线程配置
代理使用的各种线程池的大小可以在所有代理使用的 cluster-default 级别动态更新。 更新仅限于范围currentSize / 2currentSize * 2要确保 Config 更新是 处理得体。
  • num.network.threads
  • num.io.threads
  • num.replica.fetchers
  • num.recovery.threads.per.data.dir
  • log.cleaner.threads
  • background.threads
更新 ConnectionQuota 配置
代理允许给定 IP/主机的最大连接数可以在所有代理使用的 cluster-default 级别动态更新。 更改将应用于新连接创建,新限制将考虑现有连接计数。
  • max.connections.per.ip
  • max.connections.per.ip.overrides
添加和删除侦听器

可以动态添加或删除侦听器。添加新的侦听器时,必须提供侦听器的安全配置 作为带有 listener 前缀的 listener 配置listener.name.{listenerName}..如果新侦听器使用 SASL,则 必须使用 JAAS 配置属性提供侦听器的 JAAS 配置sasl.jaas.config替换为 listener 和 mechanism 前缀。有关详细信息,请参阅 Kafka 代理的 JAAS 配置

在 Kafka 版本 1.1.x 中,代理间侦听器使用的侦听器可能不会动态更新。更新代理间 listener 添加到新的侦听器中,则可以在所有 broker 上添加新的侦听器,而无需重新启动 broker。然后滚动重启 需要更新inter.broker.listener.name.

除了新侦听器的所有安全配置之外,以下配置还可以在每个代理级别动态更新:
  • listeners
  • advertised.listeners
  • listener.security.protocol.map
必须使用静态代理配置来配置代理间侦听器inter.broker.listener.namesecurity.inter.broker.protocol.

3.2 主题级配置

与主题相关的配置既具有服务器默认值,也具有可选的按主题覆盖。如果未给出每个主题的配置,则使用 server default。可以在主题创建时通过提供一个或多个--config选项。此示例创建一个名为 my-topic 的主题,该主题具有自定义的最大消息大小和刷新率:以后也可以使用 alter configs 命令更改或设置覆盖。此示例更新了 my-topic 的最大消息大小: 要检查在主题上设置的覆盖,您可以执行 要删除覆盖,您可以执行以下作 以下是主题级配置。此属性的服务器默认配置在 Server Default Property 标题下提供。给定的服务器默认配置值仅适用于没有显式主题配置覆盖的主题。
> bin/kafka-topics.sh --bootstrap-server localhost:9092 --create --topic my-topic --partitions 1 \
  --replication-factor 1 --config max.message.bytes=64000 --config flush.messages=1
> bin/kafka-configs.sh --bootstrap-server localhost:9092 --entity-type topics --entity-name my-topic
  --alter --add-config max.message.bytes=128000
> bin/kafka-configs.sh --bootstrap-server localhost:9092 --entity-type topics --entity-name my-topic --describe
> bin/kafka-configs.sh --bootstrap-server localhost:9092  --entity-type topics --entity-name my-topic
  --alter --delete-config max.message.bytes
  • cleanup.policy 的

    此配置指定要用于日志分段的保留策略。“删除”策略(这是默认策略)将在达到保留时间或大小限制时丢弃旧区段。“compact” 策略将启用日志压缩,从而保留每个键的最新值。也可以在逗号分隔的列表中指定这两个策略(例如 “delete,compact”)。在这种情况下,将根据保留时间和大小配置丢弃旧区段,而保留的区段将被压缩。

    类型:列表
    默认值:删除
    取值:[压缩,删除]
    服务器默认属性:日志清理策略
    重要性:中等
  • compression.type

    指定给定主题的最终压缩类型。此配置接受标准压缩编解码器('gzip'、'snappy'、'lz4'、'zstd')。它还接受 'uncompressed',这相当于没有压缩;以及 'producer',表示保留 producer 设置的原始压缩编解码器。

    类型:字符串
    默认值:制作人
    取值:[未压缩、zstd、lz4、snappy、gzip、生产者]
    服务器默认属性:compression.type
    重要性:中等
  • delete.retention.ms

    日志压缩主题保留删除逻辑删除标记的时间。如果使用者从偏移量 0 开始,则此设置还规定了使用者必须完成读取的时间限制,以确保他们获得最终阶段的有效快照(否则可能会在完成扫描之前收集删除逻辑删除)。

    类型:长整型
    默认值:86400000 (1 天)
    取值:[0,...]
    服务器默认属性:log.cleaner.delete.retention.ms
    重要性:中等
  • file.delete.delay.ms

    从文件系统中删除文件之前等待的时间

    类型:长整型
    默认值:60000 (1 分钟)
    取值:[0,...]
    服务器默认属性:log.segment.delete.delay.ms
    重要性:中等
  • flush.messages

    此设置允许指定一个间隔,在该间隔内,我们将强制将数据的 fsync 写入日志。例如,如果设置为 1,我们将在每条消息后 fsync;如果是 5,我们将在每 5 条消息后进行 fsync。通常,我们建议您不要设置此项,而是使用复制来实现持久性,并允许作系统的后台刷新功能,因为它效率更高。可以按主题覆盖此设置(请参阅按主题配置部分)。

    类型:长整型
    默认值:9223372036854775807
    取值:[1,...]
    服务器默认属性:log.flush.interval.messages
    重要性:中等
  • flush.ms

    此设置允许指定一个时间间隔,在该时间间隔内,我们将强制将数据的 fsync 写入日志。例如,如果将其设置为 1000,我们将在 1000 毫秒后进行 fsync。通常,我们建议您不要设置此项,而是使用复制来实现持久性,并允许作系统的后台刷新功能,因为它效率更高。

    类型:长整型
    默认值:9223372036854775807
    取值:[0,...]
    服务器默认属性:log.flush.interval.ms
    重要性:中等
  • follower.replication.throttled.replicas

    应在 follower 端限制其日志复制的副本列表。该列表应以 [PartitionId]:[BrokerId],[PartitionId]:[BrokerId]:...或者,通配符 '*' 可用于限制此主题的所有副本。

    类型:列表
    默认值:""
    取值:[partitionId]:[brokerId],[partitionId]:[brokerId],...
    服务器默认属性:
    重要性:中等
  • index.interval.bytes

    此设置控制 Kafka 将索引条目添加到其偏移索引的频率。默认设置确保我们大约每 4096 字节为一条消息编制索引。更多的索引允许读取跳到更接近日志中的确切位置,但会使索引更大。您可能不需要更改此项。

    类型:int
    默认值:4096 (4 千字节)
    取值:[0,...]
    服务器默认属性:log.index.interval.bytes
    重要性:中等
  • leader.replication.throttled.replicas

    应在 leader 端限制其日志复制的副本列表。该列表应以 [PartitionId]:[BrokerId],[PartitionId]:[BrokerId]:...或者,通配符 '*' 可用于限制此主题的所有副本。

    类型:列表
    默认值:""
    取值:[partitionId]:[brokerId],[partitionId]:[brokerId],...
    服务器默认属性:
    重要性:中等
  • max.compaction.lag.ms

    消息在日志中保持不符合压缩条件的最长时间。仅适用于正在压缩的日志。

    类型:长整型
    默认值:9223372036854775807
    取值:[1,...]
    服务器默认属性:log.cleaner.max.compaction.lag.ms
    重要性:中等
  • 最大消息字节数

    Kafka 允许的最大记录批量大小(如果启用了压缩,则在压缩后)。如果此数量增加,并且存在低于 0.10.2 的使用者,则还必须增加使用者的获取大小,以便他们可以获取如此大的记录批次。在最新的消息格式版本中,为了提高效率,记录始终被分组为多个批次。在以前的消息格式版本中,未压缩的记录不会分组为批次,在这种情况下,此限制仅适用于单个记录。

    类型:int
    默认值:1048588
    取值:[0,...]
    服务器默认属性:message.max.bytes
    重要性:中等
  • message.format.version

    [已弃用]指定代理将用于将消息附加到日志的消息格式版本。如果 'inter.broker.protocol.version' 为 3.0 或更高,则始终假定此配置的值为 '3.0' (忽略实际配置值)。否则,该值应为有效的 ApiVersion。一些示例包括:0.10.0、1.1、2.8、3.0。通过设置特定的消息格式版本,用户将证明磁盘上的所有现有消息都小于或等于指定的版本。错误地设置此值将导致使用旧版本的使用者中断,因为他们将收到格式不正确的消息。

    类型:字符串
    默认值:3.0-IV1
    取值:[0.8.0, 0.0. 8.1, 0.8.2, 0.9.0, 0.10.0-IV0, 0.10.0-IV1, 0.10.1-IV0, 0.10.1-IV1, 0.10.1-IV2, 0.10.2-IV0, 0.11.0-IV0, 0.11.0-IV1, 0.11.0-IV2, 1.0-IV0, 1.1-IV0, 2.0-IV0, 2.0-IV1, 2.1-IV0, 2.1-IV1, 2.1-IV2, 2.2-IV0, 2.2-IV1, 2.3-IV0, 2.3-IV1, 2.4-IV0, 2.4-IV1, 2.5-IV0, 2.6-IV0, 2.7-IV0, 2.7-IV1, 2.7-IV2, 2.8-IV0, 2.8-IV1, 3.0-IV0, 3.0-IV1, 3.1-IV0, 3.2-IV0, 3.3-IV0, 3.3-IV1, 3.3-IV2, 3.3-IV3, 3.4-IV0, 3.5-IV0, 3.5-IV1, 3.5-IV2]
    服务器默认属性:log.message.format.version
    重要性:中等
  • message.timestamp.difference.max.ms

    代理收到消息时的时间戳与消息中指定的时间戳之间允许的最大差值。如果 message.timestamp.type=CreateTime,则当时间戳的差异超过此阈值时,消息将被拒绝。如果 message.timestamp.type=LogAppendTime.

    类型:长整型
    默认值:9223372036854775807
    取值:[0,...]
    服务器默认属性:log.message.timestamp.difference.max.ms
    重要性:中等
  • 消息.timestamp.type

    定义消息中的时间戳是消息创建时间还是日志附加时间。该值应为 'CreateTime' 或 'LogAppendTime'

    类型:字符串
    默认值:创建时间
    取值:[创建时间、LogAppendTime]
    服务器默认属性:log.message.timestamp.type
    重要性:中等
  • 最小可清洁肮脏比例

    此配置控制日志压缩器尝试清理日志的频率(假设启用了日志压缩)。默认情况下,我们将避免清理已压缩超过 50% 的日志的日志。此比率限制了重复项在日志中浪费的最大空间(在 50% 时,最多 50% 的日志可以是重复项)。更高的比率意味着更少的清洁、更有效的清洁,但意味着在日志中浪费更多的空间。如果还指定了 max.compaction.lag.ms 或 min.compaction.lag.ms 配置,则日志压缩器会在以下任一情况下立即认为日志符合压缩条件:(i) 已达到脏比率阈值,并且日志至少在 min.compaction.lag.ms 持续时间内具有脏(未压缩)记录,或者 (ii) 如果日志最多在 max.compaction.lag.ms 时间段内具有脏(未压缩)记录。

    类型:双整型
    默认值:0.5
    取值:[0,...,1]
    服务器默认属性:log.cleaner.min.cleanable.ratio
    重要性:中等
  • min.compaction.lag.ms

    消息在日志中保持未压缩状态的最短时间。仅适用于正在压缩的日志。

    类型:长整型
    默认值:0
    取值:[0,...]
    服务器默认属性:log.cleaner.min.compaction.lag.ms
    重要性:中等
  • min.insync.replicas

    当创建者将 acks 设置为 “all” (或 “-1”) 时,此配置指定必须确认写入才能将写入视为成功的最小副本数。如果无法满足此最小值,则创建器将引发异常(NotEnoughReplicas 或 NotEnoughReplicasAfterAppend)。
    一起使用时,
    min.insync.replicasacks允许您实施更强的持久性保证。一个典型的场景是创建一个复制因子为 3 的主题,将min.insync.replicas到 2,并使用acks的 “all” 的。这将确保在大多数副本未收到写入时,创建器会引发异常。

    类型:int
    默认值:1
    取值:[1,...]
    服务器默认属性:min.insync.replicas
    重要性:中等
  • 预分配

    如果我们在创建新的日志段时应该在磁盘上预分配文件,则为 True。

    类型:布尔
    默认值:
    取值:
    服务器默认属性:log.preallocate
    重要性:中等
  • retention.bytes 的

    此配置控制分区(由日志段组成)可以增长到的最大大小,如果我们使用的是 “delete” 保留策略,则丢弃旧的日志段以释放空间。默认情况下,没有大小限制,只有一个时间限制。由于此限制是在分区级别强制执行的,因此请将其乘以分区数以计算主题保留期(以字节为单位)。

    类型:长整型
    默认值:-1
    取值:
    服务器默认属性:log.retention.bytes
    重要性:中等
  • retention.ms

    此配置控制如果我们使用 “delete” 保留策略,则在丢弃旧日志段以释放空间之前,我们将保留日志的最长时间。这表示消费者必须多久读取其数据的 SLA。如果设置为 -1,则不应用时间限制。

    类型:长整型
    默认值:604800000 (7 天)
    取值:[-1,...]
    服务器默认属性:log.retention.ms
    重要性:中等
  • 段.bytes

    此配置控制日志的分段文件大小。保留和清理始终一次完成一个文件,因此较大的数据段大小意味着更少的文件,但对保留的控制较少。

    类型:int
    默认值:1073741824 (1 GB)
    取值:[14,...]
    服务器默认属性:log.segment.bytes
    重要性:中等
  • 段.index.bytes

    此配置控制将偏移量映射到文件位置的索引的大小。我们预分配此索引文件,并仅在日志滚动后收缩它。通常不需要更改此设置。

    类型:int
    默认值:10485760 (10 MB)
    取值:[4,...]
    服务器默认属性:log.index.size.max.bytes
    重要性:中等
  • segment.jitter.ms

    从计划的 Segment 滚动时间中减去的最大随机抖动,以避免 Segment 滚动的雷霆万钧

    类型:长整型
    默认值:0
    取值:[0,...]
    服务器默认属性:log.roll.jitter.ms
    重要性:中等
  • segment.ms

    此配置控制 Kafka 将强制日志滚动的时间段,即使 Segment 文件未满,以确保保留可以删除或压缩旧数据。

    类型:长整型
    默认值:604800000 (7 天)
    取值:[1,...]
    服务器默认属性:log.roll.ms
    重要性:中等
  • unclean.leader.election.enable

    指示是否将不在 ISR 集中的副本选为领导者作为最后的手段,即使这样做可能会导致数据丢失。

    类型:布尔
    默认值:
    取值:
    服务器默认属性:unclean.leader.election.enable
    重要性:中等
  • message.downconversion.enable

    此配置控制是否启用消息格式的向下转换以满足 consume 请求。当设置为false,broker 不会为需要较旧消息格式的使用者执行向下转换。代理使用UNSUPPORTED_VERSION来自此类旧客户端的 consume 请求的错误。此配置不适用于复制到追随者可能需要的任何消息格式转换。

    类型:布尔
    默认值:
    取值:
    服务器默认属性:log.message.downconversion.enable
    重要性:

3.3 生产者配置

以下是 producer 的配置:
  • key.serializer

    Serializer 类,用于实现org.apache.kafka.common.serialization.Serializer接口。

    类型:
    默认值:
    取值:
    重要性:
  • value.serializer

    Serializer 类,用于实现org.apache.kafka.common.serialization.Serializer接口。

    类型:
    默认值:
    取值:
    重要性:
  • 引导程序.服务器

    用于建立与 Kafka 集群的初始连接的主机/端口对列表。客户端将使用所有服务器,而不管此处指定了哪些服务器进行引导 — 此列表仅影响用于发现完整服务器集的初始主机。此列表应采用以下格式host1:port1,host2:port2,....由于这些服务器仅用于初始连接以发现完整的集群成员身份(可能会动态更改),因此此列表不需要包含完整的服务器集(尽管您可能需要多个服务器,以防服务器关闭)。

    类型:列表
    默认值:""
    取值:非 null 字符串
    重要性:
  • buffer.memory

    创建者可用于缓冲等待发送到服务器的记录的内存总字节数。如果记录的发送速度超过它们被传送到服务器的速度,则生产者将阻止max.block.ms之后它将引发异常。

    此设置应大致对应于生产者将使用的总内存,但不是硬性限制,因为并非生产者使用的所有内存都用于缓冲。一些额外的内存将用于压缩(如果启用了压缩)以及维护正在进行的请求。

    类型:长整型
    默认值:33554432
    取值:[0,...]
    重要性:
  • compression.type

    创建者生成的所有数据的压缩类型。默认值为 none (即 no compression)。有效值为none,gzip,snappy,lz4zstd.压缩是全批数据的压缩,因此批处理的有效性也会影响压缩率(批处理越多意味着压缩效果越好)。

    类型:字符串
    默认值:没有
    取值:[无、gzip、snappy、lz4、zstd]
    重要性:
  • 重试

    设置大于零的值将导致客户端重新发送发送失败并出现潜在暂时性错误的任何记录。请注意,此重试与客户端在收到错误时重新发送记录没有什么不同。如果delivery.timeout.ms在成功确认之前先过期。用户通常希望不设置此配置,而是使用delivery.timeout.ms以控制重试行为。

    启用幂等性要求此配置值大于 0。如果设置了冲突的配置,并且未明确启用幂等性,则禁用幂等性。

    允许在设置enable.idempotencefalsemax.in.flight.requests.per.connection大于 1 可能会更改记录的顺序,因为如果将两个批次发送到单个分区,并且第一个批次失败并重试,但第二个批次成功,则第二个批次中的记录可能会首先显示。

    类型:int
    默认值:2147483647
    取值:[0,...,2147483647]
    重要性:
  • ssl.key.password

    密钥存储文件中私钥的密码或 'ssl.keystore.key' 中指定的 PEM 密钥。

    类型:密码
    默认值:
    取值:
    重要性:
  • ssl.keystore.certificate.chain

    由 'ssl.keystore.type' 指定的格式的证书链。默认 SSL 引擎工厂仅支持带有 X.509 证书列表的 PEM 格式

    类型:密码
    默认值:
    取值:
    重要性:
  • ssl.keystore.key

    由 'ssl.keystore.type' 指定的格式的私钥。默认 SSL 引擎工厂仅支持带有 PKCS#8 密钥的 PEM 格式。如果密钥已加密,则必须使用 'ssl.key.password' 指定密钥密码

    类型:密码
    默认值:
    取值:
    重要性:
  • ssl.keystore.location

    密钥存储文件的位置。这对于客户端是可选的,可用于客户端的双向身份验证。

    类型:字符串
    默认值:
    取值:
    重要性:
  • ssl.keystore.password

    密钥存储文件的存储密码。这对于客户端来说是可选的,只有在配置了 'ssl.keystore.location' 时才需要。PEM 格式不支持密钥存储密码。

    类型:密码
    默认值:
    取值:
    重要性:
  • ssl.truststore.certificates 证书

    由 'ssl.truststore.type' 指定格式的受信任证书。默认 SSL 引擎工厂仅支持具有 X.509 证书的 PEM 格式。

    类型:密码
    默认值:
    取值:
    重要性:
  • ssl.truststore.location

    信任存储文件的位置。

    类型:字符串
    默认值:
    取值:
    重要性:
  • ssl.truststore.password

    信任存储文件的密码。如果未设置密码,则仍将使用配置的信任存储文件,但会禁用完整性检查。PEM 格式不支持信任存储密码。

    类型:密码
    默认值:
    取值:
    重要性:
  • batch.size

    每当将多条记录发送到同一分区时,创建器将尝试将记录一起批处理到更少的请求中。这有助于客户端和服务器的性能。此配置控制默认批处理大小(以字节为单位)。

    不会尝试对大于此大小的记录进行批处理。

    发送到 broker 的请求将包含多个批次,每个批次对应一个包含可发送数据的分区。

    较小的批处理大小将使批处理不太常见,并且可能会降低吞吐量(批处理大小为零将完全禁用批处理)。非常大的批处理大小可能会更浪费内存,因为我们总是会分配指定批处理大小的缓冲区,以预期额外的记录。

    注意: 此设置给出了要发送的批量大小的上限。如果此分区累积的字节数少于此数量,我们将“延迟”等待linger.ms等待更多记录显示的时间。这linger.ms设置为 0,这意味着即使累积的 batch size 低于 0,我们也会立即发送一条记录batch.size设置。

    类型:int
    默认值:16384
    取值:[0,...]
    重要性:中等
  • 客户端.dns.lookup

    控制客户端如何使用 DNS 查找。如果设置为use_all_dns_ips,依次连接到每个返回的 IP 地址,直到建立成功连接。断开连接后,将使用下一个 IP。一旦所有 IP 都被使用了一次,客户端就会再次从主机名解析 IP(但是,JVM 和 OS 缓存 DNS 名称查找)。如果设置为resolve_canonical_bootstrap_servers_only中,将每个引导地址解析为规范名称列表。在 bootstrap 阶段之后,其行为与use_all_dns_ips.

    类型:字符串
    默认值:use_all_dns_ips
    取值:[use_all_dns_ips、resolve_canonical_bootstrap_servers_only]
    重要性:中等
  • client.id

    发出请求时传递给服务器的 id 字符串。这样做的目的是通过允许在服务器端请求日志记录中包含逻辑应用程序名称来跟踪 ip/port 之外的请求来源。

    类型:字符串
    默认值:""
    取值:
    重要性:中等
  • connections.max.idle.ms

    在此配置指定的毫秒数后关闭空闲连接。

    类型:长整型
    默认值:540000 (9 分钟)
    取值:
    重要性:中等
  • delivery.timeout.ms

    调用send()返回。这将限制记录在发送之前延迟的总时间、等待代理确认的时间(如果预期)以及允许可重试发送失败的时间。如果遇到不可恢复的错误、重试次数已用尽,或者将记录添加到已提前到达投放到期截止日期的批处理中,则创建者可能会报告未能发送早于此配置的记录。此配置的值应大于或等于request.timeout.mslinger.ms.

    类型:int
    默认值:120000 (2 分钟)
    取值:[0,...]
    重要性:中等
  • linger.ms

    创建者将请求传输之间到达的任何记录分组到单个批处理请求中。通常,这仅在 load 下发生,当记录到达的速度比发送速度快时。但是,在某些情况下,即使在中等负载下,客户端也可能希望减少请求数。此设置通过添加少量人为延迟来实现此目的,也就是说,创建者将等待给定的延迟,以允许发送其他记录,以便可以一起批处理发送,而不是立即发送记录。这可以被认为是类似于 TCP 中的 Nagle 算法。此设置给出了批处理延迟的上限:一旦我们得到batch.size的记录数,无论此设置如何,它都会立即发送,但是,如果此分区累积的字节数少于此数量,我们将“逗留”指定时间,等待更多记录显示。此设置默认为 0 (即无延迟)。设置linger.ms=5,例如,将具有减少发送的请求数的效果,但在没有负载的情况下,会给发送的记录增加多达 5 毫秒的延迟。

    类型:长整型
    默认值:0
    取值:[0,...]
    重要性:中等
  • max.block.ms

    该配置控制KafkaProducersend(),partitionsFor(),initTransactions(),sendOffsetsToTransaction(),commitTransaction()abortTransaction()方法将阻塞。为send()此超时限制了等待元数据获取和缓冲区分配的总时间(用户提供的序列化程序或分区程序中的阻塞不计入此超时)。为partitionsFor()如果元数据不可用,则此超时会限制等待元数据所花费的时间。与事务相关的方法始终阻塞,但如果无法发现事务协调器或在超时时间内未响应,则可能会超时。

    类型:长整型
    默认值:60000 (1 分钟)
    取值:[0,...]
    重要性:中等
  • 最大请求大小

    请求的最大大小(以字节为单位)。此设置将限制创建者在单个请求中发送的记录批次数,以避免发送大量请求。这实际上也是最大未压缩记录批量大小的上限。请注意,服务器对记录批量大小(如果启用了压缩,则在压缩后)有自己的上限,这可能与此不同。

    类型:int
    默认值:1048576
    取值:[0,...]
    重要性:中等
  • partitioner.class

    一个类,用于确定在生成记录时要发送到哪个分区。可用选项包括:

    • 如果未设置,则使用默认分区逻辑。此策略将尝试坚持使用分区,直到至少为分区生成 batch.size 字节。它与以下策略一起工作:
      • 如果未指定分区但存在键,请根据键的哈希值选择分区
      • 如果不存在分区或键,请选择在分区至少生成 batch.size 字节时更改的粘性分区。
    • org.apache.kafka.clients.producer.RoundRobinPartitioner: 这种分区策略是一系列连续记录中的每条记录都会被发送到不同的分区(无论是否提供 'key'),直到我们用完分区并重新开始。注意:存在一个已知问题,该问题会导致在创建新批次时分布不均匀。请查看 KAFKA-9965 了解更多详情。

    实施org.apache.kafka.clients.producer.Partitionerinterface 允许您插入自定义分区程序。

    类型:
    默认值:
    取值:
    重要性:中等
  • partitioner.ignore.keys

    当设置为 'true' 时,创建器不会使用记录键来选择分区。如果为 'false',则 producer 将在存在 key 时根据 key 的哈希值选择分区。注意:如果使用自定义分区程序,则此设置无效。

    类型:布尔
    默认值:
    取值:
    重要性:中等
  • receive.buffer.bytes

    读取数据时使用的 TCP 接收缓冲区 (SO_RCVBUF) 的大小。如果值为 -1,则将使用 OS 默认值。

    类型:int
    默认值:32768 (32 千字节)
    取值:[-1,...]
    重要性:中等
  • request.timeout.ms

    该配置控制客户端等待请求响应的最长时间。如果在超时之前未收到响应,则客户端将在必要时重新发送请求,如果重试次数已用尽,则请求失败。这应该大于replica.lag.time.max.ms(代理配置),以减少由于不必要的生产者重试而导致消息重复的可能性。

    类型:int
    默认值:30000 (30 秒)
    取值:[0,...]
    重要性:中等
  • sasl.client.callback.handler.class

    实现 AuthenticateCallbackHandler 接口的 SASL 客户端回调处理程序类的完全限定名称。

    类型:
    默认值:
    取值:
    重要性:中等
  • sasl.jaas.config

    SASL 连接的 JAAS 登录上下文参数,采用 JAAS 配置文件使用的格式。此处描述了 JAAS 配置文件格式。该值的格式为:loginModuleClass controlFlag (optionName=optionValue)*;.对于代理,配置必须以小写的侦听器前缀和 SASL 机制名称为前缀。例如,listener.name.sasl_ssl.scram-sha-256.sasl.jaas.config=com.example.ScramLoginModule required;

    类型:密码
    默认值:
    取值:
    重要性:中等
  • sasl.kerberos.service.name

    Kafka 运行的 Kerberos 主体名称。这可以在 Kafka 的 JAAS 配置或 Kafka 的配置中定义。

    类型:字符串
    默认值:
    取值:
    重要性:中等
  • sasl.login.callback.handler.class

    实现 AuthenticateCallbackHandler 接口的 SASL 登录回调处理程序类的完全限定名称。对于 broker,登录回调处理程序 config 必须以侦听器前缀和小写的 SASL 机制名称为前缀。例如,listener.name.sasl_ssl.scram-sha-256.sasl.login.callback.handler.class=com.example.CustomScramLoginCallbackHandler

    类型:
    默认值:
    取值:
    重要性:中等
  • sasl.login.class

    实现 Login 接口的类的完全限定名称。对于 broker,登录配置必须以 listener prefix 和小写的 SASL 机制名称为前缀。例如,listener.name.sasl_ssl.scram-sha-256.sasl.login.class=com.example.CustomScramLogin

    类型:
    默认值:
    取值:
    重要性:中等
  • sasl.mechanism

    用于客户端连接的 SASL 机制。这可以是安全提供程序可用的任何机制。GSSAPI 是默认机制。

    类型:字符串
    默认值:GSSAPI
    取值:
    重要性:中等
  • sasl.oauthbearer.jwks.endpoint.url

    OAuth/OIDC 提供者 URL,可从中检索提供者的 JWKS(JSON Web 密钥集)。URL 可以基于 HTTP(S) 或基于文件。如果 URL 基于 HTTP(S),则在代理启动时,将通过配置的 URL 从 OAuth/OIDC 提供程序检索 JWKS 数据。所有当时的密钥都将缓存在 broker 上,用于传入请求。如果收到对 JWT 的身份验证请求,该请求包含尚未在缓存中的“kid”标头声明值,则将按需再次查询 JWKS 终端节点。但是,代理每 sasl.oauthbearer.jwks.endpoint.refresh.ms 毫秒轮询一次 URL,以便在收到包含任何 URL 的 JWT 请求之前使用任何即将到来的密钥刷新缓存。如果 URL 是基于文件的,则代理将在启动时从配置的位置加载 JWKS 文件。如果 JWT 包含的 “kid” 标头值不在 JWKS 文件中,则代理将拒绝 JWT,并且身份验证将失败。

    类型:字符串
    默认值:
    取值:
    重要性:中等
  • sasl.oauthbearer.token.endpoint.url

    OAuth/OIDC 身份提供商的 URL。如果 URL 基于 HTTP(S),则它是颁发者的令牌端点 URL,将根据 sasl.jaas.config 中的配置向其发出登录请求。如果 URL 是基于文件的,则它会指定一个文件,其中包含由 OAuth/OIDC 身份提供者颁发的用于授权的访问令牌(JWT 序列化格式)。

    类型:字符串
    默认值:
    取值:
    重要性:中等
  • 安全协议

    用于与 broker 通信的协议。有效值为:PLAINTEXT、SSL、SASL_PLAINTEXT、SASL_SSL。

    类型:字符串
    默认值:明文
    取值:(不区分大小写)[SASL_SSL、明文、SSL SASL_PLAINTEXT]
    重要性:中等
  • 发送.buffer.bytes

    发送数据时使用的 TCP 发送缓冲区的大小 (SO_SNDBUF)。如果值为 -1,则将使用 OS 默认值。

    类型:int
    默认值:131072 (128 KB)
    取值:[-1,...]
    重要性:中等
  • socket.connection.setup.timeout.max.ms

    客户端等待建立套接字连接的最长时间。对于每个连续的连接失败,连接设置超时将呈指数级增长,直到达到此最大值。为避免连接风暴,将对超时应用随机化因子 0.2,从而产生低于计算值 20% 到高于计算值 20% 的随机范围。

    类型:长整型
    默认值:30000 (30 秒)
    取值:
    重要性:中等
  • socket.connection.setup.timeout.ms

    客户端等待建立套接字连接的时间。如果在超时时间之前未建立连接,则 Client 端将关闭套接字通道。

    类型:长整型
    默认值:10000 (10 秒)
    取值:
    重要性:中等
  • ssl.enabled.protocols 协议

    为 SSL 连接启用的协议列表。使用 Java 11 或更高版本运行时,默认值为 'TLSv1.2,TLSv1.3',否则为 'TLSv1.2'。使用 Java 11 的默认值,如果客户端和服务器都支持 TLSv1.3,则客户端和服务器将首选 TLSv1.3,否则将回退到 TLSv1.2(假设两者都至少支持 TLSv1.2)。在大多数情况下,此默认值应该很好。另请参阅 'ssl.protocol' 的配置文档。

    类型:列表
    默认值:TLSv1.2、TLSv1.3
    取值:
    重要性:中等
  • ssl.keystore.type

    密钥存储文件的文件格式。这对客户端来说是可选的。默认 'ssl.engine.factory.class' 当前支持的值为 [JKS, PKCS12, PEM]。

    类型:字符串
    默认值:JKS
    取值:
    重要性:中等
  • ssl.protocol 协议

    用于生成 SSLContext 的 SSL 协议。使用 Java 11 或更高版本运行时,默认值为 'TLSv1.3',否则为 'TLSv1.2'。对于大多数用例,此值应该很好。最近的 JVM 中允许的值为 'TLSv1.2' 和 'TLSv1.3'。较旧的 JVM 可能支持“TLS”、“TLSv1.1”、“SSL”、“SSLv2”和“SSLv3”,但由于已知的安全漏洞,不鼓励使用它们。使用此配置的默认值和 'ssl.enabled.protocols',如果服务器不支持 'TLSv1.3',则客户端将降级到 'TLSv1.2'。如果此配置设置为 'TLSv1.2',则客户端将不会使用 'TLSv1.3',即使它是 ssl.enabled.protocols 中的值之一,并且服务器仅支持 'TLSv1.3'。

    类型:字符串
    默认值:TLSv1.3 版本
    取值:
    重要性:中等
  • ssl.provider

    用于 SSL 连接的安全提供程序的名称。默认值是 JVM 的默认安全提供程序。

    类型:字符串
    默认值:
    取值:
    重要性:中等
  • ssl.truststore.type

    信任存储文件的文件格式。默认 'ssl.engine.factory.class' 当前支持的值为 [JKS, PKCS12, PEM]。

    类型:字符串
    默认值:JKS
    取值:
    重要性:中等
  • ACK 系列

    生产者要求领导者在将请求视为完成之前收到的确认数。这将控制发送的记录的持久性。允许以下设置:

    • acks=0如果设置为零,则 producer 根本不会等待服务器的任何确认。该记录将立即添加到 socket 缓冲区中,并被视为已发送。在这种情况下,不能保证服务器已经收到了记录,并且retries配置不会生效(因为客户端通常不会知道任何失败)。每条记录返回的偏移量将始终设置为-1.
    • acks=1这意味着领导者会将记录写入其本地日志,但无需等待所有追随者的完全确认即可做出响应。在这种情况下,如果 leader 在确认记录后立即失败,但在 followers 复制记录之前,则记录将丢失。
    • acks=all这意味着 leader 将等待完整的同步副本集来确认记录。这保证了只要至少有一个同步副本保持活动状态,记录就不会丢失。这是最强的可用保证。这相当于 acks=-1 设置。

    请注意,启用幂等性要求此配置值为 'all'。如果设置了冲突的配置,并且未明确启用幂等性,则禁用幂等性。

    类型:字符串
    默认值:
    取值:[全部, -1, 0, 1]
    重要性:
  • auto.include.jmx.reporter

    荒废的。是否自动包含 JmxReporter,即使它未在metric.reporters.此配置将在 Kafka 4.0 中删除,用户应包含org.apache.kafka.common.metrics.JmxReportermetric.reporters以启用 JmxReporter。

    类型:布尔
    默认值:
    取值:
    重要性:
  • enable.幂等性

    当设置为 'true' 时,创建者将确保在流中写入每条消息的一个副本。如果为“false”,则由于代理故障等原因导致的创建者重试可能会在流中写入重试消息的重复项。请注意,启用幂等性需要max.in.flight.requests.per.connection小于或等于 5(为任何允许的值保留消息顺序),retries大于 0,并且acks必须是 'all'。

    如果未设置冲突配置,则默认启用幂等性。如果设置了冲突的配置,并且未明确启用幂等性,则禁用幂等性。如果显式启用了幂等性并且设置了冲突的配置,则ConfigException被抛出。

    类型:布尔
    默认值:
    取值:
    重要性:
  • interceptor.classes

    要用作拦截器的类列表。实施org.apache.kafka.clients.producer.ProducerInterceptor接口允许您在将创建者收到的记录发布到 Kafka 集群之前拦截(并可能更改)这些记录。默认情况下,没有侦听器。

    类型:列表
    默认值:""
    取值:非 null 字符串
    重要性:
  • max.in.flight.requests.per.connection

    客户端在阻止之前将在单个连接上发送的最大未确认请求数。请注意,如果此配置设置为大于 1 且enable.idempotence设置为 false,则存在由于重试(即启用重试)而导致发送失败后消息重新排序的风险;如果禁用重试或enable.idempotence设置为 true,则将保留 Sequences。此外,启用幂等性要求此配置的值小于或等于 5。如果设置了冲突的配置,并且未明确启用幂等性,则禁用幂等性。

    类型:int
    默认值:5
    取值:[1,...]
    重要性:
  • metadata.max.age.ms

    以毫秒为单位的时间段,在此之后,即使我们没有看到任何分区领导更改以主动发现任何新的代理或分区,我们也会强制刷新元数据。

    类型:长整型
    默认值:300000 (5 分钟)
    取值:[0,...]
    重要性:
  • metadata.max.idle.ms

    控制创建者将缓存空闲主题的元数据的时间。如果自上次生成主题以来经过的时间超过元数据空闲持续时间,则主题的元数据将被遗忘,下次访问该主题将强制执行元数据获取请求。

    类型:长整型
    默认值:300000 (5 分钟)
    取值:[5000,...]
    重要性:
  • metric.reporters

    要用作指标报告器的类列表。实施org.apache.kafka.common.metrics.MetricsReporterinterface 允许插入类,这些类将在创建新指标时收到通知。JmxReporter 始终包含在内以注册 JMX 统计信息。

    类型:列表
    默认值:""
    取值:非 null 字符串
    重要性:
  • metrics.num.samples

    为计算指标而维护的样本数。

    类型:int
    默认值:2
    取值:[1,...]
    重要性:
  • metrics.recording.level

    指标的最高记录级别。

    类型:字符串
    默认值:信息
    取值:[信息、调试、跟踪]
    重要性:
  • metrics.sample.window.ms

    计算指标样本的时间窗口。

    类型:长整型
    默认值:30000 (30 秒)
    取值:[0,...]
    重要性:
  • partitioner.adaptive.partitioning.enable

    当设置为 'true' 时,创建者将尝试适应代理性能,并向托管在更快代理上的分区生成更多消息。如果为 'false',则 producer 将尝试统一分发消息。注意:如果使用自定义分区程序,则此设置无效

    类型:布尔
    默认值:
    取值:
    重要性:
  • partitioner.availability.timeout.ms

    如果 broker 无法处理来自分区的 Generate 请求partitioner.availability.timeout.mstime,则分区程序会将该分区视为不可用。如果值为 0,则禁用此逻辑。注意:如果使用自定义分区程序或partitioner.adaptive.partitioning.enable设置为 'false'

    类型:长整型
    默认值:0
    取值:[0,...]
    重要性:
  • reconnect.backoff.max.ms

    重新连接到多次连接失败的代理时等待的最长时间(以毫秒为单位)。如果提供,则对于每个连续连接失败,每个主机的回退将呈指数级增加,直到达到此最大值。计算出退避增幅后,增加 20% 的随机抖动,避免连接风暴。

    类型:长整型
    默认值:1000(1 秒)
    取值:[0,...]
    重要性:
  • reconnect.backoff.ms

    尝试重新连接到给定主机之前要等待的基本时间。这避免了在紧密循环中重复连接到主机。此回退适用于客户端与 broker 的所有连接尝试。

    类型:长整型
    默认值:50
    取值:[0,...]
    重要性:
  • retry.backoff.ms

    在尝试重试对给定主题分区的失败请求之前等待的时间。这避免了在某些故障情况下以紧密循环的形式重复发送请求。

    类型:长整型
    默认值:100
    取值:[0,...]
    重要性:
  • sasl.kerberos.kinit.cmd

    Kerberos kinit 命令路径。

    类型:字符串
    默认值:/usr/bin/kinit 中
    取值:
    重要性:
  • sasl.kerberos.min.time.before.relogin

    刷新尝试之间的登录线程休眠时间。

    类型:长整型
    默认值:60000
    取值:
    重要性:
  • sasl.kerberos.ticket.renew.jitter

    添加到续订时间的随机抖动的百分比。

    类型:双整型
    默认值:0.05
    取值:
    重要性:
  • sasl.kerberos.ticket.renew.window.factor

    登录线程将休眠,直到达到从上次刷新到票证到期的指定窗口时间因子,此时它将尝试续订票证。

    类型:双整型
    默认值:0.8
    取值:
    重要性:
  • sasl.login.connect.timeout.ms

    外部身份验证提供程序连接超时的(可选)值(以毫秒为单位)。当前仅适用于 OAUTHBEARER。

    类型:int
    默认值:
    取值:
    重要性:
  • sasl.login.read.timeout.ms

    外部身份验证提供程序读取超时的(可选)值(以毫秒为单位)。当前仅适用于 OAUTHBEARER。

    类型:int
    默认值:
    取值:
    重要性:
  • sasl.login.refresh.buffer.seconds

    刷新凭证时要保持的凭证过期前要保持的缓冲时间(以秒为单位)。如果刷新时间比缓冲秒数更接近过期时间,则刷新将上移以保持尽可能多的缓冲时间。合法值介于 0 和 3600 之间(1 小时);如果未指定值,则使用默认值 300(5 分钟)。如果此值和 sasl.login.refresh.min.period.seconds 的总和超过凭证的剩余生命周期,则它们都将被忽略。当前仅适用于 OAUTHBEARER。

    类型:
    默认值:300
    取值:[0,...,3600]
    重要性:
  • sasl.login.refresh.min.period.seconds

    登录刷新线程在刷新凭证之前等待的所需最短时间(以秒为单位)。合法值介于 0 到 900 之间(15 分钟);如果未指定值,则使用默认值 60(1 分钟)。如果此值和 sasl.login.refresh.buffer.seconds 的总和超过凭证的剩余生命周期,则它们都将被忽略。当前仅适用于 OAUTHBEARER。

    类型:
    默认值:60
    取值:[0,...,900]
    重要性:
  • sasl.login.refresh.window.factor

    登录刷新线程将休眠,直到达到相对于凭证生命周期的指定窗口因子,此时它将尝试刷新凭证。合法值介于 0.5 (50%) 和 1.0 (100%) 之间(含);如果未指定值,则使用默认值 0.8 (80%)。当前仅适用于 OAUTHBEARER。

    类型:双整型
    默认值:0.8
    取值:[0.5,...,1.0]
    重要性:
  • sasl.login.refresh.window.jitter

    相对于凭证生命周期的最大随机抖动量,该抖动量添加到登录刷新线程的休眠时间中。合法值介于 0 和 0.25 (25%) 之间(含 0 和 0.25 年);如果未指定值,则使用默认值 0.05 (5%)。当前仅适用于 OAUTHBEARER。

    类型:双整型
    默认值:0.05
    取值:[0.0,...,0.25]
    重要性:
  • sasl.login.retry.backoff.max.ms

    (可选)值(以毫秒为单位),表示尝试登录外部身份验证提供程序之间的最大等待时间。Login 使用指数退避算法,初始等待基于 sasl.login.retry.backoff.ms 设置,并且将在两次尝试之间将等待长度增加一倍,直到达到 sasl.login.retry.backoff.max.ms 设置指定的最大等待长度。当前仅适用于 OAUTHBEARER。

    类型:长整型
    默认值:10000 (10 秒)
    取值:
    重要性:
  • sasl.login.retry.backoff.ms

    尝试登录外部身份验证提供程序之间的初始等待时间的(可选)值(以毫秒为单位)。Login 使用指数退避算法,初始等待基于 sasl.login.retry.backoff.ms 设置,并且将在两次尝试之间将等待长度增加一倍,直到达到 sasl.login.retry.backoff.max.ms 设置指定的最大等待长度。当前仅适用于 OAUTHBEARER。

    类型:长整型
    默认值:100
    取值:
    重要性:
  • sasl.oauthbearer.clock.skew.seconds

    (可选)值(以秒为单位),以允许 OAuth/OIDC 身份提供者和代理的时间之间存在差异。

    类型:int
    默认值:30
    取值:
    重要性:
  • sasl.oauthbearer.expected.audience

    代理使用的(可选)逗号分隔设置,用于验证 JWT 是否是针对预期受众之一颁发的。将检查 JWT 的标准 OAuth “aud” 声明,如果设置了此值,代理将匹配 JWT 的 “aud” 声明中的值,以查看是否存在完全匹配。如果没有匹配项,代理将拒绝 JWT,并且身份验证将失败。

    类型:列表
    默认值:
    取值:
    重要性:
  • sasl.oauthbearer.expected.issuer

    代理用于验证 JWT 是否由预期颁发者创建的(可选)设置。将检查 JWT 中的标准 OAuth “iss” 声明,如果设置了此值,代理会将其与 JWT 的 “iss” 声明中的内容完全匹配。如果没有匹配项,代理将拒绝 JWT,并且身份验证将失败。

    类型:字符串
    默认值:
    取值:
    重要性:
  • sasl.oauthbearer.jwks.endpoint.refresh.ms

    代理在刷新其 JWKS(JSON Web 密钥集)缓存(包含密钥以验证 JWT 签名)之间等待的(可选)值(以毫秒为单位)。

    类型:长整型
    默认值:3600000 (1 小时)
    取值:
    重要性:
  • sasl.oauthbearer.jwks.endpoint.retry.backoff.max.ms

    尝试从外部身份验证提供程序检索 JWKS(JSON Web 密钥集)之间的最大等待时间的(可选)值(以毫秒为单位)。JWKS 检索使用指数退避算法,初始等待基于 sasl.oauthbearer.jwks.endpoint.retry.backoff.ms 设置,并且将两次尝试之间的等待长度增加一倍,直到达到 sasl.oauthbearer.jwks.endpoint.retry.backoff.max.ms 设置指定的最大等待长度。

    类型:长整型
    默认值:10000 (10 秒)
    取值:
    重要性:
  • sasl.oauthbearer.jwks.endpoint.retry.backoff.ms

    来自外部身份验证提供程序的 JWKS(JSON Web 密钥集)检索尝试之间的初始等待的(可选)值(以毫秒为单位)。JWKS 检索使用指数退避算法,初始等待基于 sasl.oauthbearer.jwks.endpoint.retry.backoff.ms 设置,并且将两次尝试之间的等待长度增加一倍,直到达到 sasl.oauthbearer.jwks.endpoint.retry.backoff.max.ms 设置指定的最大等待长度。

    类型:长整型
    默认值:100
    取值:
    重要性:
  • sasl.oauthbearer.scope.claim.name

    范围的 OAuth 声明通常命名为“范围”,但如果 OAuth/OIDC 提供商对该声明使用不同的名称,则此(可选)设置可以提供不同的名称,以用于 JWT 负载声明中包含的范围。

    类型:字符串
    默认值:范围
    取值:
    重要性:
  • sasl.oauthbearer.sub.claim.name

    主题的 OAuth 声明通常命名为“sub”,但如果 OAuth/OIDC 提供商对该声明使用不同的名称,则此(可选)设置可以提供不同的名称,以用于 JWT 负载声明中包含的主题。

    类型:字符串
    默认值:
    取值:
    重要性:
  • security.providers

    可配置的 creator 类的列表,每个类返回一个实现安全算法的提供程序。这些类应该实现org.apache.kafka.common.security.auth.SecurityProviderCreator接口。

    类型:字符串
    默认值:
    取值:
    重要性:
  • ssl.cipher.suites

    密码套件列表。这是身份验证、加密、MAC 和密钥交换算法的命名组合,用于协商使用 TLS 或 SSL 网络协议的网络连接的安全设置。默认情况下,支持所有可用的密码套件。

    类型:列表
    默认值:
    取值:
    重要性:
  • ssl.endpoint.identification.algorithm

    终端节点识别算法,用于使用服务器证书验证服务器主机名。

    类型:字符串
    默认值:https
    取值:
    重要性:
  • ssl.engine.factory.class

    org.apache.kafka.common.security.auth.SslEngineFactory 类型的类,用于提供 SSLEngine 对象。默认值为 org.apache.kafka.common.security.ssl.DefaultSslEngineFactory

    类型:
    默认值:
    取值:
    重要性:
  • ssl.keymanager.algorithm

    密钥管理器工厂用于 SSL 连接的算法。默认值是为 Java 虚拟机配置的密钥管理器工厂算法。

    类型:字符串
    默认值:SunX509 系列
    取值:
    重要性:
  • ssl.secure.random.implementation

    用于 SSL 加密作的 SecureRandom PRNG 实现。

    类型:字符串
    默认值:
    取值:
    重要性:
  • ssl.trustmanager.algorithm

    信任管理器工厂用于 SSL 连接的算法。默认值是为 Java 虚拟机配置的信任管理器工厂算法。

    类型:字符串
    默认值:PKIX
    取值:
    重要性:
  • transaction.timeout.ms

    在协调器主动中止事务之前,事务将保持打开状态的最长时间(以毫秒为单位)。事务的开始是在将第一个分区添加到事务时设置的。如果此值大于transaction.max.timeout.ms设置,请求将失败,并显示InvalidTxnTimeoutException错误。

    类型:int
    默认值:60000 (1 分钟)
    取值:
    重要性:
  • transactional.id

    用于事务性传输的 TransactionalId。这将启用跨多个生产者会话的可靠性语义,因为它允许客户端保证在开始任何新事务之前已经完成了使用相同 TransactionalId 的事务。如果未提供 TransactionalId,则生产者仅限于幂等传输。如果配置了 TransactionalId,则enable.idempotence是隐含的。默认情况下,未配置 TransactionId,这意味着无法使用事务。请注意,默认情况下,事务需要至少三个代理的集群,这是 production 的推荐设置;对于开发,您可以通过调整 broker 设置来更改此设置transaction.state.log.replication.factor.

    类型:字符串
    默认值:
    取值:非空字符串
    重要性:

3.4 消费者配置

以下是使用者的配置:
  • key.deserializer

    Deserializer 类实现org.apache.kafka.common.serialization.Deserializer接口。

    类型:
    默认值:
    取值:
    重要性:
  • value.deserializer

    Deserializer 类,用于实现org.apache.kafka.common.serialization.Deserializer接口。

    类型:
    默认值:
    取值:
    重要性:
  • 引导程序.服务器

    用于建立与 Kafka 集群的初始连接的主机/端口对列表。客户端将使用所有服务器,而不管此处指定了哪些服务器进行引导 — 此列表仅影响用于发现完整服务器集的初始主机。此列表应采用以下格式host1:port1,host2:port2,....由于这些服务器仅用于初始连接以发现完整的集群成员身份(可能会动态更改),因此此列表不需要包含完整的服务器集(尽管您可能需要多个服务器,以防服务器关闭)。

    类型:列表
    默认值:""
    取值:非 null 字符串
    重要性:
  • fetch.min.bytes

    服务器应为 fetch 请求返回的最小数据量。如果可用数据不足,则请求将等待累积该数量的数据,然后再响应请求。默认设置为 1 字节意味着一旦有该字节的数据可用,或者 fetch 请求在等待数据到达时超时,就会立即响应 fetch 请求。将此值设置为较大的值将导致服务器等待大量数据累积,这可以稍微提高服务器吞吐量,但代价是一些额外的延迟。

    类型:int
    默认值:1
    取值:[0,...]
    重要性:
  • group.id

    标识此使用者所属的使用者组的唯一字符串。如果使用者通过使用subscribe(topic)或基于 Kafka 的胶印管理策略。

    类型:字符串
    默认值:
    取值:
    重要性:
  • heartbeat.interval.ms

    使用 Kafka 的组管理工具时,向使用者协调器发送心跳之间的预期时间。检测信号用于确保使用者的会话保持活动状态,并在新使用者加入或离开组时促进重新平衡。该值必须设置为低于session.timeout.ms,但通常应设置为不高于该值的 1/3。它可以调整得更低,以控制正常再平衡的预期时间。

    类型:int
    默认值:3000(3 秒)
    取值:
    重要性:
  • max.partition.fetch.bytes

    服务器将返回的每个分区的最大数据量。记录由使用者分批获取。如果 fetch 的第一个非空 partition 中的第一个记录 batch 大于此限制,则仍将返回该 batch,以确保 consumer 可以进行进度。代理接受的最大记录批量大小是通过message.max.bytes(broker config) 或max.message.bytes(主题配置)。请参阅 fetch.max.bytes 以限制使用者请求大小。

    类型:int
    默认值:1048576 (1 MB)
    取值:[0,...]
    重要性:
  • session.timeout.ms

    用于在使用 Kafka 的组管理工具时检测客户端故障的超时。客户端定期发送检测信号,以向代理指示其活动状态。如果在此会话超时到期之前代理未收到检测信号,则代理将从组中删除此客户端并启动再平衡。请注意,该值必须在代理配置中配置的允许范围内group.min.session.timeout.msgroup.max.session.timeout.ms.

    类型:int
    默认值:45000(45 秒)
    取值:
    重要性:
  • ssl.key.password

    密钥存储文件中私钥的密码或 'ssl.keystore.key' 中指定的 PEM 密钥。

    类型:密码
    默认值:
    取值:
    重要性:
  • ssl.keystore.certificate.chain

    由 'ssl.keystore.type' 指定的格式的证书链。默认 SSL 引擎工厂仅支持带有 X.509 证书列表的 PEM 格式

    类型:密码
    默认值:
    取值:
    重要性:
  • ssl.keystore.key

    由 'ssl.keystore.type' 指定的格式的私钥。默认 SSL 引擎工厂仅支持带有 PKCS#8 密钥的 PEM 格式。如果密钥已加密,则必须使用 'ssl.key.password' 指定密钥密码

    类型:密码
    默认值:
    取值:
    重要性:
  • ssl.keystore.location

    密钥存储文件的位置。这对于客户端是可选的,可用于客户端的双向身份验证。

    类型:字符串
    默认值:
    取值:
    重要性:
  • ssl.keystore.password

    密钥存储文件的存储密码。这对于客户端来说是可选的,只有在配置了 'ssl.keystore.location' 时才需要。PEM 格式不支持密钥存储密码。

    类型:密码
    默认值:
    取值:
    重要性:
  • ssl.truststore.certificates 证书

    由 'ssl.truststore.type' 指定格式的受信任证书。默认 SSL 引擎工厂仅支持具有 X.509 证书的 PEM 格式。

    类型:密码
    默认值:
    取值:
    重要性:
  • ssl.truststore.location

    信任存储文件的位置。

    类型:字符串
    默认值:
    取值:
    重要性:
  • ssl.truststore.password

    信任存储文件的密码。如果未设置密码,则仍将使用配置的信任存储文件,但会禁用完整性检查。PEM 格式不支持信任存储密码。

    类型:密码
    默认值:
    取值:
    重要性:
  • allow.auto.create.topics

    允许在订阅或分配主题时在代理上自动创建主题。只有当代理允许使用 'auto.create.topics.enable' 代理配置时,才会自动创建被订阅的主题。当使用低于 0.11.0 的代理时,此配置必须设置为 'false'

    类型:布尔
    默认值:
    取值:
    重要性:中等
  • 自动偏移重置

    当 Kafka 中没有初始偏移量或当前偏移量在服务器上不再存在时(例如,因为该数据已被删除),该怎么办:

    • earliest:自动将 offset 重置为最早的 offset
    • latest:自动将 offset 重置为最新的 offset
    • none:如果未找到 Consumer 组的上一个偏移量,则向 Consumer 抛出异常
    • 任何其他内容:向使用者抛出异常。

    类型:字符串
    默认值:最近的
    取值:[最新、最早、无]
    重要性:中等
  • 客户端.dns.lookup

    控制客户端如何使用 DNS 查找。如果设置为use_all_dns_ips,依次连接到每个返回的 IP 地址,直到建立成功连接。断开连接后,将使用下一个 IP。一旦所有 IP 都被使用了一次,客户端就会再次从主机名解析 IP(但是,JVM 和 OS 缓存 DNS 名称查找)。如果设置为resolve_canonical_bootstrap_servers_only中,将每个引导地址解析为规范名称列表。在 bootstrap 阶段之后,其行为与use_all_dns_ips.

    类型:字符串
    默认值:use_all_dns_ips
    取值:[use_all_dns_ips、resolve_canonical_bootstrap_servers_only]
    重要性:中等
  • connections.max.idle.ms

    在此配置指定的毫秒数后关闭空闲连接。

    类型:长整型
    默认值:540000 (9 分钟)
    取值:
    重要性:中等
  • default.api.timeout.ms

    指定客户端 API 的超时 (以毫秒为单位)。此配置用作未指定timeout参数。

    类型:int
    默认值:60000 (1 分钟)
    取值:[0,...]
    重要性:中等
  • enable.auto.commit

    如果为 true,则 Consumer 的偏移量将在后台定期提交。

    类型:布尔
    默认值:
    取值:
    重要性:中等
  • exclude.internal.topics

    是否应从订阅中排除与订阅模式匹配的内部主题。始终可以显式订阅内部主题。

    类型:布尔
    默认值:
    取值:
    重要性:中等
  • fetch.max.bytes

    服务器应为 fetch 请求返回的最大数据量。记录是由消费者批量获取的,如果 fetch 的第一个非空分区中的第一个记录 batch 大于此值,仍然会返回记录 batch,以保证消费者可以进行。因此,这不是绝对的最大值。代理接受的最大记录批量大小是通过message.max.bytes(broker config) 或max.message.bytes(主题配置)。请注意,使用者并行执行多个 fetch。

    类型:int
    默认值:52428800 (50 MB)
    取值:[0,...]
    重要性:中等
  • group.instance.id

    最终用户提供的使用者实例的唯一标识符。只允许使用非空字符串。如果设置,则使用者将被视为静态成员,这意味着任何时候使用者组中都只允许一个具有此 ID 的实例。这可以与更大的会话超时结合使用,以避免由瞬时不可用(例如进程重启)引起的组重新平衡。如果未设置,使用者将作为动态成员加入组,这是传统行为。

    类型:字符串
    默认值:
    取值:非空字符串
    重要性:中等
  • 隔离级别

    控制如何读取以事务方式写入的消息。如果设置为read_committed,consumer.poll() 将仅返回已提交的事务性消息。如果设置为read_uncommitted(默认)的 consumer.poll() 将返回所有消息,甚至是已中止的事务性消息。非事务性消息将在任一模式下无条件返回。

    消息将始终按偏移顺序返回。因此,在read_committed模式下,consumer.poll() 只会返回最后一个稳定偏移量 (LSO) 的消息,该偏移量小于第一个打开事务的偏移量。特别是,在属于正在进行的交易的消息之后出现的任何消息都将被保留,直到相关交易完成。因此,read_committed当存在 IN FLIGHT 交易时,消费者将无法读取最高水位线。

    此外,当在read_committedseekToEnd 方法将返回 LSO

    类型:字符串
    默认值:read_uncommitted
    取值:[read_committed、read_uncommitted]
    重要性:中等
  • max.poll.interval.ms

    使用消费者组管理时 poll() 调用之间的最大延迟。这为使用者在获取更多记录之前可以空闲的时间设置了上限。如果在此超时到期之前未调用 poll(),则使用者被视为失败,并且该组将重新平衡以将分区重新分配给另一个成员。对于使用非 null 的使用者group.instance.id达到此超时时间,则不会立即重新分配分区。相反,消费者将停止发送检测信号,分区将在session.timeout.ms.这反映了具有 shutdown 的静态使用者的行为。

    类型:int
    默认值:300000 (5 分钟)
    取值:[1,...]
    重要性:中等
  • 最大轮询记录

    对 poll() 的单次调用中返回的最大记录数。请注意,max.poll.records不会影响底层获取行为。消费者将缓存每个 fetch 请求中的记录,并从每个轮询中以增量方式返回它们。

    类型:int
    默认值:500
    取值:[1,...]
    重要性:中等
  • partition.assignment.strategy

    类名或类类型的列表,按首选项排序,支持的分区分配策略,在使用组管理时,客户端将使用这些策略在使用者实例之间分配分区所有权。可用选项包括:

    • org.apache.kafka.clients.consumer.RangeAssignor:按主题分配分区。
    • org.apache.kafka.clients.consumer.RoundRobinAssignor:以循环方式将分区分配给使用者。
    • org.apache.kafka.clients.consumer.StickyAssignor:保证分配在最大程度上平衡,同时保留尽可能多的现有分区分配。
    • org.apache.kafka.clients.consumer.CooperativeStickyAssignor:遵循相同的 StickyAssignor 逻辑,但允许协作重新平衡。

    默认分配器是 [RangeAssignor, CooperativeStickyAssignor],默认情况下将使用 RangeAssignor,但允许升级到 CooperativeStickyAssignor,只需一次滚动退回即可从列表中删除 RangeAssignor。

    实施org.apache.kafka.clients.consumer.ConsumerPartitionAssignorinterface 允许您插入自定义分配策略。

    类型:列表
    默认值:类 org.apache.kafka.clients.consumer.RangeAssignor,类 org.apache.kafka.clients.consumer.CooperativeStickyAssignor
    取值:非 null 字符串
    重要性:中等
  • receive.buffer.bytes

    读取数据时使用的 TCP 接收缓冲区 (SO_RCVBUF) 的大小。如果值为 -1,则将使用 OS 默认值。

    类型:int
    默认值:65536 (64 千字节)
    取值:[-1,...]
    重要性:中等
  • request.timeout.ms

    该配置控制客户端等待请求响应的最长时间。如果在超时之前未收到响应,则客户端将在必要时重新发送请求,如果重试次数已用尽,则请求失败。

    类型:int
    默认值:30000 (30 秒)
    取值:[0,...]
    重要性:中等
  • sasl.client.callback.handler.class

    实现 AuthenticateCallbackHandler 接口的 SASL 客户端回调处理程序类的完全限定名称。

    类型:
    默认值:
    取值:
    重要性:中等
  • sasl.jaas.config

    SASL 连接的 JAAS 登录上下文参数,采用 JAAS 配置文件使用的格式。此处描述了 JAAS 配置文件格式。该值的格式为:loginModuleClass controlFlag (optionName=optionValue)*;.对于代理,配置必须以小写的侦听器前缀和 SASL 机制名称为前缀。例如,listener.name.sasl_ssl.scram-sha-256.sasl.jaas.config=com.example.ScramLoginModule required;

    类型:密码
    默认值:
    取值:
    重要性:中等
  • sasl.kerberos.service.name

    Kafka 运行的 Kerberos 主体名称。这可以在 Kafka 的 JAAS 配置或 Kafka 的配置中定义。

    类型:字符串
    默认值:
    取值:
    重要性:中等
  • sasl.login.callback.handler.class

    实现 AuthenticateCallbackHandler 接口的 SASL 登录回调处理程序类的完全限定名称。对于 broker,登录回调处理程序 config 必须以侦听器前缀和小写的 SASL 机制名称为前缀。例如,listener.name.sasl_ssl.scram-sha-256.sasl.login.callback.handler.class=com.example.CustomScramLoginCallbackHandler

    类型:
    默认值:
    取值:
    重要性:中等
  • sasl.login.class

    实现 Login 接口的类的完全限定名称。对于 broker,登录配置必须以 listener prefix 和小写的 SASL 机制名称为前缀。例如,listener.name.sasl_ssl.scram-sha-256.sasl.login.class=com.example.CustomScramLogin

    类型:
    默认值:
    取值:
    重要性:中等
  • sasl.mechanism

    用于客户端连接的 SASL 机制。这可以是安全提供程序可用的任何机制。GSSAPI 是默认机制。

    类型:字符串
    默认值:GSSAPI
    取值:
    重要性:中等
  • sasl.oauthbearer.jwks.endpoint.url

    OAuth/OIDC 提供者 URL,可从中检索提供者的 JWKS(JSON Web 密钥集)。URL 可以基于 HTTP(S) 或基于文件。如果 URL 基于 HTTP(S),则在代理启动时,将通过配置的 URL 从 OAuth/OIDC 提供程序检索 JWKS 数据。所有当时的密钥都将缓存在 broker 上,用于传入请求。如果收到对 JWT 的身份验证请求,该请求包含尚未在缓存中的“kid”标头声明值,则将按需再次查询 JWKS 终端节点。但是,代理每 sasl.oauthbearer.jwks.endpoint.refresh.ms 毫秒轮询一次 URL,以便在收到包含任何 URL 的 JWT 请求之前使用任何即将到来的密钥刷新缓存。如果 URL 是基于文件的,则代理将在启动时从配置的位置加载 JWKS 文件。如果 JWT 包含的 “kid” 标头值不在 JWKS 文件中,则代理将拒绝 JWT,并且身份验证将失败。

    类型:字符串
    默认值:
    取值:
    重要性:中等
  • sasl.oauthbearer.token.endpoint.url

    OAuth/OIDC 身份提供商的 URL。如果 URL 基于 HTTP(S),则它是颁发者的令牌端点 URL,将根据 sasl.jaas.config 中的配置向其发出登录请求。如果 URL 是基于文件的,则它会指定一个文件,其中包含由 OAuth/OIDC 身份提供者颁发的用于授权的访问令牌(JWT 序列化格式)。

    类型:字符串
    默认值:
    取值:
    重要性:中等
  • 安全协议

    用于与 broker 通信的协议。有效值为:PLAINTEXT、SSL、SASL_PLAINTEXT、SASL_SSL。

    类型:字符串
    默认值:明文
    取值:(不区分大小写)[SASL_SSL、明文、SSL SASL_PLAINTEXT]
    重要性:中等
  • 发送.buffer.bytes

    发送数据时使用的 TCP 发送缓冲区的大小 (SO_SNDBUF)。如果值为 -1,则将使用 OS 默认值。

    类型:int
    默认值:131072 (128 KB)
    取值:[-1,...]
    重要性:中等
  • socket.connection.setup.timeout.max.ms

    客户端等待建立套接字连接的最长时间。对于每个连续的连接失败,连接设置超时将呈指数级增长,直到达到此最大值。为避免连接风暴,将对超时应用随机化因子 0.2,从而产生低于计算值 20% 到高于计算值 20% 的随机范围。

    类型:长整型
    默认值:30000 (30 秒)
    取值:
    重要性:中等
  • socket.connection.setup.timeout.ms

    客户端等待建立套接字连接的时间。如果在超时时间之前未建立连接,则 Client 端将关闭套接字通道。

    类型:长整型
    默认值:10000 (10 秒)
    取值:
    重要性:中等
  • ssl.enabled.protocols 协议

    为 SSL 连接启用的协议列表。使用 Java 11 或更高版本运行时,默认值为 'TLSv1.2,TLSv1.3',否则为 'TLSv1.2'。使用 Java 11 的默认值,如果客户端和服务器都支持 TLSv1.3,则客户端和服务器将首选 TLSv1.3,否则将回退到 TLSv1.2(假设两者都至少支持 TLSv1.2)。在大多数情况下,此默认值应该很好。另请参阅 'ssl.protocol' 的配置文档。

    类型:列表
    默认值:TLSv1.2、TLSv1.3
    取值:
    重要性:中等
  • ssl.keystore.type

    密钥存储文件的文件格式。这对客户端来说是可选的。默认 'ssl.engine.factory.class' 当前支持的值为 [JKS, PKCS12, PEM]。

    类型:字符串
    默认值:JKS
    取值:
    重要性:中等
  • ssl.protocol 协议

    用于生成 SSLContext 的 SSL 协议。使用 Java 11 或更高版本运行时,默认值为 'TLSv1.3',否则为 'TLSv1.2'。对于大多数用例,此值应该很好。最近的 JVM 中允许的值为 'TLSv1.2' 和 'TLSv1.3'。较旧的 JVM 可能支持“TLS”、“TLSv1.1”、“SSL”、“SSLv2”和“SSLv3”,但由于已知的安全漏洞,不鼓励使用它们。使用此配置的默认值和 'ssl.enabled.protocols',如果服务器不支持 'TLSv1.3',则客户端将降级到 'TLSv1.2'。如果此配置设置为 'TLSv1.2',则客户端将不会使用 'TLSv1.3',即使它是 ssl.enabled.protocols 中的值之一,并且服务器仅支持 'TLSv1.3'。

    类型:字符串
    默认值:TLSv1.3 版本
    取值:
    重要性:中等
  • ssl.provider

    用于 SSL 连接的安全提供程序的名称。默认值是 JVM 的默认安全提供程序。

    类型:字符串
    默认值:
    取值:
    重要性:中等
  • ssl.truststore.type

    信任存储文件的文件格式。默认 'ssl.engine.factory.class' 当前支持的值为 [JKS, PKCS12, PEM]。

    类型:字符串
    默认值:JKS
    取值:
    重要性:中等
  • auto.commit.interval.ms

    如果enable.auto.commit设置为true.

    类型:int
    默认值:5000(5 秒)
    取值:[0,...]
    重要性:
  • auto.include.jmx.reporter

    荒废的。是否自动包含 JmxReporter,即使它未在metric.reporters.此配置将在 Kafka 4.0 中删除,用户应包含org.apache.kafka.common.metrics.JmxReportermetric.reporters以启用 JmxReporter。

    类型:布尔
    默认值:
    取值:
    重要性:
  • check.crcs 文件

    自动检查已使用记录的 CRC32。这可确保消息不会发生在线或磁盘损坏。此检查会增加一些开销,因此在寻求极致性能的情况下可能会禁用它。

    类型:布尔
    默认值:
    取值:
    重要性:
  • client.id

    发出请求时传递给服务器的 id 字符串。这样做的目的是通过允许在服务器端请求日志记录中包含逻辑应用程序名称来跟踪 ip/port 之外的请求来源。

    类型:字符串
    默认值:""
    取值:
    重要性:
  • 客户端.rack

    此客户端的机架标识符。这可以是指示此客户端实际位置的任何字符串值。它与代理配置 'broker.rack' 对应

    类型:字符串
    默认值:""
    取值:
    重要性:
  • fetch.max.wait.ms

    如果没有足够的数据来立即满足 fetch.min.bytes 给出的要求,则服务器在响应 fetch 请求之前将阻塞的最长时间。

    类型:int
    默认值:500
    取值:[0,...]
    重要性:
  • interceptor.classes

    要用作拦截器的类列表。实施org.apache.kafka.clients.consumer.ConsumerInterceptorinterface 允许你拦截(并可能改变)消费者收到的记录。默认情况下,没有侦听器。

    类型:列表
    默认值:""
    取值:非 null 字符串
    重要性:
  • metadata.max.age.ms

    以毫秒为单位的时间段,在此之后,即使我们没有看到任何分区领导更改以主动发现任何新的代理或分区,我们也会强制刷新元数据。

    类型:长整型
    默认值:300000 (5 分钟)
    取值:[0,...]
    重要性:
  • metric.reporters

    要用作指标报告器的类列表。实施org.apache.kafka.common.metrics.MetricsReporterinterface 允许插入类,这些类将在创建新指标时收到通知。JmxReporter 始终包含在内以注册 JMX 统计信息。

    类型:列表
    默认值:""
    取值:非 null 字符串
    重要性:
  • metrics.num.samples

    为计算指标而维护的样本数。

    类型:int
    默认值:2
    取值:[1,...]
    重要性:
  • metrics.recording.level

    指标的最高记录级别。

    类型:字符串
    默认值:信息
    取值:[信息、调试、跟踪]
    重要性:
  • metrics.sample.window.ms

    计算指标样本的时间窗口。

    类型:长整型
    默认值:30000 (30 秒)
    取值:[0,...]
    重要性:
  • reconnect.backoff.max.ms

    重新连接到多次连接失败的代理时等待的最长时间(以毫秒为单位)。如果提供,则对于每个连续连接失败,每个主机的回退将呈指数级增加,直到达到此最大值。计算出退避增幅后,增加 20% 的随机抖动,避免连接风暴。

    类型:长整型
    默认值:1000(1 秒)
    取值:[0,...]
    重要性:
  • reconnect.backoff.ms

    尝试重新连接到给定主机之前要等待的基本时间。这避免了在紧密循环中重复连接到主机。此回退适用于客户端与 broker 的所有连接尝试。

    类型:长整型
    默认值:50
    取值:[0,...]
    重要性:
  • retry.backoff.ms

    在尝试重试对给定主题分区的失败请求之前等待的时间。这避免了在某些故障情况下以紧密循环的形式重复发送请求。

    类型:长整型
    默认值:100
    取值:[0,...]
    重要性:
  • sasl.kerberos.kinit.cmd

    Kerberos kinit 命令路径。

    类型:字符串
    默认值:/usr/bin/kinit 中
    取值:
    重要性:
  • sasl.kerberos.min.time.before.relogin

    刷新尝试之间的登录线程休眠时间。

    类型:长整型
    默认值:60000
    取值:
    重要性:
  • sasl.kerberos.ticket.renew.jitter

    添加到续订时间的随机抖动的百分比。

    类型:双整型
    默认值:0.05
    取值:
    重要性:
  • sasl.kerberos.ticket.renew.window.factor

    登录线程将休眠,直到达到从上次刷新到票证到期的指定窗口时间因子,此时它将尝试续订票证。

    类型:双整型
    默认值:0.8
    取值:
    重要性:
  • sasl.login.connect.timeout.ms

    外部身份验证提供程序连接超时的(可选)值(以毫秒为单位)。当前仅适用于 OAUTHBEARER。

    类型:int
    默认值:
    取值:
    重要性:
  • sasl.login.read.timeout.ms

    外部身份验证提供程序读取超时的(可选)值(以毫秒为单位)。当前仅适用于 OAUTHBEARER。

    类型:int
    默认值:
    取值:
    重要性:
  • sasl.login.refresh.buffer.seconds

    刷新凭证时要保持的凭证过期前要保持的缓冲时间(以秒为单位)。如果刷新时间比缓冲秒数更接近过期时间,则刷新将上移以保持尽可能多的缓冲时间。合法值介于 0 和 3600 之间(1 小时);如果未指定值,则使用默认值 300(5 分钟)。如果此值和 sasl.login.refresh.min.period.seconds 的总和超过凭证的剩余生命周期,则它们都将被忽略。当前仅适用于 OAUTHBEARER。

    类型:
    默认值:300
    取值:[0,...,3600]
    重要性:
  • sasl.login.refresh.min.period.seconds

    登录刷新线程在刷新凭证之前等待的所需最短时间(以秒为单位)。合法值介于 0 到 900 之间(15 分钟);如果未指定值,则使用默认值 60(1 分钟)。如果此值和 sasl.login.refresh.buffer.seconds 的总和超过凭证的剩余生命周期,则它们都将被忽略。当前仅适用于 OAUTHBEARER。

    类型:
    默认值:60
    取值:[0,...,900]
    重要性:
  • sasl.login.refresh.window.factor

    登录刷新线程将休眠,直到达到相对于凭证生命周期的指定窗口因子,此时它将尝试刷新凭证。合法值介于 0.5 (50%) 和 1.0 (100%) 之间(含);如果未指定值,则使用默认值 0.8 (80%)。当前仅适用于 OAUTHBEARER。

    类型:双整型
    默认值:0.8
    取值:[0.5,...,1.0]
    重要性:
  • sasl.login.refresh.window.jitter

    相对于凭证生命周期的最大随机抖动量,该抖动量添加到登录刷新线程的休眠时间中。合法值介于 0 和 0.25 (25%) 之间(含 0 和 0.25 年);如果未指定值,则使用默认值 0.05 (5%)。当前仅适用于 OAUTHBEARER。

    类型:双整型
    默认值:0.05
    取值:[0.0,...,0.25]
    重要性:
  • sasl.login.retry.backoff.max.ms

    (可选)值(以毫秒为单位),表示尝试登录外部身份验证提供程序之间的最大等待时间。Login 使用指数退避算法,初始等待基于 sasl.login.retry.backoff.ms 设置,并且将在两次尝试之间将等待长度增加一倍,直到达到 sasl.login.retry.backoff.max.ms 设置指定的最大等待长度。当前仅适用于 OAUTHBEARER。

    类型:长整型
    默认值:10000 (10 秒)
    取值:
    重要性:
  • sasl.login.retry.backoff.ms

    尝试登录外部身份验证提供程序之间的初始等待时间的(可选)值(以毫秒为单位)。Login 使用指数退避算法,初始等待基于 sasl.login.retry.backoff.ms 设置,并且将在两次尝试之间将等待长度增加一倍,直到达到 sasl.login.retry.backoff.max.ms 设置指定的最大等待长度。当前仅适用于 OAUTHBEARER。

    类型:长整型
    默认值:100
    取值:
    重要性:
  • sasl.oauthbearer.clock.skew.seconds

    (可选)值(以秒为单位),以允许 OAuth/OIDC 身份提供者和代理的时间之间存在差异。

    类型:int
    默认值:30
    取值:
    重要性:
  • sasl.oauthbearer.expected.audience

    代理使用的(可选)逗号分隔设置,用于验证 JWT 是否是针对预期受众之一颁发的。将检查 JWT 的标准 OAuth “aud” 声明,如果设置了此值,代理将匹配 JWT 的 “aud” 声明中的值,以查看是否存在完全匹配。如果没有匹配项,代理将拒绝 JWT,并且身份验证将失败。

    类型:列表
    默认值:
    取值:
    重要性:
  • sasl.oauthbearer.expected.issuer

    代理用于验证 JWT 是否由预期颁发者创建的(可选)设置。将检查 JWT 中的标准 OAuth “iss” 声明,如果设置了此值,代理会将其与 JWT 的 “iss” 声明中的内容完全匹配。如果没有匹配项,代理将拒绝 JWT,并且身份验证将失败。

    类型:字符串
    默认值:
    取值:
    重要性:
  • sasl.oauthbearer.jwks.endpoint.refresh.ms

    代理在刷新其 JWKS(JSON Web 密钥集)缓存(包含密钥以验证 JWT 签名)之间等待的(可选)值(以毫秒为单位)。

    类型:长整型
    默认值:3600000 (1 小时)
    取值:
    重要性:
  • sasl.oauthbearer.jwks.endpoint.retry.backoff.max.ms

    尝试从外部身份验证提供程序检索 JWKS(JSON Web 密钥集)之间的最大等待时间的(可选)值(以毫秒为单位)。JWKS 检索使用指数退避算法,初始等待基于 sasl.oauthbearer.jwks.endpoint.retry.backoff.ms 设置,并且将两次尝试之间的等待长度增加一倍,直到达到 sasl.oauthbearer.jwks.endpoint.retry.backoff.max.ms 设置指定的最大等待长度。

    类型:长整型
    默认值:10000 (10 秒)
    取值:
    重要性:
  • sasl.oauthbearer.jwks.endpoint.retry.backoff.ms

    来自外部身份验证提供程序的 JWKS(JSON Web 密钥集)检索尝试之间的初始等待的(可选)值(以毫秒为单位)。JWKS 检索使用指数退避算法,初始等待基于 sasl.oauthbearer.jwks.endpoint.retry.backoff.ms 设置,并且将两次尝试之间的等待长度增加一倍,直到达到 sasl.oauthbearer.jwks.endpoint.retry.backoff.max.ms 设置指定的最大等待长度。

    类型:长整型
    默认值:100
    取值:
    重要性:
  • sasl.oauthbearer.scope.claim.name

    范围的 OAuth 声明通常命名为“范围”,但如果 OAuth/OIDC 提供商对该声明使用不同的名称,则此(可选)设置可以提供不同的名称,以用于 JWT 负载声明中包含的范围。

    类型:字符串
    默认值:范围
    取值:
    重要性:
  • sasl.oauthbearer.sub.claim.name

    主题的 OAuth 声明通常命名为“sub”,但如果 OAuth/OIDC 提供商对该声明使用不同的名称,则此(可选)设置可以提供不同的名称,以用于 JWT 负载声明中包含的主题。

    类型:字符串
    默认值:
    取值:
    重要性:
  • security.providers

    可配置的 creator 类的列表,每个类返回一个实现安全算法的提供程序。这些类应该实现org.apache.kafka.common.security.auth.SecurityProviderCreator接口。

    类型:字符串
    默认值:
    取值:
    重要性:
  • ssl.cipher.suites

    密码套件列表。这是身份验证、加密、MAC 和密钥交换算法的命名组合,用于协商使用 TLS 或 SSL 网络协议的网络连接的安全设置。默认情况下,支持所有可用的密码套件。

    类型:列表
    默认值:
    取值:
    重要性:
  • ssl.endpoint.identification.algorithm

    终端节点识别算法,用于使用服务器证书验证服务器主机名。

    类型:字符串
    默认值:https
    取值:
    重要性:
  • ssl.engine.factory.class

    org.apache.kafka.common.security.auth.SslEngineFactory 类型的类,用于提供 SSLEngine 对象。默认值为 org.apache.kafka.common.security.ssl.DefaultSslEngineFactory

    类型:
    默认值:
    取值:
    重要性:
  • ssl.keymanager.algorithm

    密钥管理器工厂用于 SSL 连接的算法。默认值是为 Java 虚拟机配置的密钥管理器工厂算法。

    类型:字符串
    默认值:SunX509 系列
    取值:
    重要性:
  • ssl.secure.random.implementation

    用于 SSL 加密作的 SecureRandom PRNG 实现。

    类型:字符串
    默认值:
    取值:
    重要性:
  • ssl.trustmanager.algorithm

    信任管理器工厂用于 SSL 连接的算法。默认值是为 Java 虚拟机配置的信任管理器工厂算法。

    类型:字符串
    默认值:PKIX
    取值:
    重要性:

3.5 Kafka Connect 配置

以下是 Kafka Connect 框架的配置。
  • config.storage.topic

    存储连接器配置的 Kafka 主题的名称

    类型:字符串
    默认值:
    取值:
    重要性:
  • group.id

    一个唯一字符串,用于标识此工作程序所属的 Connect 集群组。

    类型:字符串
    默认值:
    取值:
    重要性:
  • key.converter

    Converter 类,用于在 Kafka Connect 格式和写入 Kafka 的序列化形式之间进行转换。这控制写入 Kafka 或从 Kafka 读取的消息中键的格式,并且由于这与连接器无关,因此它允许任何连接器使用任何序列化格式。常见格式的示例包括 JSON 和 Avro。

    类型:
    默认值:
    取值:
    重要性:
  • offset.storage.topic

    存储源连接器偏移量的 Kafka 主题的名称

    类型:字符串
    默认值:
    取值:
    重要性:
  • 状态存储主题

    存储连接器和任务状态的 Kafka 主题的名称

    类型:字符串
    默认值:
    取值:
    重要性:
  • value.converter

    Converter 类,用于在 Kafka Connect 格式和写入 Kafka 的序列化形式之间进行转换。这控制写入 Kafka 或从 Kafka 读取的消息中值的格式,并且由于这与连接器无关,因此它允许任何连接器使用任何序列化格式。常见格式的示例包括 JSON 和 Avro。

    类型:
    默认值:
    取值:
    重要性:
  • 引导程序.服务器

    用于建立与 Kafka 集群的初始连接的主机/端口对列表。客户端将使用所有服务器,而不管此处指定了哪些服务器进行引导 — 此列表仅影响用于发现完整服务器集的初始主机。此列表应采用以下格式host1:port1,host2:port2,....由于这些服务器仅用于初始连接以发现完整的集群成员身份(可能会动态更改),因此此列表不需要包含完整的服务器集(尽管您可能需要多个服务器,以防服务器关闭)。

    类型:列表
    默认值:本地主机:9092
    取值:
    重要性:
  • exactly.once.source.support

    是否通过使用事务写入源记录及其源偏移量,以及在启动新任务代之前主动屏蔽旧任务代,从而在集群中启用对源连接器的精确一次支持。
    要在新集群上启用恰好一次源支持,请将此属性设置为 'enabled'。要在现有集群上启用支持,请先在集群中的每个 worker 上设置为 'preparing',然后设置为 'enabled'。滚动升级可用于这两项更改。有关此功能的更多信息,请参阅 exactly-once 源支持文档

    类型:字符串
    默认值:禁用
    取值:(不区分大小写)[已禁用、已启用、正在准备]
    重要性:
  • heartbeat.interval.ms

    使用 Kafka 的组管理工具时,向组协调器发送心跳之间的预期时间。心跳用于确保工作人员的会话保持活动状态,并在新成员加入或离开组时促进重新平衡。该值必须设置为低于session.timeout.ms,但通常应设置为不高于该值的 1/3。它可以调整得更低,以控制正常再平衡的预期时间。

    类型:int
    默认值:3000(3 秒)
    取值:
    重要性:
  • rebalance.timeout.ms

    再平衡开始后,每个工作线程加入组的最长时间。这基本上是对所有任务刷新任何待处理数据和提交偏移量所需的时间的限制。如果超过超时,则 worker 将从组中删除,这将导致偏移提交失败。

    类型:int
    默认值:60000 (1 分钟)
    取值:
    重要性:
  • session.timeout.ms

    用于检测 worker 故障的超时。worker 定期发送检测信号,以向 broker 指示其活动状态。如果在此会话超时到期之前,代理未收到任何检测信号,则代理将从组中删除该工作线程并启动再平衡。请注意,该值必须在代理配置中配置的允许范围内group.min.session.timeout.msgroup.max.session.timeout.ms.

    类型:int
    默认值:10000 (10 秒)
    取值:
    重要性:
  • ssl.key.password

    密钥存储文件中私钥的密码或 'ssl.keystore.key' 中指定的 PEM 密钥。

    类型:密码
    默认值:
    取值:
    重要性:
  • ssl.keystore.certificate.chain

    由 'ssl.keystore.type' 指定的格式的证书链。默认 SSL 引擎工厂仅支持带有 X.509 证书列表的 PEM 格式

    类型:密码
    默认值:
    取值:
    重要性:
  • ssl.keystore.key

    由 'ssl.keystore.type' 指定的格式的私钥。默认 SSL 引擎工厂仅支持带有 PKCS#8 密钥的 PEM 格式。如果密钥已加密,则必须使用 'ssl.key.password' 指定密钥密码

    类型:密码
    默认值:
    取值:
    重要性:
  • ssl.keystore.location

    密钥存储文件的位置。这对于客户端是可选的,可用于客户端的双向身份验证。

    类型:字符串
    默认值:
    取值:
    重要性:
  • ssl.keystore.password

    密钥存储文件的存储密码。这对于客户端来说是可选的,只有在配置了 'ssl.keystore.location' 时才需要。PEM 格式不支持密钥存储密码。

    类型:密码
    默认值:
    取值:
    重要性:
  • ssl.truststore.certificates 证书

    由 'ssl.truststore.type' 指定格式的受信任证书。默认 SSL 引擎工厂仅支持具有 X.509 证书的 PEM 格式。

    类型:密码
    默认值:
    取值:
    重要性:
  • ssl.truststore.location

    信任存储文件的位置。

    类型:字符串
    默认值:
    取值:
    重要性:
  • ssl.truststore.password

    信任存储文件的密码。如果未设置密码,则仍将使用配置的信任存储文件,但会禁用完整性检查。PEM 格式不支持信任存储密码。

    类型:密码
    默认值:
    取值:
    重要性:
  • 客户端.dns.lookup

    控制客户端如何使用 DNS 查找。如果设置为use_all_dns_ips,依次连接到每个返回的 IP 地址,直到建立成功连接。断开连接后,将使用下一个 IP。一旦所有 IP 都被使用了一次,客户端就会再次从主机名解析 IP(但是,JVM 和 OS 缓存 DNS 名称查找)。如果设置为resolve_canonical_bootstrap_servers_only中,将每个引导地址解析为规范名称列表。在 bootstrap 阶段之后,其行为与use_all_dns_ips.

    类型:字符串
    默认值:use_all_dns_ips
    取值:[use_all_dns_ips、resolve_canonical_bootstrap_servers_only]
    重要性:中等
  • connections.max.idle.ms

    在此配置指定的毫秒数后关闭空闲连接。

    类型:长整型
    默认值:540000 (9 分钟)
    取值:
    重要性:中等
  • connector.client.config.override.policy

    的类名或实现别名ConnectorClientConfigOverridePolicy.定义连接器可以覆盖哪些客户端配置。默认实现为 'All',这意味着连接器配置可以覆盖所有客户端属性。框架中其他可能的策略包括“None”(禁止连接器覆盖客户端属性)和“Principal”(允许连接器仅覆盖客户端主体)。

    类型:字符串
    默认值:
    取值:
    重要性:中等
  • receive.buffer.bytes

    读取数据时使用的 TCP 接收缓冲区 (SO_RCVBUF) 的大小。如果值为 -1,则将使用 OS 默认值。

    类型:int
    默认值:32768 (32 千字节)
    取值:[-1,...]
    重要性:中等
  • request.timeout.ms

    该配置控制客户端等待请求响应的最长时间。如果在超时之前未收到响应,则客户端将在必要时重新发送请求,如果重试次数已用尽,则请求失败。

    类型:int
    默认值:40000(40 秒)
    取值:[0,...]
    重要性:中等
  • sasl.client.callback.handler.class

    实现 AuthenticateCallbackHandler 接口的 SASL 客户端回调处理程序类的完全限定名称。

    类型:
    默认值:
    取值:
    重要性:中等
  • sasl.jaas.config

    SASL 连接的 JAAS 登录上下文参数,采用 JAAS 配置文件使用的格式。此处描述了 JAAS 配置文件格式。该值的格式为:loginModuleClass controlFlag (optionName=optionValue)*;.对于代理,配置必须以小写的侦听器前缀和 SASL 机制名称为前缀。例如,listener.name.sasl_ssl.scram-sha-256.sasl.jaas.config=com.example.ScramLoginModule required;

    类型:密码
    默认值:
    取值:
    重要性:中等
  • sasl.kerberos.service.name

    Kafka 运行的 Kerberos 主体名称。这可以在 Kafka 的 JAAS 配置或 Kafka 的配置中定义。

    类型:字符串
    默认值:
    取值:
    重要性:中等
  • sasl.login.callback.handler.class

    实现 AuthenticateCallbackHandler 接口的 SASL 登录回调处理程序类的完全限定名称。对于 broker,登录回调处理程序 config 必须以侦听器前缀和小写的 SASL 机制名称为前缀。例如,listener.name.sasl_ssl.scram-sha-256.sasl.login.callback.handler.class=com.example.CustomScramLoginCallbackHandler

    类型:
    默认值:
    取值:
    重要性:中等
  • sasl.login.class

    实现 Login 接口的类的完全限定名称。对于 broker,登录配置必须以 listener prefix 和小写的 SASL 机制名称为前缀。例如,listener.name.sasl_ssl.scram-sha-256.sasl.login.class=com.example.CustomScramLogin

    类型:
    默认值:
    取值:
    重要性:中等
  • sasl.mechanism

    用于客户端连接的 SASL 机制。这可以是安全提供程序可用的任何机制。GSSAPI 是默认机制。

    类型:字符串
    默认值:GSSAPI
    取值:
    重要性:中等
  • sasl.oauthbearer.jwks.endpoint.url

    OAuth/OIDC 提供者 URL,可从中检索提供者的 JWKS(JSON Web 密钥集)。URL 可以基于 HTTP(S) 或基于文件。如果 URL 基于 HTTP(S),则在代理启动时,将通过配置的 URL 从 OAuth/OIDC 提供程序检索 JWKS 数据。所有当时的密钥都将缓存在 broker 上,用于传入请求。如果收到对 JWT 的身份验证请求,该请求包含尚未在缓存中的“kid”标头声明值,则将按需再次查询 JWKS 终端节点。但是,代理每 sasl.oauthbearer.jwks.endpoint.refresh.ms 毫秒轮询一次 URL,以便在收到包含任何 URL 的 JWT 请求之前使用任何即将到来的密钥刷新缓存。如果 URL 是基于文件的,则代理将在启动时从配置的位置加载 JWKS 文件。如果 JWT 包含的 “kid” 标头值不在 JWKS 文件中,则代理将拒绝 JWT,并且身份验证将失败。

    类型:字符串
    默认值:
    取值:
    重要性:中等
  • sasl.oauthbearer.token.endpoint.url

    OAuth/OIDC 身份提供商的 URL。如果 URL 基于 HTTP(S),则它是颁发者的令牌端点 URL,将根据 sasl.jaas.config 中的配置向其发出登录请求。如果 URL 是基于文件的,则它会指定一个文件,其中包含由 OAuth/OIDC 身份提供者颁发的用于授权的访问令牌(JWT 序列化格式)。

    类型:字符串
    默认值:
    取值:
    重要性:中等
  • 安全协议

    用于与 broker 通信的协议。有效值为:PLAINTEXT、SSL、SASL_PLAINTEXT、SASL_SSL。

    类型:字符串
    默认值:明文
    取值:(不区分大小写)[SASL_SSL、明文、SSL SASL_PLAINTEXT]
    重要性:中等
  • 发送.buffer.bytes

    发送数据时使用的 TCP 发送缓冲区的大小 (SO_SNDBUF)。如果值为 -1,则将使用 OS 默认值。

    类型:int
    默认值:131072 (128 KB)
    取值:[-1,...]
    重要性:中等
  • ssl.enabled.protocols 协议

    为 SSL 连接启用的协议列表。使用 Java 11 或更高版本运行时,默认值为 'TLSv1.2,TLSv1.3',否则为 'TLSv1.2'。使用 Java 11 的默认值,如果客户端和服务器都支持 TLSv1.3,则客户端和服务器将首选 TLSv1.3,否则将回退到 TLSv1.2(假设两者都至少支持 TLSv1.2)。在大多数情况下,此默认值应该很好。另请参阅 'ssl.protocol' 的配置文档。

    类型:列表
    默认值:TLSv1.2、TLSv1.3
    取值:
    重要性:中等
  • ssl.keystore.type

    密钥存储文件的文件格式。这对客户端来说是可选的。默认 'ssl.engine.factory.class' 当前支持的值为 [JKS, PKCS12, PEM]。

    类型:字符串
    默认值:JKS
    取值:
    重要性:中等
  • ssl.protocol 协议

    用于生成 SSLContext 的 SSL 协议。使用 Java 11 或更高版本运行时,默认值为 'TLSv1.3',否则为 'TLSv1.2'。对于大多数用例,此值应该很好。最近的 JVM 中允许的值为 'TLSv1.2' 和 'TLSv1.3'。较旧的 JVM 可能支持“TLS”、“TLSv1.1”、“SSL”、“SSLv2”和“SSLv3”,但由于已知的安全漏洞,不鼓励使用它们。使用此配置的默认值和 'ssl.enabled.protocols',如果服务器不支持 'TLSv1.3',则客户端将降级到 'TLSv1.2'。如果此配置设置为 'TLSv1.2',则客户端将不会使用 'TLSv1.3',即使它是 ssl.enabled.protocols 中的值之一,并且服务器仅支持 'TLSv1.3'。

    类型:字符串
    默认值:TLSv1.3 版本
    取值:
    重要性:中等
  • ssl.provider

    用于 SSL 连接的安全提供程序的名称。默认值是 JVM 的默认安全提供程序。

    类型:字符串
    默认值:
    取值:
    重要性:中等
  • ssl.truststore.type

    信任存储文件的文件格式。默认 'ssl.engine.factory.class' 当前支持的值为 [JKS, PKCS12, PEM]。

    类型:字符串
    默认值:JKS
    取值:
    重要性:中等
  • worker.sync.timeout.ms

    当工作程序与其他工作程序不同步并需要重新同步配置时,请等待此时间,然后再放弃、离开组并等待回退期,然后再重新加入。

    类型:int
    默认值:3000(3 秒)
    取值:
    重要性:中等
  • worker.unsync.backoff.ms

    当 worker 与其他 worker 不同步并且无法在 worker.sync.timeout.ms 中赶上时,请在重新加入之前离开 Connect 集群很长时间。

    类型:int
    默认值:300000 (5 分钟)
    取值:
    重要性:中等
  • access.control.allow.methods

    通过设置 Access-Control-Allow-Methods 标头来设置跨域请求支持的方法。Access-Control-Allow-Methods 标头的默认值允许对 GET、POST 和 HEAD 进行跨域请求。

    类型:字符串
    默认值:""
    取值:
    重要性:
  • access.control.allow.origin

    为 REST API 请求设置 Access-Control-Allow-Origin 标头的值。要启用跨域访问,请将其设置为应允许访问 API 的应用程序的域,或将 '*' 设置为允许从任何域进行访问。默认值仅允许从 REST API 的域进行访问。

    类型:字符串
    默认值:""
    取值:
    重要性:
  • admin.listeners

    管理员 REST API 将侦听的逗号分隔的 URI 列表。支持的协议包括 HTTP 和 HTTPS。空字符串或空白字符串将禁用此功能。默认行为是使用常规侦听器(由 'listeners' 属性指定)。

    类型:列表
    默认值:
    取值:逗号分隔的 URL 列表,例如:http://localhost:8080,https://localhost:8443。
    重要性:
  • auto.include.jmx.reporter

    荒废的。是否自动包含 JmxReporter,即使它未在metric.reporters.此配置将在 Kafka 4.0 中删除,用户应包含org.apache.kafka.common.metrics.JmxReportermetric.reporters以启用 JmxReporter。

    类型:布尔
    默认值:
    取值:
    重要性:
  • client.id

    发出请求时传递给服务器的 id 字符串。这样做的目的是通过允许在服务器端请求日志记录中包含逻辑应用程序名称来跟踪 ip/port 之外的请求来源。

    类型:字符串
    默认值:""
    取值:
    重要性:
  • config.providers

    的逗号分隔名称ConfigProvider类,按指定的顺序加载和使用。实现接口ConfigProvider允许您替换连接器配置中的变量引用,例如外部化密钥的变量引用。

    类型:列表
    默认值:""
    取值:
    重要性:
  • config.storage.replication.factor

    创建配置存储主题时使用的复制因子

    类型:
    默认值:3
    取值:正数不大于 Kafka 集群中的代理数,或者 -1 以使用代理的默认值
    重要性:
  • connect.protocol 协议

    Kafka Connect 协议的兼容模式

    类型:字符串
    默认值:会话
    取值:[热切、兼容、会话]
    重要性:
  • header.converter

    HeaderConverter 类,用于在 Kafka Connect 格式和写入 Kafka 的序列化形式之间进行转换。这控制写入 Kafka 或从 Kafka 读取的消息中标头值的格式,并且由于这独立于连接器,因此它允许任何连接器使用任何序列化格式。常见格式的示例包括 JSON 和 Avro。默认情况下,SimpleHeaderConverter 用于将标头值序列化为字符串,并通过推断架构来反序列化它们。

    类型:
    默认值:org.apache.kafka.connect.storage.SimpleHeaderConverter
    取值:
    重要性:
  • inter.worker.key.generation.algorithm

    用于生成内部请求密钥的算法。算法 'HmacSHA256' 将用作支持它的 JVM 的默认值;在其他 JVM 上,不使用 default,必须在 worker 配置中手动指定此属性的值。

    类型:字符串
    默认值:HmacSHA256
    取值:worker JVM 支持的任何 KeyGenerator 算法
    重要性:
  • inter.worker.key.size

    用于对内部请求进行签名的密钥的大小(以位为单位)。如果为 null,则将使用密钥生成算法的默认密钥大小。

    类型:int
    默认值:
    取值:
    重要性:
  • inter.worker.key.ttl.ms

    用于内部请求验证的生成的会话密钥的 TTL(以毫秒为单位)

    类型:int
    默认值:3600000 (1 小时)
    取值:[0,...,2147483647]
    重要性:
  • inter.worker.signature.algorithm

    用于对内部请求进行签名的算法算法 'inter.worker.signature.algorithm' 将用作支持它的 JVM 的默认值;在其他 JVM 上,不使用 default,必须在 worker 配置中手动指定此属性的值。

    类型:字符串
    默认值:HmacSHA256
    取值:worker JVM 支持的任何 MAC 算法
    重要性:
  • inter.worker.verification.algorithms

    用于验证内部请求的允许算法列表,其中必须包含用于 inter.worker.signature.algorithm 属性的算法。算法 '[HmacSHA256]' 将用作提供算法的 JVM 上的默认值;在其他 JVM 上,不使用 default,必须在 worker 配置中手动指定此属性的值。

    类型:列表
    默认值:HmacSHA256
    取值:一个或多个 MAC 算法的列表,每个算法都受 worker JVM 支持
    重要性:
  • 监听者

    REST API 将侦听的逗号分隔的 URI 列表。支持的协议包括 HTTP 和 HTTPS。
    指定 hostname 为 0.0.0.0 以绑定到所有接口。
    将 hostname 留空以绑定到 default 接口。
    合法侦听器列表示例:HTTP://myhost:8083,HTTPS://myhost:8084

    类型:列表
    默认值:http://:8083
    取值:逗号分隔的 URL 列表,例如:http://localhost:8080,https://localhost:8443。
    重要性:
  • metadata.max.age.ms

    以毫秒为单位的时间段,在此之后,即使我们没有看到任何分区领导更改以主动发现任何新的代理或分区,我们也会强制刷新元数据。

    类型:长整型
    默认值:300000 (5 分钟)
    取值:[0,...]
    重要性:
  • metric.reporters

    要用作指标报告器的类列表。实施org.apache.kafka.common.metrics.MetricsReporterinterface 允许插入类,这些类将在创建新指标时收到通知。JmxReporter 始终包含在内以注册 JMX 统计信息。

    类型:列表
    默认值:""
    取值:
    重要性:
  • metrics.num.samples

    为计算指标而维护的样本数。

    类型:int
    默认值:2
    取值:[1,...]
    重要性:
  • metrics.recording.level

    指标的最高记录级别。

    类型:字符串
    默认值:信息
    取值:[信息,调试]
    重要性:
  • metrics.sample.window.ms

    计算指标样本的时间窗口。

    类型:长整型
    默认值:30000 (30 秒)
    取值:[0,...]
    重要性:
  • offset.flush.interval.ms

    尝试提交任务偏移量的时间间隔。

    类型:长整型
    默认值:60000 (1 分钟)
    取值:
    重要性:
  • offset.flush.timeout.ms

    在取消进程并恢复要在将来尝试提交的偏移数据之前,等待刷新记录并将分区偏移数据提交到偏移存储的最大毫秒数。此属性对使用恰好一次支持运行的源连接器没有影响。

    类型:长整型
    默认值:5000(5 秒)
    取值:
    重要性:
  • offset.storage.partitions

    创建 offset 存储 Topic 时使用的分区数

    类型:int
    默认值:25
    取值:正数,或者 -1 以使用代理的默认值
    重要性:
  • offset.storage.replication.factor

    创建偏移存储主题时使用的复制因子

    类型:
    默认值:3
    取值:正数不大于 Kafka 集群中的代理数,或者 -1 以使用代理的默认值
    重要性:
  • plugin.path 插件

    包含插件(连接器、转换器、转换)的以逗号 (,) 分隔的路径列表。该列表应由顶级目录组成,其中包括以下任意组合:
    a) 目录直接包含带有插件及其依赖项
    的 jar b) 带有插件及其依赖项
    的 uber-jars c) 目录直接包含插件类及其依赖项
    的包目录结构 注意:将遵循符号链接来发现依赖项或插件。
    示例: plugin.path=/usr/local/share/java,/usr/local/share/kafka/plugins,/opt/connectors
    不要在此属性中使用配置提供程序变量,因为在初始化配置提供程序之前,worker 的扫描程序会使用原始路径并用于替换变量。

    类型:列表
    默认值:
    取值:
    重要性:
  • reconnect.backoff.max.ms

    重新连接到多次连接失败的代理时等待的最长时间(以毫秒为单位)。如果提供,则对于每个连续连接失败,每个主机的回退将呈指数级增加,直到达到此最大值。计算出退避增幅后,增加 20% 的随机抖动,避免连接风暴。

    类型:长整型
    默认值:1000(1 秒)
    取值:[0,...]
    重要性:
  • reconnect.backoff.ms

    尝试重新连接到给定主机之前要等待的基本时间。这避免了在紧密循环中重复连接到主机。此回退适用于客户端与 broker 的所有连接尝试。

    类型:长整型
    默认值:50
    取值:[0,...]
    重要性:
  • 响应.http.headers.config

    REST API HTTP 响应标头的规则

    类型:字符串
    默认值:""
    取值:逗号分隔的标题规则,其中每个标题规则的格式为 '[action] [header name]:[header value]“,如果标题规则的任何部分包含逗号,则可以选择用双引号括起来
    重要性:
  • rest.advertised.host.name

    如果设置了此选项,则这是将提供给其他 worker 进行连接的主机名。

    类型:字符串
    默认值:
    取值:
    重要性:
  • rest.advertised.listener 的

    设置将提供给其他 worker 使用的通告侦听器(HTTP 或 HTTPS)。

    类型:字符串
    默认值:
    取值:
    重要性:
  • rest.advertised.port

    如果设置了此选项,则这是将分配给其他 worker 进行连接的端口。

    类型:int
    默认值:
    取值:
    重要性:
  • rest.extension.classes

    的逗号分隔名称ConnectRestExtension类,按指定的顺序加载和调用。实现接口ConnectRestExtension允许您将用户定义的资源(如筛选器)注入 Connect 的 REST API。通常用于添加自定义功能,如日志记录、安全性等。

    类型:列表
    默认值:""
    取值:
    重要性:
  • retry.backoff.ms

    在尝试重试对给定主题分区的失败请求之前等待的时间。这避免了在某些故障情况下以紧密循环的形式重复发送请求。

    类型:长整型
    默认值:100
    取值:[0,...]
    重要性:
  • sasl.kerberos.kinit.cmd

    Kerberos kinit 命令路径。

    类型:字符串
    默认值:/usr/bin/kinit 中
    取值:
    重要性:
  • sasl.kerberos.min.time.before.relogin

    刷新尝试之间的登录线程休眠时间。

    类型:长整型
    默认值:60000
    取值:
    重要性:
  • sasl.kerberos.ticket.renew.jitter

    添加到续订时间的随机抖动的百分比。

    类型:双整型
    默认值:0.05
    取值:
    重要性:
  • sasl.kerberos.ticket.renew.window.factor

    登录线程将休眠,直到达到从上次刷新到票证到期的指定窗口时间因子,此时它将尝试续订票证。

    类型:双整型
    默认值:0.8
    取值:
    重要性:
  • sasl.login.connect.timeout.ms

    外部身份验证提供程序连接超时的(可选)值(以毫秒为单位)。当前仅适用于 OAUTHBEARER。

    类型:int
    默认值:
    取值:
    重要性:
  • sasl.login.read.timeout.ms

    外部身份验证提供程序读取超时的(可选)值(以毫秒为单位)。当前仅适用于 OAUTHBEARER。

    类型:int
    默认值:
    取值:
    重要性:
  • sasl.login.refresh.buffer.seconds

    刷新凭证时要保持的凭证过期前要保持的缓冲时间(以秒为单位)。如果刷新时间比缓冲秒数更接近过期时间,则刷新将上移以保持尽可能多的缓冲时间。合法值介于 0 和 3600 之间(1 小时);如果未指定值,则使用默认值 300(5 分钟)。如果此值和 sasl.login.refresh.min.period.seconds 的总和超过凭证的剩余生命周期,则它们都将被忽略。当前仅适用于 OAUTHBEARER。

    类型:
    默认值:300
    取值:[0,...,3600]
    重要性:
  • sasl.login.refresh.min.period.seconds

    登录刷新线程在刷新凭证之前等待的所需最短时间(以秒为单位)。合法值介于 0 到 900 之间(15 分钟);如果未指定值,则使用默认值 60(1 分钟)。如果此值和 sasl.login.refresh.buffer.seconds 的总和超过凭证的剩余生命周期,则它们都将被忽略。当前仅适用于 OAUTHBEARER。

    类型:
    默认值:60
    取值:[0,...,900]
    重要性:
  • sasl.login.refresh.window.factor

    登录刷新线程将休眠,直到达到相对于凭证生命周期的指定窗口因子,此时它将尝试刷新凭证。合法值介于 0.5 (50%) 和 1.0 (100%) 之间(含);如果未指定值,则使用默认值 0.8 (80%)。当前仅适用于 OAUTHBEARER。

    类型:双整型
    默认值:0.8
    取值:[0.5,...,1.0]
    重要性:
  • sasl.login.refresh.window.jitter

    相对于凭证生命周期的最大随机抖动量,该抖动量添加到登录刷新线程的休眠时间中。合法值介于 0 和 0.25 (25%) 之间(含 0 和 0.25 年);如果未指定值,则使用默认值 0.05 (5%)。当前仅适用于 OAUTHBEARER。

    类型:双整型
    默认值:0.05
    取值:[0.0,...,0.25]
    重要性:
  • sasl.login.retry.backoff.max.ms

    (可选)值(以毫秒为单位),表示尝试登录外部身份验证提供程序之间的最大等待时间。Login 使用指数退避算法,初始等待基于 sasl.login.retry.backoff.ms 设置,并且将在两次尝试之间将等待长度增加一倍,直到达到 sasl.login.retry.backoff.max.ms 设置指定的最大等待长度。当前仅适用于 OAUTHBEARER。

    类型:长整型
    默认值:10000 (10 秒)
    取值:
    重要性:
  • sasl.login.retry.backoff.ms

    尝试登录外部身份验证提供程序之间的初始等待时间的(可选)值(以毫秒为单位)。Login 使用指数退避算法,初始等待基于 sasl.login.retry.backoff.ms 设置,并且将在两次尝试之间将等待长度增加一倍,直到达到 sasl.login.retry.backoff.max.ms 设置指定的最大等待长度。当前仅适用于 OAUTHBEARER。

    类型:长整型
    默认值:100
    取值:
    重要性:
  • sasl.oauthbearer.clock.skew.seconds

    (可选)值(以秒为单位),以允许 OAuth/OIDC 身份提供者和代理的时间之间存在差异。

    类型:int
    默认值:30
    取值:
    重要性:
  • sasl.oauthbearer.expected.audience

    代理使用的(可选)逗号分隔设置,用于验证 JWT 是否是针对预期受众之一颁发的。将检查 JWT 的标准 OAuth “aud” 声明,如果设置了此值,代理将匹配 JWT 的 “aud” 声明中的值,以查看是否存在完全匹配。如果没有匹配项,代理将拒绝 JWT,并且身份验证将失败。

    类型:列表
    默认值:
    取值:
    重要性:
  • sasl.oauthbearer.expected.issuer

    代理用于验证 JWT 是否由预期颁发者创建的(可选)设置。将检查 JWT 中的标准 OAuth “iss” 声明,如果设置了此值,代理会将其与 JWT 的 “iss” 声明中的内容完全匹配。如果没有匹配项,代理将拒绝 JWT,并且身份验证将失败。

    类型:字符串
    默认值:
    取值:
    重要性:
  • sasl.oauthbearer.jwks.endpoint.refresh.ms

    代理在刷新其 JWKS(JSON Web 密钥集)缓存(包含密钥以验证 JWT 签名)之间等待的(可选)值(以毫秒为单位)。

    类型:长整型
    默认值:3600000 (1 小时)
    取值:
    重要性:
  • sasl.oauthbearer.jwks.endpoint.retry.backoff.max.ms

    尝试从外部身份验证提供程序检索 JWKS(JSON Web 密钥集)之间的最大等待时间的(可选)值(以毫秒为单位)。JWKS 检索使用指数退避算法,初始等待基于 sasl.oauthbearer.jwks.endpoint.retry.backoff.ms 设置,并且将两次尝试之间的等待长度增加一倍,直到达到 sasl.oauthbearer.jwks.endpoint.retry.backoff.max.ms 设置指定的最大等待长度。

    类型:长整型
    默认值:10000 (10 秒)
    取值:
    重要性:
  • sasl.oauthbearer.jwks.endpoint.retry.backoff.ms

    来自外部身份验证提供程序的 JWKS(JSON Web 密钥集)检索尝试之间的初始等待的(可选)值(以毫秒为单位)。JWKS 检索使用指数退避算法,初始等待基于 sasl.oauthbearer.jwks.endpoint.retry.backoff.ms 设置,并且将两次尝试之间的等待长度增加一倍,直到达到 sasl.oauthbearer.jwks.endpoint.retry.backoff.max.ms 设置指定的最大等待长度。

    类型:长整型
    默认值:100
    取值:
    重要性:
  • sasl.oauthbearer.scope.claim.name

    范围的 OAuth 声明通常命名为“范围”,但如果 OAuth/OIDC 提供商对该声明使用不同的名称,则此(可选)设置可以提供不同的名称,以用于 JWT 负载声明中包含的范围。

    类型:字符串
    默认值:范围
    取值:
    重要性:
  • sasl.oauthbearer.sub.claim.name

    主题的 OAuth 声明通常命名为“sub”,但如果 OAuth/OIDC 提供商对该声明使用不同的名称,则此(可选)设置可以提供不同的名称,以用于 JWT 负载声明中包含的主题。

    类型:字符串
    默认值:
    取值:
    重要性:
  • scheduled.rebalance.max.delay.ms

    在重新平衡并将其连接器和任务重新分配给组之前,为了等待一个或多个离职工作人员返回而计划的最大延迟。在此期间,离职工人的连接器和任务仍未分配

    类型:int
    默认值:300000 (5 分钟)
    取值:[0,...,2147483647]
    重要性:
  • socket.connection.setup.timeout.max.ms

    客户端等待建立套接字连接的最长时间。对于每个连续的连接失败,连接设置超时将呈指数级增长,直到达到此最大值。为避免连接风暴,将对超时应用随机化因子 0.2,从而产生低于计算值 20% 到高于计算值 20% 的随机范围。

    类型:长整型
    默认值:30000 (30 秒)
    取值:[0,...]
    重要性:
  • socket.connection.setup.timeout.ms

    客户端等待建立套接字连接的时间。如果在超时时间之前未建立连接,则 Client 端将关闭套接字通道。

    类型:长整型
    默认值:10000 (10 秒)
    取值:[0,...]
    重要性:
  • ssl.cipher.suites

    密码套件列表。这是身份验证、加密、MAC 和密钥交换算法的命名组合,用于协商使用 TLS 或 SSL 网络协议的网络连接的安全设置。默认情况下,支持所有可用的密码套件。

    类型:列表
    默认值:
    取值:
    重要性:
  • ssl.client.auth

    配置 kafka 代理以请求客户端身份验证。以下设置是常见的:

    • ssl.client.auth=required如果设置为 required,则需要客户端身份验证。
    • ssl.client.auth=requested这意味着客户端身份验证是可选的。与 required 不同,如果设置了此选项,则客户端可以选择不提供有关自身的身份验证信息
    • ssl.client.auth=none这意味着不需要客户端身份验证。

    类型:字符串
    默认值:没有
    取值:[必需、已请求、无]
    重要性:
  • ssl.endpoint.identification.algorithm

    终端节点识别算法,用于使用服务器证书验证服务器主机名。

    类型:字符串
    默认值:https
    取值:
    重要性:
  • ssl.engine.factory.class

    org.apache.kafka.common.security.auth.SslEngineFactory 类型的类,用于提供 SSLEngine 对象。默认值为 org.apache.kafka.common.security.ssl.DefaultSslEngineFactory

    类型:
    默认值:
    取值:
    重要性:
  • ssl.keymanager.algorithm

    密钥管理器工厂用于 SSL 连接的算法。默认值是为 Java 虚拟机配置的密钥管理器工厂算法。

    类型:字符串
    默认值:SunX509 系列
    取值:
    重要性:
  • ssl.secure.random.implementation

    用于 SSL 加密作的 SecureRandom PRNG 实现。

    类型:字符串
    默认值:
    取值:
    重要性:
  • ssl.trustmanager.algorithm

    信任管理器工厂用于 SSL 连接的算法。默认值是为 Java 虚拟机配置的信任管理器工厂算法。

    类型:字符串
    默认值:PKIX
    取值:
    重要性:
  • status.storage.partitions

    创建 status storage 主题时使用的分区数

    类型:int
    默认值:5
    取值:正数,或者 -1 以使用代理的默认值
    重要性:
  • 状态.storage.replication.factor

    创建状态存储主题时使用的复制因子

    类型:
    默认值:3
    取值:正数不大于 Kafka 集群中的代理数,或者 -1 以使用代理的默认值
    重要性:
  • task.shutdown.graceful.timeout.ms

    等待任务正常关闭的时间。这是总时间,而不是每个任务。所有任务都触发了 shutdown,然后按顺序等待。

    类型:长整型
    默认值:5000(5 秒)
    取值:
    重要性:
  • topic.creation.enable

    当源连接器配置了 'topic.creation.' 属性时,是否允许自动创建源连接器使用的主题。每个任务都将使用管理员客户端创建其主题,并且不会依赖 Kafka 代理自动创建主题。

    类型:布尔
    默认值:
    取值:
    重要性:
  • topic.tracking.allow.reset

    如果设置为 true,则允许用户请求重置每个连接器的活动主题集。

    类型:布尔
    默认值:
    取值:
    重要性:
  • topic.tracking.enable

    启用在运行时跟踪每个连接器的活动主题集。

    类型:布尔
    默认值:
    取值:
    重要性:

3.5.1 源连接器配置

下面是源连接器的配置。
  • 名字

    用于此连接器的全局唯一名称。

    类型:字符串
    默认值:
    取值:没有 ISO 控制字符的非空字符串
    重要性:
  • connector.class

    此连接器的类的名称或别名。必须是 org.apache.kafka.connect.connector.Connector 的子类。如果连接器是 org.apache.kafka.connect.file.FileStreamSinkConnector,则可以指定此全名,也可以使用“FileStreamSink”或“FileStreamSinkConnector”来缩短配置时间

    类型:字符串
    默认值:
    取值:
    重要性:
  • tasks.max

    用于此连接器的最大任务数。

    类型:int
    默认值:1
    取值:[1,...]
    重要性:
  • key.converter

    Converter 类,用于在 Kafka Connect 格式和写入 Kafka 的序列化形式之间进行转换。这控制写入 Kafka 或从 Kafka 读取的消息中键的格式,并且由于这与连接器无关,因此它允许任何连接器使用任何序列化格式。常见格式的示例包括 JSON 和 Avro。

    类型:
    默认值:
    取值:
    重要性:
  • value.converter

    Converter 类,用于在 Kafka Connect 格式和写入 Kafka 的序列化形式之间进行转换。这控制写入 Kafka 或从 Kafka 读取的消息中值的格式,并且由于这与连接器无关,因此它允许任何连接器使用任何序列化格式。常见格式的示例包括 JSON 和 Avro。

    类型:
    默认值:
    取值:
    重要性:
  • header.converter

    HeaderConverter 类,用于在 Kafka Connect 格式和写入 Kafka 的序列化形式之间进行转换。这控制写入 Kafka 或从 Kafka 读取的消息中标头值的格式,并且由于这独立于连接器,因此它允许任何连接器使用任何序列化格式。常见格式的示例包括 JSON 和 Avro。默认情况下,SimpleHeaderConverter 用于将标头值序列化为字符串,并通过推断架构来反序列化它们。

    类型:
    默认值:
    取值:
    重要性:
  • config.action.reload

    当外部配置提供程序中的更改导致连接器的配置属性发生更改时,Connect 应对连接器执行的作。值 'none' 表示 Connect 不执行任何作。值“restart”表示 Connect 应使用更新的配置属性重新启动/重新加载连接器。如果外部配置提供程序指示配置值将在将来过期,则实际上可能会安排在将来重新启动。

    类型:字符串
    默认值:重新启动
    取值:[无,重启]
    重要性:
  • 变换

    要应用于记录的转换的别名。

    类型:列表
    默认值:""
    取值:非 null 字符串,唯一转换别名
    重要性:
  • 谓词

    转换使用的谓词的别名。

    类型:列表
    默认值:""
    取值:非 null 字符串,唯一谓词别名
    重要性:
  • 错误.重试.timeout

    重新尝试失败作的最大持续时间(以毫秒为单位)。默认值为 0,这意味着不会尝试重试。使用 -1 表示无限次重试。

    类型:长整型
    默认值:0
    取值:
    重要性:中等
  • errors.retry.delay.max.ms

    连续重试尝试之间的最大持续时间(以毫秒为单位)。一旦达到此限制,延迟就会增加抖动,以防止出现雷霆万钞的问题。

    类型:长整型
    默认值:60000 (1 分钟)
    取值:
    重要性:中等
  • errors.tolerance 的

    在连接器作期间容忍错误的行为。'none' 是默认值,表示任何错误都将导致连接器任务立即失败;'all' 更改行为以跳过有问题的记录。

    类型:字符串
    默认值:没有
    取值:[无,全部]
    重要性:中等
  • errors.log.enable

    如果为 true,则将每个错误以及失败作和有问题记录的详细信息写入 Connect 应用程序日志。默认情况下,这是 'false',因此仅报告不允许的错误。

    类型:布尔
    默认值:
    取值:
    重要性:中等
  • errors.log.include.messages

    是否在日志中包含导致失败的 Connect 记录。对于 sink 记录,将记录 topic、partition、offset 和 timestamp。对于源记录,将记录键和值(及其架构)、所有标头以及时间戳、Kafka 主题、Kafka 分区、源分区和源偏移量。默认情况下为 'false',这将阻止将记录键、值和标头写入日志文件。

    类型:布尔
    默认值:
    取值:
    重要性:中等
  • topic.creation.groups

    源连接器创建的主题的配置组

    类型:列表
    默认值:""
    取值:非 null 字符串,唯一主题创建组
    重要性:
  • exactly.once.support

    允许的值是 requested、required。如果设置为 “required”,则强制对连接器进行印前检查,以确保它可以通过给定的配置提供恰好一次语义。某些连接器可能能够提供 exactly-once 语义,但不能向 Connect 发出信号表明它们支持此功能;在这种情况下,在创建连接器之前,应仔细查阅连接器的文档,并且此属性的值应设置为“requested”。此外,如果该值设置为“required”,但执行印前检查验证的工作程序没有为源连接器启用精确一次支持,则创建或验证连接器的请求将失败。

    类型:字符串
    默认值:要求
    取值:(不区分大小写)[必填、请求]
    重要性:中等
  • transaction.boundary 交易

    允许的值为:poll、interval、connector。如果设置为 'poll',则将为此连接器中的每个任务提供给 Connect 的每批记录启动并提交新的生产者事务。如果设置为 'connector',则依赖于连接器定义的事务边界;请注意,并非所有连接器都能够定义自己的事务边界,在这种情况下,尝试使用此值实例化连接器将失败。最后,如果设置为 'interval',则仅在用户定义的时间间隔过后提交事务。

    类型:字符串
    默认值:民意调查
    取值:(不区分大小写)[间隔、轮询、连接器]
    重要性:中等
  • transaction.boundary.interval.ms

    如果 'transaction.boundary' 设置为 'interval',则确定连接器任务提交生产者事务的间隔。如果未设置,则默认为 worker 级别的 'offset.flush.interval.ms' 属性的值。如果指定了不同的 transaction.boundary,则它不起作用。

    类型:长整型
    默认值:
    取值:[0,...]
    重要性:
  • offsets.storage.topic

    要用于此连接器的单独偏移主题的名称。如果为空或未指定,则将使用 worker 的 global offsets 主题名称。如果指定了 offsets 主题,则如果此连接器所针对的 Kafka 集群上尚不存在该主题,则将创建 offsets 主题(如果连接器的生产者的 bootstrap.servers 属性已从工作线程的 bootstrap.servers 属性中覆盖,则可能与用于 worker 的全局 offsets 主题的主题不同)。仅适用于分布式模式;在 Standalone 模式下,设置此属性将不起作用。

    类型:字符串
    默认值:
    取值:非空字符串
    重要性:

3.5.2 Sink 连接器配置

下面是 sink 连接器的配置。
  • 名字

    用于此连接器的全局唯一名称。

    类型:字符串
    默认值:
    取值:没有 ISO 控制字符的非空字符串
    重要性:
  • connector.class

    此连接器的类的名称或别名。必须是 org.apache.kafka.connect.connector.Connector 的子类。如果连接器是 org.apache.kafka.connect.file.FileStreamSinkConnector,则可以指定此全名,也可以使用“FileStreamSink”或“FileStreamSinkConnector”来缩短配置时间

    类型:字符串
    默认值:
    取值:
    重要性:
  • tasks.max

    用于此连接器的最大任务数。

    类型:int
    默认值:1
    取值:[1,...]
    重要性:
  • 主题

    要使用的主题列表,以逗号分隔

    类型:列表
    默认值:""
    取值:
    重要性:
  • topics.regex 格式

    正则表达式提供要使用的主题。在后台,正则表达式被编译为java.util.regex.Pattern.只应指定 topics 或 topics.regex 之一。

    类型:字符串
    默认值:""
    取值:有效的正则表达式
    重要性:
  • key.converter

    Converter 类,用于在 Kafka Connect 格式和写入 Kafka 的序列化形式之间进行转换。这控制写入 Kafka 或从 Kafka 读取的消息中键的格式,并且由于这与连接器无关,因此它允许任何连接器使用任何序列化格式。常见格式的示例包括 JSON 和 Avro。

    类型:
    默认值:
    取值:
    重要性:
  • value.converter

    Converter 类,用于在 Kafka Connect 格式和写入 Kafka 的序列化形式之间进行转换。这控制写入 Kafka 或从 Kafka 读取的消息中值的格式,并且由于这与连接器无关,因此它允许任何连接器使用任何序列化格式。常见格式的示例包括 JSON 和 Avro。

    类型:
    默认值:
    取值:
    重要性:
  • header.converter

    HeaderConverter 类,用于在 Kafka Connect 格式和写入 Kafka 的序列化形式之间进行转换。这控制写入 Kafka 或从 Kafka 读取的消息中标头值的格式,并且由于这独立于连接器,因此它允许任何连接器使用任何序列化格式。常见格式的示例包括 JSON 和 Avro。默认情况下,SimpleHeaderConverter 用于将标头值序列化为字符串,并通过推断架构来反序列化它们。

    类型:
    默认值:
    取值:
    重要性:
  • config.action.reload

    当外部配置提供程序中的更改导致连接器的配置属性发生更改时,Connect 应对连接器执行的作。值 'none' 表示 Connect 不执行任何作。值“restart”表示 Connect 应使用更新的配置属性重新启动/重新加载连接器。如果外部配置提供程序指示配置值将在将来过期,则实际上可能会安排在将来重新启动。

    类型:字符串
    默认值:重新启动
    取值:[无,重启]
    重要性:
  • 变换

    要应用于记录的转换的别名。

    类型:列表
    默认值:""
    取值:非 null 字符串,唯一转换别名
    重要性:
  • 谓词

    转换使用的谓词的别名。

    类型:列表
    默认值:""
    取值:非 null 字符串,唯一谓词别名
    重要性:
  • 错误.重试.timeout

    重新尝试失败作的最大持续时间(以毫秒为单位)。默认值为 0,这意味着不会尝试重试。使用 -1 表示无限次重试。

    类型:长整型
    默认值:0
    取值:
    重要性:中等
  • errors.retry.delay.max.ms

    连续重试尝试之间的最大持续时间(以毫秒为单位)。一旦达到此限制,延迟就会增加抖动,以防止出现雷霆万钞的问题。

    类型:长整型
    默认值:60000 (1 分钟)
    取值:
    重要性:中等
  • errors.tolerance 的

    在连接器作期间容忍错误的行为。'none' 是默认值,表示任何错误都将导致连接器任务立即失败;'all' 更改行为以跳过有问题的记录。

    类型:字符串
    默认值:没有
    取值:[无,全部]
    重要性:中等
  • errors.log.enable

    如果为 true,则将每个错误以及失败作和有问题记录的详细信息写入 Connect 应用程序日志。默认情况下,这是 'false',因此仅报告不允许的错误。

    类型:布尔
    默认值:
    取值:
    重要性:中等
  • errors.log.include.messages

    是否在日志中包含导致失败的 Connect 记录。对于 sink 记录,将记录 topic、partition、offset 和 timestamp。对于源记录,将记录键和值(及其架构)、所有标头以及时间戳、Kafka 主题、Kafka 分区、源分区和源偏移量。默认情况下为 'false',这将阻止将记录键、值和标头写入日志文件。

    类型:布尔
    默认值:
    取值:
    重要性:中等
  • errors.deadletterqueue.topic.name

    要用作死信队列 (DLQ) 的主题名称,这些消息在由此接收器连接器或其转换或转换器处理时导致错误。默认情况下,主题名称为空,这意味着 DLQ 中不会记录任何消息。

    类型:字符串
    默认值:""
    取值:
    重要性:中等
  • errors.deadletterqueue.topic.replication.factor

    复制因子,用于创建死信队列主题(如果尚不存在)。

    类型:
    默认值:3
    取值:
    重要性:中等
  • errors.deadletterqueue.context.headers.enable

    如果为 true,则将包含错误上下文的标头添加到写入死信队列的消息中。为避免与原始记录中的标头冲突,所有错误上下文 Header 键、所有错误上下文 Header 键都将以__connect.errors.

    类型:布尔
    默认值:
    取值:
    重要性:中等

3.6 Kafka Streams 配置

以下是 Kafka Streams 客户端库的配置。
  • application.id

    流处理应用程序的标识符。在 Kafka 集群中必须是唯一的。它用作 1) 默认 client-id 前缀,2) 用于成员资格管理的组 ID,3) changelog 主题前缀。

    类型:字符串
    默认值:
    取值:
    重要性:
  • 引导程序.服务器

    用于建立与 Kafka 集群的初始连接的主机/端口对列表。客户端将使用所有服务器,而不管此处指定了哪些服务器进行引导 — 此列表仅影响用于发现完整服务器集的初始主机。此列表应采用以下格式host1:port1,host2:port2,....由于这些服务器仅用于初始连接以发现完整的集群成员身份(可能会动态更改),因此此列表不需要包含完整的服务器集(尽管您可能需要多个服务器,以防服务器关闭)。

    类型:列表
    默认值:
    取值:
    重要性:
  • num.standby.replicas

    每个任务的备用副本数。

    类型:int
    默认值:0
    取值:
    重要性:
  • state.dir 中

    状态存储的目录位置。对于共享同一底层文件系统的每个 streams 实例,此路径必须是唯一的。

    类型:字符串
    默认值:/var/folders/qq/2qmvd8cd11x3fcd6wbgpn9pw0000gn/T//kafka-streams
    取值:
    重要性:
  • 可接受.recovery.lag

    客户端被视为已捕获到足以接收活动任务分配的可接受最大滞后(要赶上的偏移量)。分配后,它仍将在处理之前恢复更改日志的其余部分。为避免在再平衡期间暂停处理,此配置应对应于给定工作负载的恢复时间远低于一分钟。必须至少为 0。

    类型:长整型
    默认值:10000
    取值:[0,...]
    重要性:中等
  • cache.max.bytes.buffering

    用于跨所有线程缓冲的最大内存字节数

    类型:长整型
    默认值:10485760
    取值:[0,...]
    重要性:中等
  • client.id

    用于内部使用者、生产者和恢复使用者的客户端 ID 的 ID 前缀字符串,模式为<client.id>-StreamThread-<threadSequenceNumber$gt;-<consumer|producer|restore-consumer>.

    类型:字符串
    默认值:""
    取值:
    重要性:中等
  • default.deserialization.exception.handler

    实现org.apache.kafka.streams.errors.DeserializationExceptionHandler接口。

    类型:
    默认值:org.apache.kafka.streams.errors.LogAndFailExceptionHandler
    取值:
    重要性:中等
  • default.key.serde

    实现org.apache.kafka.common.serialization.Serde接口。请注意,当使用窗口化 serde 类时,需要设置实现org.apache.kafka.common.serialization.Serde通过 'default.windowed.key.serde.inner' 或 'default.windowed.value.serde.inner' 的接口

    类型:
    默认值:
    取值:
    重要性:中等
  • default.list.key.serde.inner

    实现org.apache.kafka.common.serialization.Serde接口。当且仅当default.key.serdeconfiguration 设置为org.apache.kafka.common.serialization.Serdes.ListSerde

    类型:
    默认值:
    取值:
    重要性:中等
  • default.list.key.serde.type

    default 类,用于实现java.util.List接口。当且仅当default.key.serdeconfiguration 设置为org.apache.kafka.common.serialization.Serdes.ListSerde注意,当使用 list serde 类时,需要设置实现org.apache.kafka.common.serialization.Serde通过 'default.list.key.serde.inner' 的接口

    类型:
    默认值:
    取值:
    重要性:中等
  • 默认列表.值.serde.inner

    list serde 的默认内部类,用于实现org.apache.kafka.common.serialization.Serde接口。当且仅当default.value.serdeconfiguration 设置为org.apache.kafka.common.serialization.Serdes.ListSerde

    类型:
    默认值:
    取值:
    重要性:中等
  • default.list.value.serde.type

    default 类,用于实现java.util.List接口。当且仅当default.value.serdeconfiguration 设置为org.apache.kafka.common.serialization.Serdes.ListSerde注意,当使用 list serde 类时,需要设置实现org.apache.kafka.common.serialization.Serde通过 'default.list.value.serde.inner' 的接口

    类型:
    默认值:
    取值:
    重要性:中等
  • default.production.exception.handler

    实现org.apache.kafka.streams.errors.ProductionExceptionHandler接口。

    类型:
    默认值:org.apache.kafka.streams.errors.DefaultProductionExceptionHandler
    取值:
    重要性:中等
  • default.timestamp.extract或

    默认时间戳提取器类,该类实现org.apache.kafka.streams.processor.TimestampExtractor接口。

    类型:
    默认值:org.apache.kafka.streams.processor.FailOnInvalidTimestamp
    取值:
    重要性:中等
  • default.value.serde

    实现org.apache.kafka.common.serialization.Serde接口。请注意,当使用窗口化 serde 类时,需要设置实现org.apache.kafka.common.serialization.Serde通过 'default.windowed.key.serde.inner' 或 'default.windowed.value.serde.inner' 的接口

    类型:
    默认值:
    取值:
    重要性:中等
  • max.task.idle.ms

    此配置控制联接和合并是否会产生无序结果。config 值是流任务在完全赶上某些(但不是全部)输入分区以等待创建器发送其他记录并避免跨多个输入流可能出现的无序记录处理时,流任务将保持空闲状态的最长时间(以毫秒为单位)。默认值 (零) 不会等待创建者发送更多记录,但会等待获取代理上已存在的数据。此默认值意味着对于代理上已存在的记录,Streams 将按时间戳顺序处理它们。设置为 -1 可完全禁用空闲并处理任何本地可用的数据,即使这样做可能会产生无序处理。

    类型:长整型
    默认值:0
    取值:
    重要性:中等
  • max.warmup.replicas

    可以一次分配的预热副本(超出配置的 num.standbys 的额外备用副本)的最大数量,以便在任务在已重新分配到的另一个实例上预热时保持任务在一个实例上可用。用于限制可用于高可用性的额外代理流量和集群状态的数量。必须至少为 1。请注意,一个预热副本对应于一个 Stream Task。此外,请注意,每个预热副本只能在再平衡期间提升为活动任务(通常在所谓的探测再平衡期间,以 'probing.rebalance.interval.ms' 配置指定的频率发生)。这意味着活动任务从一个 Kafka Streams 实例迁移到另一个实例的最大速率可以由 ('max.warmup.replicas' / 'probing.rebalance.interval.ms') 确定。

    类型:int
    默认值:2
    取值:[1,...]
    重要性:中等
  • num.stream.threads

    要执行流处理的线程数。

    类型:int
    默认值:1
    取值:
    重要性:中等
  • processing.guarantee

    应使用的处理保证。可能的值为at_least_once(默认)和exactly_once_v2(需要 Brokers 版本 2.5 或更高版本)。已弃用的选项包括exactly_once(需要代理版本 0.11.0 或更高版本)和exactly_once_beta(需要 Brokers 版本 2.5 或更高版本)。请注意,默认情况下,恰好一次处理需要至少三个代理的集群,这是 production 的推荐设置;对于开发,您可以通过调整 broker 设置来更改此设置transaction.state.log.replication.factortransaction.state.log.min.isr.

    类型:字符串
    默认值:at_least_once
    取值:[at_least_once、exactly_once、exactly_once_beta、exactly_once_v2]
    重要性:中等
  • rack.aware.assignment.tags

    用于在 Kafka Streams 实例之间分配备用副本的客户端标签键列表。配置后,Kafka Streams 将尽最大努力在每个客户端标签维度上分配备用任务。

    类型:列表
    默认值:""
    取值:最多包含 5 个元素的列表
    重要性:中等
  • replication.factor

    由流处理应用程序创建的更改日志主题和重新分区主题的复制因子。默认的-1(含义:使用 Broker 默认复制因子)需要 Broker 版本 2.4 或更高版本

    类型:int
    默认值:-1
    取值:
    重要性:中等
  • 安全协议

    用于与 broker 通信的协议。有效值为:PLAINTEXT、SSL、SASL_PLAINTEXT、SASL_SSL。

    类型:字符串
    默认值:明文
    取值:(不区分大小写)[SASL_SSL、明文、SSL SASL_PLAINTEXT]
    重要性:中等
  • statestore.cache.max.bytes

    用于所有线程中的状态存储缓存的最大内存字节数

    类型:长整型
    默认值:10485760 (10 MB)
    取值:[0,...]
    重要性:中等
  • task.timeout.ms

    任务可能因内部错误而停止并重试直到引发错误的最长时间(以毫秒为单位)。如果超时为 0ms,则任务将针对第一个内部错误引发错误。对于任何大于 0 毫秒的超时,任务将在引发错误之前至少重试一次。

    类型:长整型
    默认值:300000 (5 分钟)
    取值:[0,...]
    重要性:中等
  • topology.optimization (拓扑优化)

    一个配置,告诉 Kafka Streams 是否应该优化拓扑以及要应用哪些优化。可接受的值为:“+NO_OPTIMIZATION+”、“+OPTIMIZE+”或以逗号分隔的特定优化列表:(“+REUSE_KTABLE_SOURCE_TOPICS+”、“+MERGE_REPARTITION_TOPICS+” + “SINGLE_STORE_SELF_JOIN+”)”。NO_OPTIMIZATION”。

    类型:字符串
    默认值:没有
    取值:[全部,无,reuse.ktable.source.topics,merge.repartition.topics,single.store.self.join]
    重要性:中等
  • 应用程序 .server

    一个 host:port 对,指向用户定义的终端节点,该终端节点可用于此 KafkaStreams 实例上的状态存储发现和交互式查询。

    类型:字符串
    默认值:""
    取值:
    重要性:
  • auto.include.jmx.reporter

    荒废的。是否自动包含 JmxReporter,即使它未在metric.reporters.此配置将在 Kafka 4.0 中删除,用户应包含org.apache.kafka.common.metrics.JmxReportermetric.reporters以启用 JmxReporter。

    类型:布尔
    默认值:
    取值:
    重要性:
  • buffered.records.per.partition

    每个分区缓冲区的最大记录数。

    类型:int
    默认值:1000
    取值:
    重要性:
  • 内置 in.metrics.version

    要使用的内置指标的版本。

    类型:字符串
    默认值:最近的
    取值:[最新]
    重要性:
  • commit.interval.ms

    提交处理进度的频率(以毫秒为单位)。对于 at-least-once 处理,committing 表示保存处理器的位置(即偏移量)。对于 exactly-once 处理,这意味着提交事务,其中包括保存位置并使输出主题中提交的数据对隔离级别为 read_committed 的使用者可见。(请注意,如果processing.guarantee设置为exactly_once_v2,exactly_once,默认值为100,否则默认值为30000.

    类型:长整型
    默认值:30000 (30 秒)
    取值:[0,...]
    重要性:
  • connections.max.idle.ms

    在此配置指定的毫秒数后关闭空闲连接。

    类型:长整型
    默认值:540000 (9 分钟)
    取值:
    重要性:
  • default.client.supplier

    客户端供应商类实现org.apache.kafka.streams.KafkaClientSupplier接口。

    类型:
    默认值:org.apache.kafka.streams.processor.internals.DefaultKafkaClientSupplier
    取值:
    重要性:
  • default.dsl.store

    DSL 运算符使用的默认状态存储类型。

    类型:字符串
    默认值:rocksDB
    取值:[rocksDB,in_memory]
    重要性:
  • metadata.max.age.ms

    以毫秒为单位的时间段,在此之后,即使我们没有看到任何分区领导更改以主动发现任何新的代理或分区,我们也会强制刷新元数据。

    类型:长整型
    默认值:300000 (5 分钟)
    取值:[0,...]
    重要性:
  • metric.reporters

    要用作指标报告器的类列表。实施org.apache.kafka.common.metrics.MetricsReporterinterface 允许插入类,这些类将在创建新指标时收到通知。JmxReporter 始终包含在内以注册 JMX 统计信息。

    类型:列表
    默认值:""
    取值:
    重要性:
  • metrics.num.samples

    为计算指标而维护的样本数。

    类型:int
    默认值:2
    取值:[1,...]
    重要性:
  • metrics.recording.level

    指标的最高记录级别。

    类型:字符串
    默认值:信息
    取值:[信息、调试、跟踪]
    重要性:
  • metrics.sample.window.ms

    计算指标样本的时间窗口。

    类型:长整型
    默认值:30000 (30 秒)
    取值:[0,...]
    重要性:
  • poll.ms

    块等待输入的时间(以毫秒为单位)。

    类型:长整型
    默认值:100
    取值:
    重要性:
  • probing.rebalance.interval.ms

    在触发再平衡以探测已完成预热并准备变为活动状态的预热副本之前等待的最长时间(以毫秒为单位)。探测再平衡将继续触发,直到分配平衡为止。必须至少为 1 分钟。

    类型:长整型
    默认值:600000 (10 分钟)
    取值:[60000,...]
    重要性:
  • receive.buffer.bytes

    读取数据时使用的 TCP 接收缓冲区 (SO_RCVBUF) 的大小。如果值为 -1,则将使用 OS 默认值。

    类型:int
    默认值:32768 (32 千字节)
    取值:[-1,...]
    重要性:
  • reconnect.backoff.max.ms

    重新连接到多次连接失败的代理时等待的最长时间(以毫秒为单位)。如果提供,则对于每个连续连接失败,每个主机的回退将呈指数级增加,直到达到此最大值。计算出退避增幅后,增加 20% 的随机抖动,避免连接风暴。

    类型:长整型
    默认值:1000(1 秒)
    取值:[0,...]
    重要性:
  • reconnect.backoff.ms

    尝试重新连接到给定主机之前要等待的基本时间。这避免了在紧密循环中重复连接到主机。此回退适用于客户端与 broker 的所有连接尝试。

    类型:长整型
    默认值:50
    取值:[0,...]
    重要性:
  • repartition.purge.interval.ms

    从重新分区主题中删除完全消耗的记录的频率(以毫秒为单位)。自上次清除以来,至少在此值之后将进行清除,但可能会延迟到以后。(请注意,与commit.interval.ms,则此值的默认值保持不变,当processing.guarantee设置为exactly_once_v2).

    类型:长整型
    默认值:30000 (30 秒)
    取值:[0,...]
    重要性:
  • request.timeout.ms

    该配置控制客户端等待请求响应的最长时间。如果在超时之前未收到响应,则客户端将在必要时重新发送请求,如果重试次数已用尽,则请求失败。

    类型:int
    默认值:40000(40 秒)
    取值:[0,...]
    重要性:
  • 重试

    将值设置为大于零将导致客户端重新发送任何失败并出现潜在暂时性错误的请求。建议将该值设置为 0 或 'MAX_VALUE' 并使用相应的超时参数来控制客户端应重试请求的时间。

    类型:int
    默认值:0
    取值:[0,...,2147483647]
    重要性:
  • retry.backoff.ms

    在尝试重试对给定主题分区的失败请求之前等待的时间。这避免了在某些故障情况下以紧密循环的形式重复发送请求。

    类型:长整型
    默认值:100
    取值:[0,...]
    重要性:
  • rocksdb.config.setter

    一个 Rocks DB 配置 setter 类或类名,用于实现org.apache.kafka.streams.state.RocksDBConfigSetter接口

    类型:
    默认值:
    取值:
    重要性:
  • 发送.buffer.bytes

    发送数据时使用的 TCP 发送缓冲区的大小 (SO_SNDBUF)。如果值为 -1,则将使用 OS 默认值。

    类型:int
    默认值:131072 (128 KB)
    取值:[-1,...]
    重要性:
  • state.cleanup.delay.ms

    迁移分区时,删除状态前等待的时间(以毫秒为单位)。仅限至少 10 月未修改的状态目录state.cleanup.delay.ms将被删除

    类型:长整型
    默认值:600000 (10 分钟)
    取值:
    重要性:
  • upgrade.from

    允许以向后兼容的方式进行升级。从 [0.10.0, 1.1] 升级到 2.0+ 或从 [2.0, 2.3] 升级到 2.4+ 时,需要这样做。从 3.3 升级到较新版本时,不需要指定此配置。默认值为 'null'。接受的值为“0.10.0”、“0.10.1”、“0.10.2”、“0.11.0”、“1.0”、“1.1”、“2.0”、“2.1”、“2.2”、“2.3”、“2.4”、“2.5”、“2.6”、“2.7”、“2.8”、“3.0”、“3.1”、“3.2”、“3.3”、“3.4”(用于从相应的旧版本升级)。

    类型:字符串
    默认值:
    取值:[空, 0.10.0, 0.10.1, 0.10.2, 0.11.0, 1.0, 1.1, 2.0, 2.1, 2.2, 2.3, 2.4, 2.5, 2.6, 2.7, 2.8, 3.0, 3.1, 3.2, 3.3, 3.4]
    重要性:
  • window.size.ms

    设置 deserializer 的窗口大小,以便计算窗口结束时间。

    类型:长整型
    默认值:
    取值:
    重要性:
  • windowed.inner.class.serde

    窗口记录的内部类的默认序列化器/反序列化器。必须实现org.apache.kafka.common.serialization.Serde接口。请注意,在 KafkaStreams 应用程序中设置此配置会导致错误,因为它只能从 Plain consumer 客户端使用。

    类型:字符串
    默认值:
    取值:
    重要性:
  • windowstore.changelog.additional.retention.ms

    添加到 Windows maintainMs 以确保数据不会过早地从日志中删除。允许 clock drift。默认值为 1 天

    类型:长整型
    默认值:86400000 (1 天)
    取值:
    重要性:

3.7 管理员配置

以下是 Kafka Admin 客户端库的配置。
  • 引导程序.服务器

    用于建立与 Kafka 集群的初始连接的主机/端口对列表。客户端将使用所有服务器,而不管此处指定了哪些服务器进行引导 — 此列表仅影响用于发现完整服务器集的初始主机。此列表应采用以下格式host1:port1,host2:port2,....由于这些服务器仅用于初始连接以发现完整的集群成员身份(可能会动态更改),因此此列表不需要包含完整的服务器集(尽管您可能需要多个服务器,以防服务器关闭)。

    类型:列表
    默认值:
    取值:
    重要性:
  • ssl.key.password

    密钥存储文件中私钥的密码或 'ssl.keystore.key' 中指定的 PEM 密钥。

    类型:密码
    默认值:
    取值:
    重要性:
  • ssl.keystore.certificate.chain

    由 'ssl.keystore.type' 指定的格式的证书链。默认 SSL 引擎工厂仅支持带有 X.509 证书列表的 PEM 格式

    类型:密码
    默认值:
    取值:
    重要性:
  • ssl.keystore.key

    由 'ssl.keystore.type' 指定的格式的私钥。默认 SSL 引擎工厂仅支持带有 PKCS#8 密钥的 PEM 格式。如果密钥已加密,则必须使用 'ssl.key.password' 指定密钥密码

    类型:密码
    默认值:
    取值:
    重要性:
  • ssl.keystore.location

    密钥存储文件的位置。这对于客户端是可选的,可用于客户端的双向身份验证。

    类型:字符串
    默认值:
    取值:
    重要性:
  • ssl.keystore.password

    密钥存储文件的存储密码。这对于客户端来说是可选的,只有在配置了 'ssl.keystore.location' 时才需要。PEM 格式不支持密钥存储密码。

    类型:密码
    默认值:
    取值:
    重要性:
  • ssl.truststore.certificates 证书

    由 'ssl.truststore.type' 指定格式的受信任证书。默认 SSL 引擎工厂仅支持具有 X.509 证书的 PEM 格式。

    类型:密码
    默认值:
    取值:
    重要性:
  • ssl.truststore.location

    信任存储文件的位置。

    类型:字符串
    默认值:
    取值:
    重要性:
  • ssl.truststore.password

    信任存储文件的密码。如果未设置密码,则仍将使用配置的信任存储文件,但会禁用完整性检查。PEM 格式不支持信任存储密码。

    类型:密码
    默认值:
    取值:
    重要性:
  • 客户端.dns.lookup

    控制客户端如何使用 DNS 查找。如果设置为use_all_dns_ips,依次连接到每个返回的 IP 地址,直到建立成功连接。断开连接后,将使用下一个 IP。一旦所有 IP 都被使用了一次,客户端就会再次从主机名解析 IP(但是,JVM 和 OS 缓存 DNS 名称查找)。如果设置为resolve_canonical_bootstrap_servers_only中,将每个引导地址解析为规范名称列表。在 bootstrap 阶段之后,其行为与use_all_dns_ips.

    类型:字符串
    默认值:use_all_dns_ips
    取值:[use_all_dns_ips、resolve_canonical_bootstrap_servers_only]
    重要性:中等
  • client.id

    发出请求时传递给服务器的 id 字符串。这样做的目的是通过允许在服务器端请求日志记录中包含逻辑应用程序名称来跟踪 ip/port 之外的请求来源。

    类型:字符串
    默认值:""
    取值:
    重要性:中等
  • connections.max.idle.ms

    在此配置指定的毫秒数后关闭空闲连接。

    类型:长整型
    默认值:300000 (5 分钟)
    取值:
    重要性:中等
  • default.api.timeout.ms

    指定客户端 API 的超时 (以毫秒为单位)。此配置用作未指定timeout参数。

    类型:int
    默认值:60000 (1 分钟)
    取值:[0,...]
    重要性:中等
  • receive.buffer.bytes

    读取数据时使用的 TCP 接收缓冲区 (SO_RCVBUF) 的大小。如果值为 -1,则将使用 OS 默认值。

    类型:int
    默认值:65536 (64 千字节)
    取值:[-1,...]
    重要性:中等
  • request.timeout.ms

    该配置控制客户端等待请求响应的最长时间。如果在超时之前未收到响应,则客户端将在必要时重新发送请求,如果重试次数已用尽,则请求失败。

    类型:int
    默认值:30000 (30 秒)
    取值:[0,...]
    重要性:中等
  • sasl.client.callback.handler.class

    实现 AuthenticateCallbackHandler 接口的 SASL 客户端回调处理程序类的完全限定名称。

    类型:
    默认值:
    取值:
    重要性:中等
  • sasl.jaas.config

    SASL 连接的 JAAS 登录上下文参数,采用 JAAS 配置文件使用的格式。此处描述了 JAAS 配置文件格式。该值的格式为:loginModuleClass controlFlag (optionName=optionValue)*;.对于代理,配置必须以小写的侦听器前缀和 SASL 机制名称为前缀。例如,listener.name.sasl_ssl.scram-sha-256.sasl.jaas.config=com.example.ScramLoginModule required;

    类型:密码
    默认值:
    取值:
    重要性:中等
  • sasl.kerberos.service.name

    Kafka 运行的 Kerberos 主体名称。这可以在 Kafka 的 JAAS 配置或 Kafka 的配置中定义。

    类型:字符串
    默认值:
    取值:
    重要性:中等
  • sasl.login.callback.handler.class

    实现 AuthenticateCallbackHandler 接口的 SASL 登录回调处理程序类的完全限定名称。对于 broker,登录回调处理程序 config 必须以侦听器前缀和小写的 SASL 机制名称为前缀。例如,listener.name.sasl_ssl.scram-sha-256.sasl.login.callback.handler.class=com.example.CustomScramLoginCallbackHandler

    类型:
    默认值:
    取值:
    重要性:中等
  • sasl.login.class

    实现 Login 接口的类的完全限定名称。对于 broker,登录配置必须以 listener prefix 和小写的 SASL 机制名称为前缀。例如,listener.name.sasl_ssl.scram-sha-256.sasl.login.class=com.example.CustomScramLogin

    类型:
    默认值:
    取值:
    重要性:中等
  • sasl.mechanism

    用于客户端连接的 SASL 机制。这可以是安全提供程序可用的任何机制。GSSAPI 是默认机制。

    类型:字符串
    默认值:GSSAPI
    取值:
    重要性:中等
  • sasl.oauthbearer.jwks.endpoint.url

    OAuth/OIDC 提供者 URL,可从中检索提供者的 JWKS(JSON Web 密钥集)。URL 可以基于 HTTP(S) 或基于文件。如果 URL 基于 HTTP(S),则在代理启动时,将通过配置的 URL 从 OAuth/OIDC 提供程序检索 JWKS 数据。所有当时的密钥都将缓存在 broker 上,用于传入请求。如果收到对 JWT 的身份验证请求,该请求包含尚未在缓存中的“kid”标头声明值,则将按需再次查询 JWKS 终端节点。但是,代理每 sasl.oauthbearer.jwks.endpoint.refresh.ms 毫秒轮询一次 URL,以便在收到包含任何 URL 的 JWT 请求之前使用任何即将到来的密钥刷新缓存。如果 URL 是基于文件的,则代理将在启动时从配置的位置加载 JWKS 文件。如果 JWT 包含的 “kid” 标头值不在 JWKS 文件中,则代理将拒绝 JWT,并且身份验证将失败。

    类型:字符串
    默认值:
    取值:
    重要性:中等
  • sasl.oauthbearer.token.endpoint.url

    OAuth/OIDC 身份提供商的 URL。如果 URL 基于 HTTP(S),则它是颁发者的令牌端点 URL,将根据 sasl.jaas.config 中的配置向其发出登录请求。如果 URL 是基于文件的,则它会指定一个文件,其中包含由 OAuth/OIDC 身份提供者颁发的用于授权的访问令牌(JWT 序列化格式)。

    类型:字符串
    默认值:
    取值:
    重要性:中等
  • 安全协议

    用于与 broker 通信的协议。有效值为:PLAINTEXT、SSL、SASL_PLAINTEXT、SASL_SSL。

    类型:字符串
    默认值:明文
    取值:(不区分大小写)[SASL_SSL、明文、SSL SASL_PLAINTEXT]
    重要性:中等
  • 发送.buffer.bytes

    发送数据时使用的 TCP 发送缓冲区的大小 (SO_SNDBUF)。如果值为 -1,则将使用 OS 默认值。

    类型:int
    默认值:131072 (128 KB)
    取值:[-1,...]
    重要性:中等
  • socket.connection.setup.timeout.max.ms

    客户端等待建立套接字连接的最长时间。对于每个连续的连接失败,连接设置超时将呈指数级增长,直到达到此最大值。为避免连接风暴,将对超时应用随机化因子 0.2,从而产生低于计算值 20% 到高于计算值 20% 的随机范围。

    类型:长整型
    默认值:30000 (30 秒)
    取值:
    重要性:中等
  • socket.connection.setup.timeout.ms

    客户端等待建立套接字连接的时间。如果在超时时间之前未建立连接,则 Client 端将关闭套接字通道。

    类型:长整型
    默认值:10000 (10 秒)
    取值:
    重要性:中等
  • ssl.enabled.protocols 协议

    为 SSL 连接启用的协议列表。使用 Java 11 或更高版本运行时,默认值为 'TLSv1.2,TLSv1.3',否则为 'TLSv1.2'。使用 Java 11 的默认值,如果客户端和服务器都支持 TLSv1.3,则客户端和服务器将首选 TLSv1.3,否则将回退到 TLSv1.2(假设两者都至少支持 TLSv1.2)。在大多数情况下,此默认值应该很好。另请参阅 'ssl.protocol' 的配置文档。

    类型:列表
    默认值:TLSv1.2、TLSv1.3
    取值:
    重要性:中等
  • ssl.keystore.type

    密钥存储文件的文件格式。这对客户端来说是可选的。默认 'ssl.engine.factory.class' 当前支持的值为 [JKS, PKCS12, PEM]。

    类型:字符串
    默认值:JKS
    取值:
    重要性:中等
  • ssl.protocol 协议

    用于生成 SSLContext 的 SSL 协议。使用 Java 11 或更高版本运行时,默认值为 'TLSv1.3',否则为 'TLSv1.2'。对于大多数用例,此值应该很好。最近的 JVM 中允许的值为 'TLSv1.2' 和 'TLSv1.3'。较旧的 JVM 可能支持“TLS”、“TLSv1.1”、“SSL”、“SSLv2”和“SSLv3”,但由于已知的安全漏洞,不鼓励使用它们。使用此配置的默认值和 'ssl.enabled.protocols',如果服务器不支持 'TLSv1.3',则客户端将降级到 'TLSv1.2'。如果此配置设置为 'TLSv1.2',则客户端将不会使用 'TLSv1.3',即使它是 ssl.enabled.protocols 中的值之一,并且服务器仅支持 'TLSv1.3'。

    类型:字符串
    默认值:TLSv1.3 版本
    取值:
    重要性:中等
  • ssl.provider

    用于 SSL 连接的安全提供程序的名称。默认值是 JVM 的默认安全提供程序。

    类型:字符串
    默认值:
    取值:
    重要性:中等
  • ssl.truststore.type

    信任存储文件的文件格式。默认 'ssl.engine.factory.class' 当前支持的值为 [JKS, PKCS12, PEM]。

    类型:字符串
    默认值:JKS
    取值:
    重要性:中等
  • auto.include.jmx.reporter

    荒废的。是否自动包含 JmxReporter,即使它未在metric.reporters.此配置将在 Kafka 4.0 中删除,用户应包含org.apache.kafka.common.metrics.JmxReportermetric.reporters以启用 JmxReporter。

    类型:布尔
    默认值:
    取值:
    重要性:
  • metadata.max.age.ms

    以毫秒为单位的时间段,在此之后,即使我们没有看到任何分区领导更改以主动发现任何新的代理或分区,我们也会强制刷新元数据。

    类型:长整型
    默认值:300000 (5 分钟)
    取值:[0,...]
    重要性:
  • metric.reporters

    要用作指标报告器的类列表。实施org.apache.kafka.common.metrics.MetricsReporterinterface 允许插入类,这些类将在创建新指标时收到通知。JmxReporter 始终包含在内以注册 JMX 统计信息。

    类型:列表
    默认值:""
    取值:
    重要性:
  • metrics.num.samples

    为计算指标而维护的样本数。

    类型:int
    默认值:2
    取值:[1,...]
    重要性:
  • metrics.recording.level

    指标的最高记录级别。

    类型:字符串
    默认值:信息
    取值:[信息、调试、跟踪]
    重要性:
  • metrics.sample.window.ms

    计算指标样本的时间窗口。

    类型:长整型
    默认值:30000 (30 秒)
    取值:[0,...]
    重要性:
  • reconnect.backoff.max.ms

    重新连接到多次连接失败的代理时等待的最长时间(以毫秒为单位)。如果提供,则对于每个连续连接失败,每个主机的回退将呈指数级增加,直到达到此最大值。计算出退避增幅后,增加 20% 的随机抖动,避免连接风暴。

    类型:长整型
    默认值:1000(1 秒)
    取值:[0,...]
    重要性:
  • reconnect.backoff.ms

    尝试重新连接到给定主机之前要等待的基本时间。这避免了在紧密循环中重复连接到主机。此回退适用于客户端与 broker 的所有连接尝试。

    类型:长整型
    默认值:50
    取值:[0,...]
    重要性:
  • 重试

    将值设置为大于零将导致客户端重新发送任何失败并出现潜在暂时性错误的请求。建议将该值设置为 0 或 'MAX_VALUE' 并使用相应的超时参数来控制客户端应重试请求的时间。

    类型:int
    默认值:2147483647
    取值:[0,...,2147483647]
    重要性:
  • retry.backoff.ms

    在尝试重试失败的请求之前要等待的时间。这避免了在某些故障情况下以紧密循环的形式重复发送请求。

    类型:长整型
    默认值:100
    取值:[0,...]
    重要性:
  • sasl.kerberos.kinit.cmd

    Kerberos kinit 命令路径。

    类型:字符串
    默认值:/usr/bin/kinit 中
    取值:
    重要性:
  • sasl.kerberos.min.time.before.relogin

    刷新尝试之间的登录线程休眠时间。

    类型:长整型
    默认值:60000
    取值:
    重要性:
  • sasl.kerberos.ticket.renew.jitter

    添加到续订时间的随机抖动的百分比。

    类型:双整型
    默认值:0.05
    取值:
    重要性:
  • sasl.kerberos.ticket.renew.window.factor

    登录线程将休眠,直到达到从上次刷新到票证到期的指定窗口时间因子,此时它将尝试续订票证。

    类型:双整型
    默认值:0.8
    取值:
    重要性:
  • sasl.login.connect.timeout.ms

    外部身份验证提供程序连接超时的(可选)值(以毫秒为单位)。当前仅适用于 OAUTHBEARER。

    类型:int
    默认值:
    取值:
    重要性:
  • sasl.login.read.timeout.ms

    外部身份验证提供程序读取超时的(可选)值(以毫秒为单位)。当前仅适用于 OAUTHBEARER。

    类型:int
    默认值:
    取值:
    重要性:
  • sasl.login.refresh.buffer.seconds

    刷新凭证时要保持的凭证过期前要保持的缓冲时间(以秒为单位)。如果刷新时间比缓冲秒数更接近过期时间,则刷新将上移以保持尽可能多的缓冲时间。合法值介于 0 和 3600 之间(1 小时);如果未指定值,则使用默认值 300(5 分钟)。如果此值和 sasl.login.refresh.min.period.seconds 的总和超过凭证的剩余生命周期,则它们都将被忽略。当前仅适用于 OAUTHBEARER。

    类型:
    默认值:300
    取值:[0,...,3600]
    重要性:
  • sasl.login.refresh.min.period.seconds

    登录刷新线程在刷新凭证之前等待的所需最短时间(以秒为单位)。合法值介于 0 到 900 之间(15 分钟);如果未指定值,则使用默认值 60(1 分钟)。如果此值和 sasl.login.refresh.buffer.seconds 的总和超过凭证的剩余生命周期,则它们都将被忽略。当前仅适用于 OAUTHBEARER。

    类型:
    默认值:60
    取值:[0,...,900]
    重要性:
  • sasl.login.refresh.window.factor

    登录刷新线程将休眠,直到达到相对于凭证生命周期的指定窗口因子,此时它将尝试刷新凭证。合法值介于 0.5 (50%) 和 1.0 (100%) 之间(含);如果未指定值,则使用默认值 0.8 (80%)。当前仅适用于 OAUTHBEARER。

    类型:双整型
    默认值:0.8
    取值:[0.5,...,1.0]
    重要性:
  • sasl.login.refresh.window.jitter

    相对于凭证生命周期的最大随机抖动量,该抖动量添加到登录刷新线程的休眠时间中。合法值介于 0 和 0.25 (25%) 之间(含 0 和 0.25 年);如果未指定值,则使用默认值 0.05 (5%)。当前仅适用于 OAUTHBEARER。

    类型:双整型
    默认值:0.05
    取值:[0.0,...,0.25]
    重要性:
  • sasl.login.retry.backoff.max.ms

    (可选)值(以毫秒为单位),表示尝试登录外部身份验证提供程序之间的最大等待时间。Login 使用指数退避算法,初始等待基于 sasl.login.retry.backoff.ms 设置,并且将在两次尝试之间将等待长度增加一倍,直到达到 sasl.login.retry.backoff.max.ms 设置指定的最大等待长度。当前仅适用于 OAUTHBEARER。

    类型:长整型
    默认值:10000 (10 秒)
    取值:
    重要性:
  • sasl.login.retry.backoff.ms

    尝试登录外部身份验证提供程序之间的初始等待时间的(可选)值(以毫秒为单位)。Login 使用指数退避算法,初始等待基于 sasl.login.retry.backoff.ms 设置,并且将在两次尝试之间将等待长度增加一倍,直到达到 sasl.login.retry.backoff.max.ms 设置指定的最大等待长度。当前仅适用于 OAUTHBEARER。

    类型:长整型
    默认值:100
    取值:
    重要性:
  • sasl.oauthbearer.clock.skew.seconds

    (可选)值(以秒为单位),以允许 OAuth/OIDC 身份提供者和代理的时间之间存在差异。

    类型:int
    默认值:30
    取值:
    重要性:
  • sasl.oauthbearer.expected.audience

    代理使用的(可选)逗号分隔设置,用于验证 JWT 是否是针对预期受众之一颁发的。将检查 JWT 的标准 OAuth “aud” 声明,如果设置了此值,代理将匹配 JWT 的 “aud” 声明中的值,以查看是否存在完全匹配。如果没有匹配项,代理将拒绝 JWT,并且身份验证将失败。

    类型:列表
    默认值:
    取值:
    重要性:
  • sasl.oauthbearer.expected.issuer

    代理用于验证 JWT 是否由预期颁发者创建的(可选)设置。将检查 JWT 中的标准 OAuth “iss” 声明,如果设置了此值,代理会将其与 JWT 的 “iss” 声明中的内容完全匹配。如果没有匹配项,代理将拒绝 JWT,并且身份验证将失败。

    类型:字符串
    默认值:
    取值:
    重要性:
  • sasl.oauthbearer.jwks.endpoint.refresh.ms

    代理在刷新其 JWKS(JSON Web 密钥集)缓存(包含密钥以验证 JWT 签名)之间等待的(可选)值(以毫秒为单位)。

    类型:长整型
    默认值:3600000 (1 小时)
    取值:
    重要性:
  • sasl.oauthbearer.jwks.endpoint.retry.backoff.max.ms

    尝试从外部身份验证提供程序检索 JWKS(JSON Web 密钥集)之间的最大等待时间的(可选)值(以毫秒为单位)。JWKS 检索使用指数退避算法,初始等待基于 sasl.oauthbearer.jwks.endpoint.retry.backoff.ms 设置,并且将两次尝试之间的等待长度增加一倍,直到达到 sasl.oauthbearer.jwks.endpoint.retry.backoff.max.ms 设置指定的最大等待长度。

    类型:长整型
    默认值:10000 (10 秒)
    取值:
    重要性:
  • sasl.oauthbearer.jwks.endpoint.retry.backoff.ms

    来自外部身份验证提供程序的 JWKS(JSON Web 密钥集)检索尝试之间的初始等待的(可选)值(以毫秒为单位)。JWKS 检索使用指数退避算法,初始等待基于 sasl.oauthbearer.jwks.endpoint.retry.backoff.ms 设置,并且将两次尝试之间的等待长度增加一倍,直到达到 sasl.oauthbearer.jwks.endpoint.retry.backoff.max.ms 设置指定的最大等待长度。

    类型:长整型
    默认值:100
    取值:
    重要性:
  • sasl.oauthbearer.scope.claim.name

    范围的 OAuth 声明通常命名为“范围”,但如果 OAuth/OIDC 提供商对该声明使用不同的名称,则此(可选)设置可以提供不同的名称,以用于 JWT 负载声明中包含的范围。

    类型:字符串
    默认值:范围
    取值:
    重要性:
  • sasl.oauthbearer.sub.claim.name

    主题的 OAuth 声明通常命名为“sub”,但如果 OAuth/OIDC 提供商对该声明使用不同的名称,则此(可选)设置可以提供不同的名称,以用于 JWT 负载声明中包含的主题。

    类型:字符串
    默认值:
    取值:
    重要性:
  • security.providers

    可配置的 creator 类的列表,每个类返回一个实现安全算法的提供程序。这些类应该实现org.apache.kafka.common.security.auth.SecurityProviderCreator接口。

    类型:字符串
    默认值:
    取值:
    重要性:
  • ssl.cipher.suites

    密码套件列表。这是身份验证、加密、MAC 和密钥交换算法的命名组合,用于协商使用 TLS 或 SSL 网络协议的网络连接的安全设置。默认情况下,支持所有可用的密码套件。

    类型:列表
    默认值:
    取值:
    重要性:
  • ssl.endpoint.identification.algorithm

    终端节点识别算法,用于使用服务器证书验证服务器主机名。

    类型:字符串
    默认值:https
    取值:
    重要性:
  • ssl.engine.factory.class

    org.apache.kafka.common.security.auth.SslEngineFactory 类型的类,用于提供 SSLEngine 对象。默认值为 org.apache.kafka.common.security.ssl.DefaultSslEngineFactory

    类型:
    默认值:
    取值:
    重要性:
  • ssl.keymanager.algorithm

    密钥管理器工厂用于 SSL 连接的算法。默认值是为 Java 虚拟机配置的密钥管理器工厂算法。

    类型:字符串
    默认值:SunX509 系列
    取值:
    重要性:
  • ssl.secure.random.implementation

    用于 SSL 加密作的 SecureRandom PRNG 实现。

    类型:字符串
    默认值:
    取值:
    重要性:
  • ssl.trustmanager.algorithm

    信任管理器工厂用于 SSL 连接的算法。默认值是为 Java 虚拟机配置的信任管理器工厂算法。

    类型:字符串
    默认值:PKIX
    取值:
    重要性:

3.8 系统属性

Kafka 支持一些可以通过 Java 系统属性启用的配置。系统属性通常是通过将 -D 标志传递给运行 Kafka 组件的 Java 虚拟机来设置的。 以下是支持的系统属性。
  • org.apache.kafka.disallowed.login.modules

    此系统属性用于禁用 SASL JAAS 配置中有问题的登录模块使用。此属性接受以逗号分隔的 loginModule 名称列表。默认情况下,com.sun.security.auth.module.JndiLoginModule loginModule 处于禁用状态。

    如果用户想要启用 JndiLoginModule,用户需要显式重置 system 属性,如下所示。我们建议用户验证配置,并且只允许受信任的 JNDI 配置。有关更多详细信息,CVE-2023-25194

     -Dorg.apache.kafka.disallowed.login.modules=

    要禁用更多 loginModules,请使用逗号分隔的 loginModule 名称更新 system 属性。确保将 JndiLoginModule 模块名称显式添加到逗号分隔列表中,如下所示。

     -Dorg.apache.kafka.disallowed.login.modules=com.sun.security.auth.module.JndiLoginModule,com.ibm.security.auth.module.LdapLoginModule,com.ibm.security.auth.module.Krb5LoginModule
    因为:3.4.0
    默认值:com.sun.security.auth.module.JndiLoginModule

4.1 动机

我们将 Kafka 设计为能够充当一个统一平台,用于处理大型公司可能拥有的所有实时数据源。为此,我们必须考虑相当广泛的用例。

它必须具有高吞吐量才能支持高容量事件流,例如实时日志聚合。

它需要妥善处理大量数据积压,以便能够支持来自离线系统的定期数据加载。

这也意味着系统必须处理低延迟交付,以处理更传统的消息传递用例。

我们希望支持对这些源进行分区、分布式、实时处理,以创建新的派生源。这激发了我们的分区和消费者模型。

最后,在流被馈送到其他数据系统进行服务的情况下,我们知道系统必须能够在机器故障的情况下保证容错能力。

支持这些用途使我们设计出具有许多独特元素的设计,这些元素更类似于数据库日志,而不是传统的消息传递系统。我们将在以下各节中概述设计的一些元素。

4.2 持久性

不要害怕文件系统!

Kafka 严重依赖文件系统来存储和缓存消息。人们普遍认为 “磁盘很慢” ,这使得人们怀疑持久结构能否提供有竞争力的性能。 事实上,磁盘比人们预期的要慢得多,也快得多,这取决于它们的使用方式;而设计得当的磁盘结构通常可以和网络一样快。

关于磁盘性能的关键事实是,在过去十年中,硬盘驱动器的吞吐量一直与磁盘寻道的延迟不同。因此,在具有 6 个 7200rpm SATA RAID-5 阵列的 JBOD 配置上,线性写入的性能约为 600MB/秒,但随机写入的性能仅为 100k/秒左右,相差超过 6000 倍。这些线性读取和写入是最 可预测所有使用模式,并受作系统的大量优化。现代作系统提供预读和后写技术,这些技术以大块倍数预取数据,并且 将较小的逻辑写入分组到较大的物理写入中。有关此问题的进一步讨论,请参阅此 ACM Queue 文章;他们实际上发现,在某些情况下,顺序磁盘访问可能比随机内存访问更快!

为了补偿这种性能差异,现代作系统在将主内存用于磁盘缓存方面变得越来越激进。现代作系统会很乐意将所有空闲内存转移到 磁盘缓存,在回收内存时性能损失很小。所有磁盘读取和写入都将通过此统一缓存。如果不使用直接 I/O,则无法轻松关闭此功能,因此即使 如果一个进程维护数据的进程内缓存,那么这些数据很可能会在 OS Pagecache 中重复,从而有效地将所有内容存储两次。

此外,我们正在 JVM 之上构建,任何花时间研究 Java 内存使用情况的人都知道两件事:

  1. 对象的内存开销非常高,通常会使存储的数据大小增加一倍(或更糟)。
  2. 随着堆内数据的增加,Java 垃圾回收变得越来越复杂和缓慢。

由于这些因素,使用文件系统并依赖页面缓存优于维护内存中缓存或其他结构 — 通过自动访问,我们至少将可用缓存增加了一倍 到所有空闲内存,并且可能通过存储紧凑的字节结构而不是单个对象来再次加倍。这样做将导致在 32GB 计算机上缓存高达 28-30GB,而不会受到 GC 惩罚。 此外,即使服务重新启动,此缓存也将保持热状态,而进程内缓存需要在内存中重建(对于 10GB 缓存,可能需要 10 分钟),否则需要启动 具有完全冷的缓存(这可能意味着糟糕的初始性能)。这也大大简化了代码,因为维护缓存和文件系统之间一致性的所有逻辑现在都在作系统中。 这往往比一次性的进程内尝试更有效、更正确。如果您的磁盘使用偏向于线性读取,则预读实际上是在每个缓存上预先填充有用的数据 磁盘读取。

这表明了一个非常简单的设计:当我们空间用完时,我们不是尽可能多地在内存中维护并将其全部刷新到文件系统中,而是将其反转。所有数据都是即时的 写入文件系统上的持久日志,而不必刷新到磁盘。实际上,这只是意味着它被传输到内核的页面缓存中。

这种以页面缓存为中心的设计风格在 Varnish 设计的文章中进行了描述(以及适度的傲慢)。

恒定时间就足够了

消息传递系统中使用的持久性数据结构通常是每个使用者的队列,其中包含关联的 BTree 或其他通用随机访问数据结构,以维护有关消息的元数据。 BTrees 是可用的最通用的数据结构,可以在消息传递系统中支持各种事务性和非事务性语义。 不过,它们确实带来了相当高的成本: Btree作是 O(log N)。通常 O(log N) 被认为本质上等同于常数时间,但对于磁盘作并非如此。 磁盘寻道的每次弹出时间为 10 毫秒,每个磁盘一次只能执行一次寻道,因此并行度受到限制。因此,即使是少量的磁盘查找也会导致非常高的开销。 由于存储系统将非常快的缓存作与非常慢的物理磁盘作混合在一起,因此随着数据在固定缓存下增加,观察到的树结构性能通常是超线性的——即加倍 您的数据使事情变得比两倍慢要糟糕得多。

直观地说,持久队列可以构建在简单的读取和附加到文件之上,就像日志记录解决方案的常见情况一样。这种结构的优点是所有作都是 O(1) 并且读取不是 块写入或彼此写入。这具有明显的性能优势,因为性能与数据大小完全分离 — 一台服务器现在可以充分利用许多廉价的、 低转速 1+TB SATA 驱动器。尽管它们的寻道性能很差,但这些驱动器对于大型读取和写入具有可接受的性能,并且价格是其 1/3,容量是其 3 倍。

能够访问几乎无限的磁盘空间而不会造成任何性能损失意味着我们可以提供一些在消息传递系统中通常没有的功能。例如,在 Kafka 中,而不是尝试 删除消息 一旦它们被消耗,我们可以将消息保留相对较长的时间(比如一周)。正如我们将要描述的那样,这为消费者带来了很大的灵活性。

4.3 效率

我们在效率方面投入了大量精力。我们的主要用例之一是处理 Web 活动数据,这是非常大量的:每个页面视图可能会产生数十次写入。此外,我们假设每个 发布的消息至少被一个消费者(通常是多个)阅读,因此我们努力使消费尽可能便宜。

我们还从构建和运行许多类似系统的经验中发现,效率是有效多租户运营的关键。如果下游基础设施服务可以轻松成为 瓶颈由于应用程序使用量的小幅增加,这种微小的更改通常会产生问题。通过非常快的速度,我们帮助确保应用程序在基础设施之前在负载下翻倒。 当尝试在集中式集群上运行支持数十或数百个应用程序的集中式服务时,这一点尤其重要,因为使用模式的变化几乎每天都在发生。

我们在上一节中讨论了磁盘效率。一旦消除了不良的磁盘访问模式,这种类型的系统中效率低下有两个常见原因:太多的小 I/O作,以及 过多的字节复制。

小的 I/O 问题既发生在客户端和服务器之间,也发生在服务器自己的持久作中。

为了避免这种情况,我们的协议是围绕 “消息集” 抽象构建的,该抽象自然地将消息分组在一起。这允许网络请求将消息分组在一起并分摊网络开销 往返,而不是一次发送一条消息。反过来,服务器一次性将消息块附加到其日志中,而使用者一次获取较大的线性块。

这种简单的优化产生了数量级的速度提升。批处理会导致更大的网络数据包、更大的顺序磁盘作、连续的内存块等,所有这些都允许 Kafka 将 随机消息的突发流写入流向使用者的线性写入。

另一个效率低下的地方是字节复制。在低消息速率下,这不是问题,但在负载下,影响很大。为避免这种情况,我们采用了由 producer、broker 和 consumer(因此可以在它们之间传输数据块而无需修改)。

代理维护的消息日志本身只是一个文件目录,每个文件都由一系列消息集填充,这些消息集已以生成者和使用者使用的相同格式写入磁盘。 保持这种通用格式可以优化最重要的作:持久性日志块的网络传输。现代 unix作系统为传输数据提供了高度优化的代码路径 从 PageCache 中输出到套接字;在 Linux 中,这是通过 sendfile 系统调用完成的。

要了解 sendfile 的影响,了解将数据从文件传输到套接字的常见数据路径非常重要:

  1. 作系统将数据从磁盘读取到内核空间的页面缓存中
  2. 应用程序将数据从内核空间读取到用户空间缓冲区中
  3. 应用程序将数据写回到内核空间的套接字缓冲区中
  4. 作系统将数据从 socket 缓冲区复制到 NIC 缓冲区,然后通过网络发送数据

这显然是低效的,有四个副本和两个系统调用。使用 sendfile,通过允许作系统将数据从 pagecache 直接发送到网络,可以避免这种重新复制。所以在这个优化的 path,则只需要 NIC 缓冲区的最终副本。

我们预计一个常见使用案例是某个主题的多个使用者。使用上面的零副本优化,数据将仅复制到页面缓存中一次,并在每次使用时重复使用,而不是存储在内存中 并在每次读取时复制到 user-space。这允许以接近网络连接限制的速率使用消息。

pagecache 和 sendfile 的这种组合意味着,在消费者大部分都赶上了 Kafka 集群上,您将不会在磁盘上看到任何读取活动,因为它们将完全从缓存中提供数据。

TLS/SSL 库在用户空间(内核内SSL_sendfile目前不受 Kafka 支持)。由于此限制,sendfile在启用 SSL 时不使用。启用 SSL 配置,请参阅security.protocolsecurity.inter.broker.protocol

有关 Java 中 sendfile 和零拷贝支持的更多背景信息,请参阅此文章

端到端批量压缩

在某些情况下,瓶颈实际上不是 CPU 或磁盘,而是网络带宽。对于需要通过广域网在数据中心之间发送消息的数据管道来说,尤其如此。答案是肯定的 用户始终可以一次压缩一条消息,而无需 Kafka 提供任何支持,但这可能会导致压缩率非常差,因为大部分冗余是由于 相同类型(例如 JSON 中的字段名称或 Web 日志中的用户代理或常见字符串值)。高效压缩需要将多条消息压缩在一起,而不是单独压缩每条消息。

Kafka 通过高效的批处理格式支持此功能。可以将一批消息聚集在一起,压缩并发送到此表单的服务器。这批消息将以压缩形式写入,并将 在日志中保持压缩状态,并且只会由 Consumer 解压缩。

Kafka 支持 GZIP、Snappy、LZ4 和 ZStandard 压缩协议。有关压缩的更多详细信息,请参阅此处

4.4 制作人

负载均衡

创建者将数据直接发送到作为分区领导者的代理,而无需任何中间路由层。为了帮助创建者执行此作,所有 Kafka 节点都可以响应有关哪个 服务器处于活动状态,并且主题分区的 leader 在任何给定时间都位于该位置,以允许创建者适当地定向其请求。

客户端控制将消息发布到哪个分区。这可以是随机完成的,实现一种随机负载均衡,也可以通过一些语义分区函数来完成。我们公开了接口 对于语义分区,允许用户指定要分区的键,并使用该键对分区进行哈希处理(如果需要,还可以选择覆盖分区函数)。例如,如果密钥 chosen 是用户 ID,则给定用户的所有数据都将发送到同一分区。这反过来又将允许消费者对他们的消费做出地方性假设。这种分区样式是显式的 旨在允许在使用者中进行位置敏感处理。

异步发送

批处理是提高效率的重要驱动因素之一,为了启用批处理,Kafka 生产者将尝试在内存中积累数据,并在单个请求中发送更大的批处理。可以配置批处理 累积的消息数不超过固定数量的消息,并且等待时间不超过某个固定的延迟限制(比如 64k 或 10 毫秒)。这允许累积更多字节来发送,并且 服务器。这种缓冲是可配置的,并提供了一种机制来权衡少量的额外延迟以获得更好的吞吐量。

可以找到有关创建者的配置API 的详细信息 在文档的其他位置。

4.5 消费者

Kafka 使用者的工作原理是向引导它想要使用的分区的代理发出 “fetch” 请求。使用者使用每个请求在日志中指定其偏移量,并接收回一个日志块 从那个位置开始。因此,消费者对这个位置有很大的控制权,如果需要,可以倒带它以重新消费数据。

推 vs. 拉

我们考虑的一个初始问题是,使用者是否应该从代理中提取数据,或者代理应该将数据推送给使用者。在这方面,Kafka 遵循了大多数消息传递所采用的更传统的设计 系统,其中数据从生产者推送到代理,并由使用者从代理中提取。一些以日志记录为中心的系统(如 ScribeApache Flume)遵循非常不同的基于推送的路径,其中数据被推送到下游。这两种方法各有利弊。但是,基于推送的系统存在困难 作为代理控制数据传输速率,因此与不同的使用者打交道。目标通常是让消费者能够以尽可能高的速度消费;不幸的是,在 A Push 中 系统这意味着当消费者的消费速度低于生产速度时,消费者往往会不堪重负(本质上是拒绝服务攻击)。基于拉取的系统具有更好的属性,即 消费者只是落后了,并在可以的时候迎头赶上。这可以通过某种回退协议来缓解,消费者可以通过该协议表明它不堪重负,但将传输速率提高到 充分利用(但永远不要过度利用)消费者比看起来更棘手。以前以这种方式构建系统的尝试导致我们采用了更传统的拉取模型。

基于拉取的系统的另一个优点是,它适合对发送给使用者的数据进行主动批处理。基于推送的系统必须选择立即发送请求或累积更多数据 然后稍后发送它,而不知道下游使用者是否能够立即处理它。如果针对低延迟进行调整,这将导致一次仅针对 transfer 最终会被缓冲,这是浪费。基于拉取的设计解决了这个问题,因为消费者总是在日志中的当前位置之后(或最多某个可配置的最大值)拉取所有可用的消息 size) 的 Package。因此,可以在不引入不必要的延迟的情况下获得最佳批处理。

一个朴素的基于拉取的系统的缺陷在于,如果 broker 没有数据,消费者最终可能会在一个紧密的循环中轮询,实际上是忙于等待数据到达。为了避免这种情况,我们在 拉取请求,它允许使用者请求在 “长轮询” 中阻塞,直到数据到达(并且可以选择等到给定数量的字节可用,以确保较大的传输大小)。

你可以想象其他可能的设计,这些设计只是拉式的,端到端的。生产者将本地写入本地日志,代理将从该日志中提取,消费者从中提取。类似类型的 经常提出 “store-and-forward” producer。这很有趣,但我们认为不太适合拥有数千个生产者的目标用例。我们在 Scale 让我们觉得,在系统中涉及许多应用程序的数千个磁盘实际上不会使事情变得更可靠,而且作起来会是一场噩梦。在实践中,我们发现 可以大规模运行具有强大 SLA 的管道,而无需生产者持久性。

消费者位置

令人惊讶的是,跟踪已消耗的内容是消息传递系统的关键性能点之一。

大多数消息传送系统都保留有关代理上使用的消息的元数据。也就是说,当消息分发给使用者时,代理要么立即在本地记录该事实,要么可能等待 供消费者确认。这是一个相当直观的选择,实际上,对于单机服务器来说,并不清楚这种状态还可以去哪里。由于许多 消息传递系统的扩展性很差,这也是一个务实的选择 - 因为 broker 知道消耗了什么,所以它可以立即删除它,从而保持较小的数据量。

也许不太明显的是,让经纪人和消费者就消费的内容达成一致并不是一个小问题。如果 broker 将消息记录为立即消费 当它通过网络分发时,如果消费者无法处理消息(比如因为它崩溃或请求超时或其他原因),该消息将丢失。为了解决这个问题,许多消息传递 系统添加了确认功能,这意味着消息在发送时仅标记为已发送,而不是已使用;代理等待使用者的特定确认来记录 消息作为已消费的 API 值。此策略解决了丢失消息的问题,但会产生新问题。首先,如果消费者处理了消息,但在发送确认之前失败了,那么 消息将被消耗两次。第二个问题是关于性能的,现在 broker 必须为每条消息保留多个状态(首先是锁定它,这样它就不会被第二次发出,然后是标记 它是永久消耗的,以便可以将其移除)。必须处理棘手的问题,例如如何处理已发送但从未确认的消息。

Kafka 的处理方式不同。我们的主题分为一组完全有序的分区,每个分区在任何给定时间都由每个订阅使用者组中的一个使用者使用。这意味着 每个分区中使用者的位置只是一个整数,即要消耗的下一条消息的偏移量。这使得有关已消耗内容的状态非常小,每个分区只有一个数字。 此状态可以定期进行检查点作。这使得消息确认的等效性非常便宜。

这个决定还有一个附带的好处。使用者可以故意回退到旧的偏移量并重新使用数据。这违反了队列的公共契约,但事实证明这是一个基本功能 对于许多消费者来说。例如,如果消费者代码存在 Bug,并且在消费了某些消息后被发现,那么一旦 Bug 被修复,消费者可以重新消费这些消息。

离线数据加载

可扩展的持久性允许使用者仅定期使用,例如定期将数据批量加载到离线系统(如 Hadoop 或关系数据)的批处理数据加载 仓库。

在 Hadoop 的情况下,我们通过将负载拆分到各个映射任务上来并行数据加载,每个任务对应一个节点/主题/分区组合,从而允许加载中的完全并行性。Hadoop 提供任务 管理,失败的任务可以重新启动,而不会有重复数据的危险 — 它们只是从原来的位置重新启动。

静态成员资格

静态成员资格旨在提高流应用程序、消费者组和其他构建在组再平衡协议之上的应用程序的可用性。 再平衡协议依赖于组协调器将实体 ID 分配给组成员。这些生成的 ID 是短暂的,当成员重新启动并重新加入时,它们会发生变化。 对于基于使用者的应用程序,这种 “动态成员资格” 可能会导致在管理作期间将很大一部分任务重新分配给不同的实例 例如代码部署、配置更新和定期重启。对于大型 state 应用程序,shuffle 任务在处理之前需要很长时间来恢复其本地状态 并导致应用程序部分或全部不可用。在这一观察的推动下,Kafka 的群组管理协议允许群组成员提供持久性实体 ID。 根据这些 ID 的组成员资格保持不变,因此不会触发再平衡。

如果要使用静态成员身份,

  • 将代理集群和客户端应用程序升级到 2.3 或更高版本,并确保升级后的代理使用inter.broker.protocol.version2.3 或更高。
  • 设置配置ConsumerConfig#GROUP_INSTANCE_ID_CONFIG设置为一个组下每个使用者实例的唯一值。
  • 对于 Kafka Streams 应用程序,设置唯一的ConsumerConfig#GROUP_INSTANCE_ID_CONFIG每个 KafkaStreams 实例, 与实例的已用线程数无关。
如果您的代理版本低于 2.3,但您选择将ConsumerConfig#GROUP_INSTANCE_ID_CONFIG在客户端,应用程序将检测 代理版本,然后引发 UnsupportedException。如果您不小心为不同的实例配置了重复的 ID, broker 端的 fencing 机制将通过触发org.apache.kafka.common.errors.FencedInstanceIdException. 有关更多详细信息,请参阅 KIP-345

4.6 消息传递语义

现在我们已经对生产者和消费者的工作原理有了一点了解,让我们讨论一下 Kafka 在生产者和消费者之间提供的语义保证。显然,有多种可能的消息传递 可以提供的保证:

  • At most once (最多一次) - 邮件可能会丢失,但永远不会重新传送。
  • 至少一次 - 邮件永远不会丢失,但可能会重新传送。
  • 恰好一次 — 这就是人们真正想要的,每条消息都只传递一次。
值得注意的是,这分为两个问题:发布消息的持久性保证和使用消息时的保证。

许多系统声称提供 “exactly once” 交付语义,但阅读细则很重要,这些声明中的大多数都是误导性的(即,它们没有转化为消费者或生产者的情况 可能会失败,如果存在多个使用者进程,或者写入磁盘的数据可能会丢失)。

Kafka 的语义很简单。当发布消息时,我们有一个消息被 “提交” 到日志的概念。一旦提交了已发布的消息,只要有一个代理 复制此消息写入的分区保持 “活动” 状态。提交消息的定义、活动分区以及我们尝试处理的故障类型的描述将是 将在下一节中更详细地介绍。现在,让我们假设一个完美的无损代理,并尝试了解对生产者和使用者的保证。如果生产者尝试发布消息,并且 遇到网络错误时,无法确定此错误是在提交消息之前还是之后发生。这类似于使用自动生成的键插入数据库表的语义。

在 0.11.0.0 之前,如果生产者未能收到指示消息已提交的响应,则它别无选择,只能重新发送消息。这提供了至少一次传递语义,因为 如果原始请求实际上已成功,则在重新发送期间可能会再次将 message 写入日志。从 0.11.0.0 开始,Kafka 生产者还支持幂等交付选项,该选项保证重新发送 不会导致日志中出现重复条目。为此,代理为每个创建者分配一个 ID,并使用创建者随每条消息发送的序列号删除重复消息。 同样从 0.11.0.0 开始,生产者支持使用类似事务的语义将消息发送到多个主题分区的能力:即所有消息都已成功写入,或者没有一条消息成功写入。 其主要用例是 Kafka 主题之间的 exactly-once 处理(如下所述)。

并非所有用例都需要如此强大的保证。对于延迟敏感型用途,我们允许创建者指定所需的持久性级别。如果创建者指定要等待消息 提交时,可能需要 10 毫秒左右。但是,创建者也可以指定它希望完全异步地执行发送,或者它只想等待 leader (而不是 必然是追随者)有信息。

现在让我们从消费者的角度描述语义。所有副本都有完全相同的日志,具有相同的偏移量。使用者控制其在此日志中的位置。如果消费者从未崩溃 可以只将此位置存储在内存中,但是如果 consumer 失败并且我们希望此主题分区由另一个进程接管,则新进程将需要选择一个适当的位置来开始 加工。假设使用者读取了一些消息 —— 它有几个选项来处理消息并更新其位置。

  1. 它可以读取消息,然后保存其在日志中的位置,最后处理消息。在这种情况下,使用者进程可能会在保存其位置之后但在保存之前崩溃 其消息处理的输出。在这种情况下,接管处理的进程将从保存的位置开始,即使该位置之前的几条消息尚未处理。这对应于 更改为 “at-most-once” 语义,例如在使用者失败的情况下,消息可能不会被处理。
  2. 它可以读取消息、处理消息,最后保存其位置。在这种情况下,使用者进程可能会在处理消息之后但在保存其位置之前崩溃。 在这种情况下,当新进程接管时,它收到的前几条消息已经被处理过。这对应于消费者失败情况下的 “at-least-once” 语义。在许多情况下 消息具有主键,因此更新是幂等的(两次接收相同的消息只会用自身的另一个副本覆盖记录)。

那么 Exactly once 语义(即你真正想要的东西)呢?当从 Kafka 主题消费并生成到另一个主题时(如在 Kafka Streams 应用程序中),我们可以利用上面提到的 0.11.0.0 中新的事务性生产者功能。Consumer 的位置作为消息存储在 topic 中,因此我们可以将偏移量写入 Kafka 的 与接收已处理数据的输出主题相同的事务。如果事务被中止,消费者的位置将恢复为原来的值,并且输出主题上生成的数据将不可见 分配给其他使用者,具体取决于他们的 “隔离级别”。在默认的 “read_uncommitted” 隔离级别中,所有消息对使用者都是可见的,即使它们是中止事务的一部分。 但在 “read_committed” 中,消费者将仅返回来自已提交的事务的消息(以及不属于事务的任何消息)。

写入外部系统时,限制在于需要将使用者的位置与实际存储为 output 的内容相协调。实现这一目标的经典方法是引入两阶段 commit 在 Consumer 位置的存储和 consumer 输出的存储之间。但是,这可以通过让消费者将其偏移量存储在与 它的输出。这更好,因为使用者可能想要写入的许多输出系统不支持两阶段提交。例如,考虑一个 Kafka Connect 连接器,该连接器将数据填充到 HDFS 中,以及它读取的数据的偏移量,以便保证数据和 offsets 既更新 Offsets,要么都未更新。对于许多其他数据系统,我们遵循类似的模式,这些系统需要这些更强的语义,并且消息没有主键来允许重复数据删除。

因此,Kafka 实际上支持 Kafka Streams 中的 Exactly-once 交付,并且事务性生产者/使用者通常可用于提供 在 Kafka 主题之间传输和处理数据时进行 exactly-once 交付。其他目标系统的 Exactly-once 交付通常需要与此类系统合作,但 Kafka 提供了 offset 实现这一点(另请参阅 Kafka Connect)。否则,Kafka 默认保证至少一次交付,并允许 用户通过在生产者上禁用重试并在处理一批消息之前在使用者中提交偏移量来实现最多一次传输。

4.7 复制

Kafka 在可配置数量的服务器上复制每个主题分区的日志(您可以逐个主题设置此复制因子)。这允许在 群集中的服务器发生故障,因此消息在发生故障时仍然可用。

其他消息传递系统提供了一些与复制相关的功能,但是,在我们(完全有偏见的)看来,这似乎是一个附加的东西,没有被大量使用,并且有很大的缺点:副本处于非活动状态, 吞吐量受到严重影响,需要繁琐的手动配置等。默认情况下,Kafka 旨在与复制一起使用——事实上,我们将未复制的主题实现为复制的主题,其中 复制因子为 1。

复制单位是主题分区。在非故障条件下,Kafka 中的每个分区都有一个 leader 和零个或多个 follower。包括领导者在内的副本总数构成 复制因子。所有写入都转到分区的 leader,读取可以转到分区的 leader 或 followers。通常,分区数比 broker 多得多,并且 leader 在 broker 之间均匀分布。follower 上的日志为 与 leader 的日志相同 — 所有 leader 都具有相同的偏移量和相同顺序的消息(当然,在任何给定时间,leader 的日志末尾都可能有一些尚未复制的消息)。

追随者像普通的 Kafka 使用者一样使用来自领导者的消息,并将其应用于自己的日志。让追随者从领导者那里拉动有一个很好的特性,即允许追随者自然地 将他们应用于日志的日志条目批处理在一起。

与大多数分布式系统一样,自动处理故障需要精确定义节点“活动”的含义。在 Kafka 中,有一个特殊节点 称为 “controller” ,负责管理集群中 broker 的注册。Broker 活跃度有两个条件:

  1. Broker 必须保持与控制器的活动会话,以便接收定期元数据更新。
  2. 充当 follower 的 broker 必须复制 leader 的写入,并且不能“太远”落后。

“活动会话” 的含义取决于集群配置。对于 KRaft 集群,活动会话由 向控制器发送定期检测信号。如果控制器在broker.session.timeout.msexpires,则节点被视为离线。

对于使用 Zookeeper 的集群,活动性是通过代理在 初始化其 Zookeeper 会话。如果 broker 在 Zookeeper 过期前未能向 Zookeeper 发送心跳,导致 session 丢失zookeeper.session.timeout.ms,则节点将被删除。然后,控制器将通过 Zookeeper 监视注意到节点删除 并将代理标记为离线。

我们将满足这两个条件的节点称为 “同步” ,以避免 “alive” 或 “failed” 的模糊性。leader 跟踪 “同步” 副本集, 这被称为 ISR。如果不满足这些条件中的任何一个,则将从 ISR 中删除代理。例如 如果 follower 死亡,则控制器将通过丢失其 session 来注意到故障,并将从 ISR 中删除 broker。 另一方面,如果 follower 落后于 leader 太远,但仍具有活动会话,则 leader 也可以将其从 ISR 中删除。 滞后副本的确定是通过replica.lag.time.max.ms配置。 在此配置设置的最大时间内无法赶上 leader 上的日志末尾的副本将从 ISR 中删除。

在分布式系统术语中,我们只尝试处理 “fail/recover” 故障模型,其中节点突然停止工作,然后恢复(可能不知道它们已经死亡)。Kafka 不会 处理所谓的“拜占庭”故障,其中节点产生任意或恶意响应(可能是由于错误或犯规)。

现在,我们可以更精确地定义,当该分区的 ISR 中的所有副本都已将消息应用于其日志时,该消息被视为已提交。 只有提交的消息才会分发给使用者。这意味着使用者不必担心可能会看到如果领导者失败可能会丢失的消息。另一方面,生产商 可以选择等待或不等待消息提交,具体取决于他们对延迟和持久性之间权衡的偏好。此首选项由 acks 设置控制,该设置中的 producer 使用。 请注意,主题具有同步副本的“最小数量”设置,当创建者请求确认消息 已写入完整的同步副本集。如果生产者请求不太严格的确认,则可以提交和使用消息。 即使同步副本的数量低于最小值(例如,它可以低至仅 leader 副本)。

Kafka 提供的保证是,只要始终至少有一个 in sync 副本处于活动状态,提交的消息就不会丢失。

在短暂的故障转移期后,Kafka 在节点故障的情况下仍可用,但在存在网络分区的情况下可能无法保持可用。

复制的日志:仲裁、ISR 和状态机(天哪!

Kafka 分区的核心是复制日志。复制日志是分布式数据系统中最基本的原语之一,有许多方法可以实现它。复制的日志可以是 被其他系统用作以状态机样式实现其他分布式系统的原语。

复制日志模拟了按一系列值的顺序达成共识的过程(通常对日志条目进行编号 0、1、2 等)。实现此目的的方法有很多种,但最简单、最快捷 与选择提供给它的值的 Sequences 的 leader 一起使用。只要 leader 还活着,所有 follower 只需复制 leader 选择的值和顺序。

当然,如果领导者没有失败,我们就不需要追随者!当领导者去世时,我们需要从追随者中选择一位新的领导者。但是追随者本身可能会落后或崩溃,因此我们必须确保我们 选择最新的关注者。日志复制算法必须提供的基本保证是,如果我们告诉客户端一条消息已提交,并且 leader 失败,则我们选择的新 leader 也必须具有 那个信息。这会产生一个权衡:如果领导者在宣布消息已提交之前等待更多追随者确认消息,那么将有更多潜在的可选举领导者。

如果选择所需的确认数和必须比较的日志数才能选择领导者,从而保证存在重叠,则这称为 Quorum。

这种权衡的常见方法是对提交决策和领导者选举都使用多数票。这不是 Kafka 的作用,但无论如何,让我们探索它以了解权衡。假设我们 有 2 个f+1 副本。如果 f+1 副本必须在 leader 声明提交之前收到一条消息,并且如果我们通过从至少 f+1 个副本中选出具有最完整日志的 follower 来选举新的 leader,那么,在不超过 f 次失败的情况下,可以保证 leader 拥有所有提交的消息。这是因为在任何 f+1 副本中,必须至少有一个副本包含 所有已提交的邮件。该副本的日志将是最完整的,因此将被选为新的 leader。每个算法必须处理许多剩余细节(例如精确定义的 使日志更完整,确保 leader 故障期间的日志一致性或更改副本集中的服务器集),但我们暂时忽略这些。

这种多数投票方法有一个非常好的特性:延迟仅取决于最快的服务器。也就是说,如果复制因子为 3,则延迟由较快的 follower 而不是较慢的 follower 决定。

这个系列中有各种各样的算法,包括 ZooKeeper 的 ZabRaft、 和 Viewstamped Replication 的 Replication。 据我们所知,与 Kafka 的实际实现最相似的学术出版物是 Microsoft 的 PacificA

多数票的缺点是,不需要很多失败就会让你没有可选举的领导人。容忍 1 次失败需要 3 个数据副本,容忍 2 次失败需要 5 个副本 的数据。根据我们的经验,对于实际系统来说,仅仅有足够的冗余来容忍单个故障是不够的,但每次写入执行 5 次,磁盘空间要求是 5 倍,是 1/5 吞吐量,对于大容量数据问题不是很实用。这可能就是为什么仲裁算法更常出现在共享集群配置(如 ZooKeeper)中,而对于主数据来说不太常见的原因 存储。例如,在 HDFS 中,namenode 的高可用性功能是建立在基于多数投票的日志之上的,但是这个更多的 昂贵的方法不用于数据本身。

Kafka 在选择其 quorum 集时采用的方法略有不同。Kafka 不是多数投票,而是动态维护一组同步副本 (ISR),这些副本被捕获到领导者。仅此集的成员 有资格竞选领导人。在所有同步副本都收到写入之前,对 Kafka 分区的写入不被视为已提交。每当此 ISR 集发生更改时,它都会保留在群集元数据中。 因此,ISR 中的任何副本都有资格被选为 leader。这是 Kafka 使用模型的一个重要因素,其中有很多分区,确保领导平衡很重要。 使用此 ISR 模型和 f+1 副本,Kafka 主题可以容忍 f 失败,而不会丢失已提交的消息。

对于我们希望处理的大多数用例,我们认为这种权衡是合理的。在实践中,为了容忍 f 次失败,多数投票和 ISR 方法都将等待相同数量的副本 在提交消息之前确认(例如,要在一次失败中幸存下来,多数 quorum 需要 3 个副本和 1 个确认,而 ISR 方法需要 2 个副本和 1 个确认)。 能够在没有最慢服务器的情况下提交是多数投票方法的一个优势。但是,我们认为允许客户端选择是否阻止消息提交可以改善这种情况。 由于所需的复制因子较低而增加的吞吐量和磁盘空间是值得的。

另一个重要的设计区别是 Kafka 不要求崩溃的节点在恢复时所有数据都完好无损。此空间中的复制算法依赖于 “稳定存储”,在任何故障恢复场景中都不会丢失,而不会发生潜在的一致性冲突。这个假设有两个主要问题。首先,磁盘错误是我们最常见的问题 在持久数据系统的实际作中观察,它们通常不会保持数据完好无损。其次,即使这不是问题,我们也不想要求在每次写入时使用 fsync 以保持一致性 保证,因为这会将性能降低 2 到 3 个数量级。我们允许副本重新加入 ISR 的协议可确保在重新加入之前,它必须再次完全重新同步,即使它丢失了未刷新 数据。

不洁的领导人选举:如果他们都死了怎么办?

请注意,Kafka 对数据丢失的保证是基于至少一个副本保持同步。如果复制分区的所有节点都死了,则此保证不再成立。

但是,当所有副本都死去时,实际系统需要做一些合理的事情。如果您不幸发生这种情况,重要的是要考虑会发生什么。有两种行为可能是 实现:

  1. 等待 ISR 中的副本恢复运行,并选择此副本作为 leader(希望它仍然拥有其所有数据)。
  2. 选择作为领导者恢复生机的第一个副本 (不一定在 ISR 中)。

这是可用性和一致性之间的简单权衡。如果我们在 ISR 中等待副本,那么只要这些副本关闭,我们就保持不可用。如果此类副本或其数据被销毁 丢失了,那么我们就永远宕机了。另一方面,如果一个非同步副本恢复了生命,并且我们允许它成为领导者,那么它的日志就会成为事实的来源,即使它不能保证 拥有每条提交的消息。默认情况下,从版本 0.11.0.0 开始,Kafka 选择第一种策略并倾向于等待一致的副本。可以使用 配置属性 unclean.leader.election.enable,以支持正常运行时间优于一致性的使用案例。

这种困境并非 Kafka 所独有。它存在于任何基于 quorum 的方案中。例如,在多数投票方案中,如果大多数服务器遭受永久故障,那么您必须选择损失 100% 的 您的数据,或者通过将现有服务器上剩余的数据作为新的事实来源来违反一致性。

可用性和持久性保证

写入 Kafka 时,创建者可以选择是等待 0,1 个副本还是所有 (-1) 副本确认消息。 请注意,“acknowledgement by all replicas” 并不能保证已分配的完整副本集已收到该消息。默认情况下,当 acks=all 时,一旦所有当前同步,就会发生确认 副本已收到消息。例如,如果一个主题仅配置了两个副本,而一个副本失败(即,只剩下一个同步副本),则指定 acks=all 的写入将成功。然而,这些 如果剩余副本也失败,则写入可能会丢失。 尽管这确保了分区的最大可用性,但对于某些更喜欢持久性而不是可用性的用户来说,这种行为可能是不可取的。因此,我们提供了两个主题级配置,它们可以是 过去,消息持久性优于可用性:
  1. 禁用不干净的 leader election - 如果所有副本都变得不可用,则分区将保持不可用状态,直到最新的 leader 再次可用。这实际上更喜欢不可用 克服消息丢失的风险。有关澄清,请参阅上一节 Unclean Leader Election。
  2. 指定最小 ISR 大小 - 仅当 ISR 大小高于某个最小值时,分区将仅接受写入,以防止仅写入单个副本的消息丢失。 随后变得不可用。仅当创建者使用 acks=all 并保证消息至少由这么多同步副本确认时,此设置才会生效。 此设置在一致性和可用性之间进行权衡。最小 ISR 大小的设置越高,一致性越好,因为可以保证将消息写入更多副本,从而减少 丢失的概率。但是,它会降低可用性,因为如果同步副本的数量低于最小阈值,分区将不可用于写入。

副本管理

上面关于复制日志的讨论实际上只涵盖了单个日志,即一个主题分区。但是,Kafka 集群将管理成百上千个这样的分区。我们尝试平衡分区 在集群中以循环方式进行集群,以避免在少量节点上为高容量主题的所有分区进行集群。同样,我们试图平衡领导层,以便每个节点都是 份额。

优化领导层选举流程也很重要,因为这是不可用的关键窗口。天真的 leader elect 实现最终会为每个分区运行一个 election for all 对该节点发生故障时托管的节点进行分区。如上文有关复制的章节所述,Kafka 集群具有称为 “控制器” 的特殊角色,即 负责管理经纪人的注册。如果控制器检测到代理故障,则负责选择 ISR 的剩余成员之一作为新的领导者。 结果是,我们能够将许多必需的领导层变更通知批量汇总在一起,这使得选举过程对大量人来说要便宜得多、更快捷 的分区。如果控制器本身出现故障,则将选择另一个控制器。

4.8 日志压缩

日志压缩可确保 Kafka 始终保留单个主题分区的数据日志中每个消息键的至少最后一个已知值。它解决了还原等使用案例和场景 状态,或者在作维护期间应用程序重启后重新加载缓存。让我们更详细地研究这些使用案例,然后描述压缩的工作原理。

到目前为止,我们只描述了更简单的数据保留方法,即在固定时间段后或当日志达到某个预定大小时丢弃旧日志数据。这适用于时态事件 数据,例如每条记录独立存在的日志记录。但是,一类重要的数据流是对键控可变数据(例如,对数据库表的更改)的更改日志。

让我们讨论这样一个 Stream 的具体示例。假设我们有一个包含用户电子邮件地址的主题;每次用户更新其电子邮件地址时,我们都会使用其用户 ID 作为 primary key 的 key 中。现在假设我们在一段时间内为 ID 为 123 的用户发送以下消息,每条消息对应于电子邮件地址的更改(省略了其他 ID 的消息):

123 => bill@microsoft.com
        .
        .
        .
123 => bill@gatesfoundation.org
        .
        .
        .
123 => bill@gmail.com
日志压缩为我们提供了一个更精细的保留机制,以便保证我们至少保留每个主键的最后一次更新(例如bill@gmail.com).通过这样做,我们保证 log 包含每个键的最终值的完整快照,而不仅仅是最近更改的键。这意味着下游消费者可以从这个主题中恢复他们自己的状态,而不必保留一个完整的 所有更改的日志。

让我们先看看一些有用的用例,然后看看如何使用它。

  1. 数据库更改订阅。通常需要在多个数据系统中拥有数据集,而这些系统之一通常是某种数据库(RDBMS 或新奇的键值 store 的例如,您可能有一个数据库、一个缓存、一个搜索集群和一个 Hadoop 集群。对数据库的每次更改都需要反映在缓存、搜索集群中,并最终反映在 Hadoop 中。 如果一个人只处理实时更新,则只需要最近的日志。但是,如果您希望能够重新加载缓存或恢复失败的搜索节点,则可能需要一个完整的数据集。
  2. 事件溯源。这是一种应用程序设计风格,它将查询处理与应用程序设计放在一起,并使用更改日志作为应用程序的主要存储。
  3. 日志以实现高可用性。执行本地计算的进程可以通过注销对其本地状态所做的更改来使其具有容错能力,以便另一个进程可以重新加载这些更改和 如果它失败了,请继续。这方面的一个具体示例是在流查询系统中处理计数、聚合和其他类似 “group by” 的处理。实时流处理框架 Samza 正是为此目的使用此功能
在每种情况下,用户主要需要处理更改的实时馈送,但有时,当机器崩溃或需要重新加载或重新处理数据时,需要执行满负载。 Log compaction 允许从相同的后备主题为这两个用例提供数据。 此博客文章中更详细地介绍了日志的这种使用方式。

一般的思路很简单。如果我们有无限的日志保留,并且我们记录了上述情况下的每次更改,那么我们将从系统首次开始捕获系统每次的状态。 使用此完整日志,我们可以通过重放日志中的前 N 条记录来还原到任何时间点。这个假设的完整日志对于多次更新单个记录的系统来说不是很实用 因为即使对于稳定的数据集,日志也会无限增长。丢弃旧更新的简单日志保留机制将限制空间,但日志不再是恢复当前状态的方法 - 现在 从日志开头还原不再重新创建当前状态,因为可能根本不会捕获旧更新。

日志压缩是一种机制,用于提供更精细的每条记录保留,而不是更粗粒度的基于时间的保留。这个想法是有选择地删除我们最近更新了 相同的主键。这样可以保证日志至少具有每个键的最后一个状态。

此保留策略可以按主题设置,因此单个集群可以包含一些主题,其中保留是通过大小或时间强制执行的,而其他主题则通过压缩强制执行保留。

此功能的灵感来自 LinkedIn 最古老、最成功的基础设施之一 — 名为 Databus 的数据库变更日志缓存服务。 与大多数日志结构存储系统不同,Kafka 是为订阅而构建的,它组织数据以实现快速线性读取和写入。与 Databus 不同,Kafka 充当事实来源存储,因此即使在 否则 upstream 数据源将无法重放的情况。

日志压缩基础知识

这是一个高级图片,其中显示了 Kafka 日志的逻辑结构以及每条消息的偏移量。

日志的头部与传统的 Kafka 日志相同。它具有密集的连续偏移量并保留所有消息。Log compaction 添加了一个用于处理日志尾部的选项。上图显示了一个日志 尾巴压实。请注意,日志尾部的消息保留了首次写入时分配的原始偏移量,该偏移量永远不会更改。另请注意,所有偏移量在 日志,即使具有该偏移量的消息已被压缩掉;在这种情况下,此位置与日志中出现的下一个最高偏移量没有区别。例如,在上图中, 偏移量 36、37 和 38 都是等效位置,从这些偏移量中的任何一个开始的读取都将返回以 38 开头的消息集。

压缩还允许删除。具有键和 null 负载的消息将被视为从日志中删除。此类记录有时称为逻辑删除。此删除标记将导致删除具有该键的任何先前邮件(就像任何新的 message 的 KEY),但 DELETE 标记很特殊,因为它们本身会在一段时间后从日志中清除以释放空间。不再保留删除的时间点是 在上图中标记为 “Delete retention point”(删除保留点)。

压缩是通过定期重新复制日志段在后台完成的。清理不会阻止读取,并且可以限制为使用不超过可配置的 I/O 吞吐量,以避免影响 生产者和消费者。压缩日志段的实际过程如下所示:

Log Compaction 提供哪些保障

日志压缩可保证以下内容:
  1. 任何保持在日志头内的使用者都将看到写入的每条消息;这些消息将具有 Sequential Offsets。主题的min.compaction.lag.ms可用于 保证在写入消息后必须经过最短时间长度,然后才能压缩消息。即,它为每条消息在 (未压缩的) head 中保留多长时间提供了一个下限。 主题的max.compaction.lag.ms可用于保证写入消息的时间与消息符合压缩条件的时间之间的最大延迟。
  2. 消息的顺序始终保持不变。Compaction 永远不会对消息重新排序,只会删除一些消息。
  3. 消息的偏移量永远不会改变。它是日志中某个位置的永久标识符。
  4. 任何从日志开头开始的使用者都将至少看到所有记录的最终状态(按写入顺序排列)。此外,如果 使用者到达日志头部的时间比主题的delete.retention.ms设置(默认值为 24 小时)。换句话说:由于删除标记发生了 在读取的同时,如果 DELETE 标记滞后超过delete.retention.ms.

日志压缩详细信息

日志压缩由日志清理器处理,日志清理器是一个后台线程池,用于重新复制日志段文件,从而删除其键出现在日志头中的记录。每个压实机螺纹的工作原理如下:
  1. 它选择对数头对数尾部比率最高的对数
  2. 它为日志头中的每个键创建最后一个偏移量的简洁摘要
  3. 它会从头到尾重新复制日志,删除日志中稍后出现的键。新的、干净的 Segment 会立即交换到日志中,因此所需的额外磁盘空间仅为 1 additional log segment(不是日志的完整副本)。
  4. log head 的摘要本质上只是一个空间紧凑的哈希表。每个条目正好使用 24 个字节。因此,使用 8GB 的清理缓冲区,一次清理迭代可以清理大约 366GB 的日志头 (假设 1k 条消息)。

配置 Log Cleaner

默认情况下,日志清理器处于启用状态。这将启动更干净的线程池。 要在特定主题上启用日志清理,请添加特定于日志的属性
log.cleanup.policy=compact
log.cleanup.policyproperty 是定义的代理配置设置 在代理的server.properties文件;它影响了所有主题 在集群中没有配置覆盖,如此处所述。 日志清理器可以配置为保留日志的未压缩 “head” 的最小量。这可以通过设置压缩时间滞后来启用。 这可用于防止更新于最小消息使用时间的消息受到压缩。如果未设置,则除最后一个 Segment (即当前 Segment) 外,所有日志 Segment 都有资格进行压缩 正在写入。即使活动分段的所有消息都早于最小压缩时间滞后,也不会压缩活动分段。 日志清理器可以配置为确保最大延迟,在此延迟之后,未压缩的日志 “head” 将符合日志压缩的条件。 这可用于防止低生成速率的日志在无限持续时间内保持不符合压缩条件。如果未设置,则不会压缩不超过 min.cleanable.dirty.ratio 的日志。 请注意,此压缩截止时间并不是硬性保证,因为它仍受 Log Cleaner 线程的可用性和实际压缩时间的影响。 您需要监控 uncleanable-partitions-count、max-clean-time-secs 和 max-compaction-delay-secs 指标。
log.cleaner.min.compaction.lag.ms
log.cleaner.max.compaction.lag.ms

此处介绍了进一步的 cleaner 配置。

4.9 配额

Kafka 集群能够对请求实施配额,以控制客户端使用的代理资源。两种类型 的客户端配额可由 Kafka 代理对共享配额的每组客户端强制执行:

  1. 网络带宽配额定义字节速率阈值(自 0.9 起)
  2. 请求速率配额将 CPU 利用率阈值定义为网络和 I/O 线程的百分比(自 0.11 起)

为什么需要配额

生产者和使用者可以生成/使用非常大量的数据,或者以非常高的 rate 并因此垄断了 broker 资源,导致网络饱和,并且通常会 DOS 其他客户端和 broker 本身。 拥有配额可以防止这些问题,并且在大型多租户集群中尤为重要,因为一小部分行为不良的客户端可能会降低行为良好的客户端的用户体验。 事实上,当将 Kafka 作为服务运行时,这甚至可以根据商定的合同强制执行 API 限制。

客户端组

Kafka 客户端的身份是用户主体,它表示安全集群中经过身份验证的用户。在支持未经身份验证的客户端的集群中,用户主体是一组未经身份验证的 用户 由代理使用可配置的PrincipalBuilder.Client-id 是客户端的逻辑分组,具有客户端应用程序选择的有意义的名称。元组 (user, client-id) 定义 共享 User Principal 和 Client-ID 的 Client 端的安全逻辑组。

配额可应用于 (user, client-id)、user 或 client-id 组。对于给定连接,将应用与连接匹配的最具体配额。配额组的所有连接共享为该组配置的配额。 例如,如果 (user=“test-user”, client-id=“test-client”) 的生产配额为 10MB/秒,则此配额将在客户端 ID 为“test-client”的用户“test-user”的所有生产者实例之间共享。

配额配置

可以为 (user, client-id)、user 和 client-id 组定义配额配置。可以在需要更高(甚至更低)配额的任何配额级别覆盖默认配额。 该机制类似于按主题日志配置覆盖。 用户和(用户、client-id)配额覆盖将写入 ZooKeeper 的 /config/users 下,client-id 配额覆盖将写入 /config/clients 下。 这些覆盖由所有代理读取,并立即生效。这样,我们就可以更改配额,而不必对整个集群进行滚动重启。有关详细信息,请参阅此处。 每个组的默认配额也可以使用相同的机制动态更新。

配额配置的优先顺序为:

  1. /config/users/<user>/clients/<client-id 中>
  2. /config/users/<user>/clients/<default>
  3. /config/users/<user>
  4. /config/users/<default>/clients/<client-id 中>
  5. /config/users/<default>/clients/<default>
  6. /config/users/<default>
  7. /config/clients/<client-id 中>
  8. /config/clients/<default>

网络带宽配额

网络带宽配额定义为共享配额的每组客户端的字节速率阈值。 默认情况下,每个唯一客户端组都会收到集群配置的固定配额(以字节/秒为单位)。 此配额是按代理定义的。每组客户端最多可以发布/获取 X 字节/秒 在客户端受到限制之前。

请求速率配额

请求速率配额定义为客户端可以在请求处理程序 I/O 上使用的时间百分比 配额时段内每个 broker 的线程和网络线程。n% 的配额表示一个线程的 n%,因此配额超出了 ((num.io.threads + num.network.threads) * 100)% 的总容量。 每组客户端可以在配额中的所有 I/O 和网络线程中使用最高 n% 的总百分比 窗口。由于分配给 I/O 和网络线程的线程数通常基于 根据 Broker 主机上的可用内核数,请求速率配额表示 CPU 的总百分比 可供共享配额的每组客户端使用。

执法

默认情况下,每个唯一客户端组都会收到集群配置的固定配额。 此配额是按代理定义的。每个客户端都可以在限制之前利用每个代理的此配额。我们认为为每个代理定义这些配额比 每个客户端具有固定的集群带宽,因为这需要一种在所有代理之间共享客户端配额使用的机制。这可能比配额实现本身更难做到正确!

代理在检测到配额冲突时如何反应?在我们的解决方案中,代理首先计算将违规客户端置于其配额以下所需的延迟量 并立即返回带有延迟的响应。如果是 fetch 请求,响应将不包含任何数据。然后,broker 将 channel 静音到 client, 不再处理来自客户端的请求,直到延迟结束。在收到延迟持续时间为非零的响应后,Kafka 客户端还将避免 在延迟期间向 broker 发送进一步的请求。因此,来自受限制的客户端的请求实际上会从两端被阻止。 即使使用不考虑 broker 的延迟响应的旧 client 实现,broker 通过静音其 socket 通道施加的背压也是如此 仍然可以处理行为不良的客户端的限制。那些向受限制的通道发送进一步请求的客户端只有在延迟结束后才会收到响应。

字节速率和线程利用率在多个小窗口(例如 30 个窗口,每个窗口 1 秒)上测量,以便快速检测和纠正配额冲突。通常,具有较大的测量窗口 (例如 10 个窗口,每个窗口 30 秒)会导致大量流量爆发,然后是长时间的延迟,这在用户体验方面不是很好。

5.1 网络层

网络层是一个相当简单的 NIO 服务器,不会详细描述。sendfile 实现是通过提供TransferableRecords接口 AwriteTo方法。这允许文件支持的消息集使用更高效的transferToimplementation 而不是进程内缓冲写入。线程模型是单个接收器线程和 N 个处理器线程,每个线程处理固定数量的连接。此设计已在其他地方进行了相当彻底的测试,并发现易于实现且快速。该协议保持非常简单,以便将来以其他语言实现 Client 端。

5.2 消息

消息由可变长度标头、可变长度不透明键字节数组和可变长度不透明值字节数组组成。以下部分介绍了标头的格式。 保持 key 和 value 不透明是正确的决定:现在 serialization libraries 取得了很大的进展,任何特定的选择都不太可能适合所有用途。不用说,使用 Kafka 的特定应用程序可能会强制要求使用特定的序列化类型作为其使用的一部分。这RecordBatchinterface 只是一个消息迭代器,具有用于批量读取和写入 NIO 的专用方法Channel.

5.3 消息格式

消息(又名 Records)总是批量写入。消息批次的技术术语是记录批次,记录批次包含一个或多个记录。在退化情况下,我们可以有一个包含单个记录的记录批处理。 记录批处理和记录有自己的标题。每个格式如下所述。

5.3.1 批量记录

以下是 RecordBatch 的磁盘格式。

baseOffset: int64
batchLength: int32
partitionLeaderEpoch: int32
magic: int8 (current magic value is 2)
crc: int32
attributes: int16
    bit 0~2:
        0: no compression
        1: gzip
        2: snappy
        3: lz4
        4: zstd
    bit 3: timestampType
    bit 4: isTransactional (0 means not transactional)
    bit 5: isControlBatch (0 means not a control batch)
    bit 6: hasDeleteHorizonMs (0 means baseTimestamp is not set as the delete horizon for compaction)
    bit 7~15: unused
lastOffsetDelta: int32
baseTimestamp: int64
maxTimestamp: int64
producerId: int64
producerEpoch: int16
baseSequence: int32
records: [Record]

请注意,启用压缩后,压缩的记录数据将直接在记录数计数之后进行序列化。

CRC 涵盖从属性到批处理末尾的数据(即 CRC 之后的所有字节)。它位于 magic byte 之后,该 magic byte 意味着客户端必须先解析 magic byte,然后才能决定如何解释 batch length 和 magic byte 之间的字节。分区领导者 epoch 字段不包含在 CRC 计算中,以避免在为接收的每个批次分配此字段时需要重新计算 CRC 经纪人。CRC-32C (Castagnoli) 多项式用于计算。

压缩时:与旧的消息格式不同,magic v2 及更高版本在清理日志时保留原始批处理的第一个和最后一个偏移量/序列号。这是必需的,以便能够恢复 重新加载日志时的 producer 状态。例如,如果我们没有保留最后一个序列号,那么在分区领导失败后,生产者可能会看到 OutOfSequence 错误。基本序列号必须 保留以进行重复检查(代理通过验证传入批处理的第一个和最后一个序列号是否与该生产者的最后一个序列号匹配来检查传入的 Produce 请求是否存在重复项)。因此, 当 Batch 中的所有记录都已清理,但仍保留 Batch 以保留生产者的最后一个序列号时,日志中可能会有空 Batch。这里的一个奇怪之处在于 baseTimestamp 字段在压缩过程中不会保留,因此如果压缩掉批处理中的第一条记录,它将发生变化。

如果记录批处理包含具有 null 有效负载或中止事务标记的记录,则 Compaction 还可以修改 baseTimestamp。baseTimestamp 将设置为应删除这些记录的时间戳 还设置了 Delete horizon 属性位。

5.3.1.1 控制批次

控制批处理包含一条称为控制记录的记录。不应将控制记录传递给应用程序。相反,使用者使用它们来筛选掉中止的事务性消息。

控制记录的 key 符合以下架构:

version: int16 (current version is 0)
type: int16 (0 indicates an abort marker, 1 indicates a commit)

控制记录值的架构取决于类型。该值对客户端不透明。

5.3.2 记录

记录级标头是在 Kafka 0.11.0 中引入的。下面描述了带有 Headers 的记录的磁盘格式。

length: varint
attributes: int8
    bit 0~7: unused
timestampDelta: varlong
offsetDelta: varint
keyLength: varint
key: byte[]
valueLen: varint
value: byte[]
Headers => [Header]
5.3.2.1 记录头
headerKeyLength: varint
headerKey: String
headerValueLength: varint
Value: byte[]

我们使用与 Protobuf 相同的 varint 编码。有关后者的更多信息,请点击此处。记录中的标题计数 也被编码为 varint。

5.3.3 旧消息格式

在 Kafka 0.11 之前,消息被传输并存储在消息集中。在消息集中,每条消息都有自己的元数据。请注意,尽管消息集表示为数组, 它们前面没有 int32 数组大小,就像协议中的其他数组元素一样。

消息集:
MessageSet (Version: 0) => [offset message_size message]
offset => INT64
message_size => INT32
message => crc magic_byte attributes key value
    crc => INT32
    magic_byte => INT8
    attributes => INT8
        bit 0~2:
            0: no compression
            1: gzip
            2: snappy
        bit 3~7: unused
    key => BYTES
    value => BYTES
MessageSet (Version: 1) => [offset message_size message]
offset => INT64
message_size => INT32
message => crc magic_byte attributes timestamp key value
    crc => INT32
    magic_byte => INT8
    attributes => INT8
        bit 0~2:
            0: no compression
            1: gzip
            2: snappy
            3: lz4
        bit 3: timestampType
            0: create time
            1: log append time
        bit 4~7: unused
    timestamp => INT64
    key => BYTES
    value => BYTES

在 Kafka 0.10 之前的版本中,唯一支持的消息格式版本(在 magic 值中表示)是 0。消息格式版本 1 是在版本 0.10 中引入的时间戳支持。

  • 与上面的版本 2 类似,属性的最低位表示压缩类型。
  • 在版本 1 中,生产者应始终将时间戳类型位设置为 0。如果 topic 配置为使用日志追加时间, (通过代理级配置 log.message.timestamp.type = LogAppendTime 或主题级配置 message.timestamp.type = LogAppendTime), Broker 将覆盖消息集中的 Timestamp Type 和 Timestamp。
  • 属性的最高位必须设置为 0。

在消息格式版本 0 和 1 中,Kafka 支持递归消息以启用压缩。在这种情况下,必须设置消息的属性 以指示其中一种压缩类型,并且 value 字段将包含使用该类型压缩的消息集。我们经常参考 将嵌套消息指定为 “inner messages”,将包装消息视为 “outer message”。请注意,键应为 null ,其偏移量将是最后一条内部消息的偏移量。

当收到递归版本 0 消息时,代理会解压缩这些消息,并为每个内部消息单独分配一个偏移量。 在版本 1 中,为避免服务器端重新压缩,将仅为包装器消息分配偏移量。内部信息 将具有相对偏移量。绝对偏移量可以使用与外部消息的偏移量来计算,该偏移量对应于 设置为分配给最后一条内部消息的偏移量。

crc 字段包含后续消息字节的 CRC32(而不是 CRC-32C)(即从魔术字节到值)。

5.4 日志

一个名为 “my-topic” 的主题的日志有两个分区,由两个目录组成(即my-topic-0my-topic-1) 填充包含该主题消息的数据文件。日志文件的格式是一系列 “log entries” ;每个日志条目都是一个 4 字节的整数 N,用于存储消息长度,后跟 N 个消息字节。每条消息都由一个 64 位整数偏移量唯一标识,该偏移量给出了该消息开头的字节位置,该偏移量在该分区上发送到该主题的所有消息流中。每条消息的磁盘格式如下。每个日志文件都以其包含的第一条消息的偏移量命名。因此,创建的第一个文件将是 00000000000000000000.log,并且每个附加文件将具有一个整数名称,大约来自前一个文件的 S 字节,其中 S 是配置中给定的最大日志文件大小。

记录的确切二进制格式作为标准接口进行版本控制和维护,因此可以在生产者、代理和客户端之间传输记录批次,而无需在需要时重新复制或转换。上一节包含有关记录的磁盘格式的详细信息。

使用 message offset 作为消息 ID 是不常见的。我们最初的想法是使用生产者生成的 GUID,并在每个代理上维护从 GUID 到 offset 的映射。但是,由于使用者必须维护每个服务器的 ID,因此 GUID 的全局唯一性没有提供任何值。此外,维护从随机 ID 到偏移量的 Map 的复杂性需要一个重量级的索引结构,该结构必须与磁盘同步,本质上需要一个完整的持久随机访问数据结构。因此,为了简化查找结构,我们决定使用一个简单的每个分区原子计数器,它可以与分区 ID 和节点 ID 耦合来唯一标识消息;这使得查找结构更简单,尽管每个使用者请求仍可能有多个 looked。然而,一旦我们确定了一个计数器,直接使用偏移量似乎是很自然的——毕竟两者都是分区独有的单调递增整数。由于偏移量对使用者 API 是隐藏的,因此此决定最终是一个实现细节,我们采用了更高效的方法。

日志允许串行附加,这些附加总是转到最后一个文件。当此文件达到可配置的大小(例如 1GB)时,该文件将滚动到新文件。日志采用两个配置参数:M,它提供在强制 OS 将文件刷新到磁盘之前要写入的消息数,以及 S,它提供强制刷新的秒数。这提供了持久性保证,在系统崩溃时最多丢失 M 条消息或 S 秒的数据。

通过给出消息的 64 位逻辑偏移量和 S 字节最大块大小来完成读取。这将返回 S 字节缓冲区中包含的消息的迭代器。S 旨在大于任何单个消息,但在消息异常大的情况下,可以重试多次读取,每次将缓冲区大小增加一倍,直到成功读取消息。可以指定最大消息和缓冲区大小,以使服务器拒绝大于某个大小的消息,并给客户端一个 Client 端一个最大读取量的绑定,以获得完整的消息。读取缓冲区很可能以部分消息结尾,这很容易通过大小定界来检测。

从 offset 读取的实际过程需要首先找到存储数据的 log segment 文件,根据全局 offset 值计算特定于文件的 offset,然后从该文件 offset 中读取。搜索是针对为每个文件维护的内存中范围的简单二进制搜索变体完成的。

该日志提供了获取最近写入的消息的功能,以允许客户端从“现在”开始订阅。当使用者未能在 SLA 指定的天数内使用其数据时,这也很有用。在这种情况下,当客户端尝试使用不存在的偏移量时,它会得到一个 OutOfRangeException,并且可能会根据用例重置自身或失败。

以下是发送给使用者的结果的格式。

MessageSetSend (fetch result)

total length     : 4 bytes
error code       : 2 bytes
message 1        : x bytes
...
message n        : x bytes
MultiMessageSetSend (multiFetch result)

total length       : 4 bytes
error code         : 2 bytes
messageSetSend 1
...
messageSetSend n

删除

一次删除一个日志段的数据。日志管理器应用两个指标来识别 Segment,它们是 符合删除条件:时间和大小。对于基于时间的策略,将考虑记录时间戳,其中 区段文件中的最大时间戳(记录顺序无关紧要)定义 整个 segment。默认情况下,基于大小的保留处于禁用状态。启用后,日志管理器会不断删除 最旧的 segment 文件,直到分区的整体大小再次在配置的限制范围内。如果两者都 策略,则由于任一策略而符合删除条件的区段将为 删除。为了避免锁定读取,同时仍然允许修改 segment 列表的删除,我们使用 copy-on-write style segment list 实现,该实现提供一致的视图以允许在 删除过程中日志段的不可变静态快照视图。

保证

日志提供了一个配置参数 M,该参数控制在强制刷新到磁盘之前写入的最大消息数。启动时,将运行一个日志恢复进程,该进程将迭代最新日志分段中的所有消息,并验证每个消息条目是否有效。如果消息的大小和偏移量之和小于文件的长度,并且消息负载的 CRC32 与消息中存储的 CRC 匹配,则消息条目有效。如果检测到损坏,日志将被截断为最后一个有效偏移量。

请注意,必须处理两种损坏:由于崩溃而丢失未写入块的截断,以及将无意义的块添加到文件中的损坏。这样做的原因是,一般来说,作系统不保证文件 inode 和实际块数据之间的写入顺序,因此,如果 inode 更新为新大小,则除了丢失写入数据外,文件还可能获得无意义的数据,但在写入包含该数据的块之前发生崩溃。CRC 检测到这种极端情况,并防止它损坏日志(尽管未写的消息当然会丢失)。

5.5 分发

消费者偏移跟踪

Kafka 使用者跟踪它在每个分区中消耗的最大偏移量,并能够提交偏移量,因此 它可以在重新启动时从这些偏移量中恢复。Kafka 提供了存储 指定代理(对于该组)中的给定使用者组,称为组协调器。即任何使用者实例 在该 Consumer 组中,应将其偏移量提交和提取发送到该组协调器 (Broker)。消费组是 根据 Coordinator 的组名称分配给 Coordinator。消费者可以通过发出 FindCoordinatorRequest 来查找其协调器 到任何 Kafka 代理,并读取 FindCoordinatorResponse,其中将包含协调器详细信息。消费者 然后,可以继续从 Coordinator broker 提交或获取偏移量。如果协调器移动,使用者将 需要重新发现协调器。偏移提交可以自动完成,也可以由使用者实例手动完成。

当组协调器收到 OffsetCommitRequest 时,它会将请求附加到名为 __consumer_offsets 的特殊压缩 Kafka 主题。 只有在 offsets topic 的所有副本都收到 offset 后,broker 才会向 Consumer 发送成功的 offset commit 响应。 如果偏移量未能在可配置的超时时间内复制,则偏移量提交将失败,使用者可以在退出后重试提交。 代理会定期压缩 offsets 主题,因为它只需要维护每个分区的最新 offset 提交。 协调器还将偏移量缓存在内存中的表中,以便快速提供偏移量获取。

当协调器收到偏移量获取请求时,它只会从 offsets 缓存中返回最后提交的偏移量向量。 如果 coordinator 刚刚启动,或者它刚刚成为一组新的消费者组的协调器(通过成为 offsets 主题的分区的领导者), 它可能需要将 offsets 主题分区加载到缓存中。在这种情况下,偏移量获取将失败,并显示 CoordinatorLoadInProgressException 的 CoordinatorLoadInProgressException,并且使用者可以在回退后重试 OffsetFetchRequest。

ZooKeeper 目录

下面给出了用于在消费者和代理之间进行协调的 ZooKeeper 结构和算法。

表示法

当路径中的元素被表示时[xyz],这意味着 xyz 的值不是固定的,实际上 xyz 的每个可能值都有一个 ZooKeeper znode。例如/topics/[topic]将是名为 /topics 的目录,其中包含每个主题名称的子目录。还给出了数值范围,例如[0...5]以指示子目录 0、1、2、3、4。箭头用于指示 znode 的内容。例如->/hello -> world将指示包含值 “world” 的 znode /hello。

Broker 节点注册表

/brokers/ids/[0...N] --> {"jmx_port":...,"timestamp":...,"endpoints":[...],"host":...,"version":...,"port":...} (ephemeral node)

这是所有现有代理节点的列表,每个代理节点都提供了一个唯一的逻辑代理 ID,用于向使用者标识它(必须作为其配置的一部分提供)。启动时,代理节点通过在 /brokers/ids 下创建具有逻辑代理 ID 的 znode 来注册自身。逻辑代理 ID 的用途是允许将代理移动到其他物理计算机,而不会影响使用者。尝试注册已在使用的代理 ID(例如,因为两个服务器配置了相同的代理 ID)会导致错误。

由于代理使用临时 znodes 在 ZooKeeper 中注册自身,因此此注册是动态的,如果代理关闭或死亡(从而通知使用者它不再可用),则此注册将消失。

Broker Topic 注册表

/brokers/topics/[topic]/partitions/[0...N]/state --> {"controller_epoch":...,"leader":...,"version":...,"leader_epoch":...,"isr":[...]} (ephemeral node)

每个代理在其维护的主题下注册自身,并存储该主题的分区数。

集群 ID

集群 ID 是分配给 Kafka 集群的唯一且不可变的标识符。群集 ID 最多可以有 22 个字符,允许的字符由正则表达式 [a-zA-Z0-9_\-]+ 定义,该表达式对应于 URL 安全型 Base64 变体使用的字符,没有填充。从概念上讲,它是在首次启动集群时自动生成的。

在实现方面,它是在首次成功启动版本 0.10.1 或更高版本的代理时生成的。代理尝试从/cluster/idznode 的如果 znode 不存在,则代理将生成新的群集 ID,并使用此群集 ID 创建 znode。

代理节点注册

代理节点基本上是独立的,因此它们只发布有关他们所拥有的信息。当 broker 加入时,它会在 broker node registry 目录下注册自身,并写入有关其主机名和端口的信息。代理还在 Broker 主题注册表中注册现有主题及其逻辑分区的列表。在 broker 上创建新主题时,将动态注册这些主题。

7.1 安全概述

在版本 0.9.0.0 中,Kafka 社区添加了许多功能,这些功能可以单独使用,也可以一起使用,从而提高 Kafka 集群的安全性。目前支持以下安全措施:
  1. 使用 SSL 或 SASL 对来自客户端(生产者和使用者)、其他代理和工具的代理连接进行身份验证。Kafka 支持以下 SASL 机制:
    • SASL/GSSAPI (Kerberos) - 从版本 0.9.0.0 开始
    • SASL/PLAIN - 从版本 0.10.0.0 开始
    • SASL/SCRAM-SHA-256 和 SASL/SCRAM-SHA-512 - 从版本 0.10.2.0 开始
    • SASL/OAUTHBEARER - 从版本 2.0 开始
  2. 对从 broker 到 ZooKeeper 的连接进行身份验证
  3. 使用 SSL 对在代理和客户端之间、代理之间或代理和工具之间传输的数据进行加密(请注意,启用 SSL 时性能会下降,其大小取决于 CPU 类型和 JVM 实现。
  4. 客户端对读/写作的授权
  5. 授权是可插拔的,并且支持与外部授权服务集成
值得注意的是,安全性是可选的 - 支持不安全的集群,以及经过身份验证、未经身份验证、加密和非加密客户端的混合。 以下指南介绍了如何在客户端和代理中配置和使用安全功能。

7.2 侦听器配置

为了保护 Kafka 集群,有必要保护用于 与服务器通信。每个服务器都必须定义一组侦听器,这些侦听器用于 接收来自客户端和其他服务器的请求。每个侦听器都可以配置 使用各种机制对客户端进行身份验证,并确保 server 和 Client 端进行加密。本节提供了配置的入门 的监听者。

Kafka 服务器支持侦听多个端口上的连接。这是通过 这listeners属性,该属性接受以逗号分隔的 要启用的侦听器列表。必须在每个服务器上至少定义一个侦听器。格式 中定义的每个侦听器listeners如下所示:

{LISTENER_NAME}://{hostname}:{port}

LISTENER_NAME通常是一个描述性名称,用于定义 侦听器。例如,许多配置对客户端流量使用单独的侦听器, 因此,它们可能会将相应的侦听器称为CLIENT在配置中:

listeners=CLIENT://localhost:9092

每个侦听器的安全协议在单独的配置中定义:listener.security.protocol.map.该值是一个逗号分隔的列表 映射到其安全协议的每个侦听器。例如,follow 值 配置指定CLIENTlistener 将使用 SSL,而BROKERlistener 将使用 plaintext 来执行。

listener.security.protocol.map=CLIENT:SSL,BROKER:PLAINTEXT

安全协议的可能选项(不区分大小写)如下所示:

  1. 明文
  2. SSL认证
  3. SASL_PLAINTEXT
  4. SASL_SSL

纯文本协议不提供安全性,不需要任何其他配置。 在以下部分中,本文档介绍如何配置其余协议。

如果每个必需的侦听器都使用单独的安全协议,也可以使用 Security Protocol name 作为listeners.使用上面的示例, 我们可以跳过CLIENTBROKER监听者 使用以下定义:

listeners=SSL://localhost:9092,PLAINTEXT://localhost:9093

但是,我们建议用户为侦听器提供显式名称,因为它 使每个侦听器的预期用途更加清晰。

在此列表中的侦听器中,可以声明要用于 代理间通信,方法是将inter.broker.listener.name配置 设置为侦听器的名称。代理间侦听器的主要用途是 分区复制。如果未定义,则确定代理间侦听器 由security.inter.broker.protocol哪 默认为PLAINTEXT.

对于依赖 Zookeeper 存储集群元数据的遗留集群,可以 声明一个单独的侦听器,用于从活动控制器传播元数据 到经纪人。这是由control.plane.listener.name.主动控制器 当需要将元数据更新推送到集群中的 broker 时,将使用此侦听器。 使用 control plane 侦听器的好处是它使用单独的处理线程 这使得应用程序流量不太可能阻碍元数据更改的及时传播 (例如分区领导者和 ISR 更新)。请注意,默认值为 null,即 表示控制器将使用由inter.broker.listener

在 KRaft 集群中,broker 是具有broker已启用角色 在process.roles控制器是具有controller已启用角色。侦听器配置取决于角色。由inter.broker.listener.name专门用于 broker 之间的请求。 另一方面,控制器必须使用单独的侦听器,它由controller.listener.names配置。这不能设置为相同的 值作为代理间侦听器。

控制器接收来自其他控制器和 broker 的请求。为 因此,即使服务器没有controller已启用角色 (即它只是一个 broker),它仍然必须定义控制器侦听器以及 配置它所需的任何 security 属性。例如,我们可能 在独立代理上使用以下配置:

process.roles=broker
listeners=BROKER://localhost:9092
inter.broker.listener.name=BROKER
controller.quorum.voters=0@localhost:9093
controller.listener.names=CONTROLLER
listener.security.protocol.map=BROKER:SASL_SSL,CONTROLLER:SASL_SSL

在此示例中,控制器侦听器仍配置为使用SASL_SSLsecurity 协议,但它不包含在listeners由于经纪人 不公开控制器侦听器本身。在这种情况下将使用的端口 来自controller.quorum.votersconfiguration,它定义了 控制器的完整列表。

对于同时启用了 broker 和 controller 角色的 KRaft 服务器,配置 类似。唯一的区别是控制器侦听器必须包含在listeners:

process.roles=broker,controller
listeners=BROKER://localhost:9092,CONTROLLER://localhost:9093
inter.broker.listener.name=BROKER
controller.quorum.voters=0@localhost:9093
controller.listener.names=CONTROLLER
listener.security.protocol.map=BROKER:SASL_SSL,CONTROLLER:SASL_SSL

这是 中定义的端口的要求controller.quorum.voters自 完全匹配一个公开的 Controller 侦听器。例如,此处的CONTROLLERlistener 绑定到 9093 端口。连接字符串 定义者controller.quorum.voters然后还必须使用端口 9093, 就像这里一样。

控制器将接受对controller.listener.names. 通常只有一个控制器侦听器,但可以有多个。 例如,这提供了一种将活动侦听器从一个端口或安全性更改的方法 协议传递给另一个集群的 roll(一个 roll 公开新的侦听器, 和 1 次滚动以删除旧的侦听器)。当定义了多个控制器侦听器时, 列表中的第一个 ID 将用于出站请求。

在 Kafka 中,通常为客户端使用单独的侦听器。这允许 集群间侦听器在网络级别隔离。在控制器的情况下 listener 中,监听器应该被隔离,因为客户端不能使用它 无论如何。客户端应连接到代理上配置的任何其他侦听器。 发送给控制器的任何请求都将按如下所述转发

在下一节中,本文档将介绍如何启用 SSL 在侦听器上进行加密和身份验证。然后,下一部分将 涵盖使用 SASL 的其他身份验证机制。

7.3 使用 SSL 进行加密和身份验证

Apache Kafka 允许客户端使用 SSL 进行流量加密和身份验证。默认情况下,SSL 处于禁用状态,但可以根据需要打开 SSL。 以下段落详细介绍了如何设置您自己的 PKI 基础设施,使用它来创建证书,并配置 Kafka 以使用这些证书。
  1. 为每个 Kafka 代理生成 SSL 密钥和证书

    部署一个或多个支持 SSL 的代理的第一步是为每个服务器生成一个公钥/私钥对。 由于 Kafka 希望所有密钥和证书都存储在密钥库中,因此我们将使用 Java 的 keytool 命令来完成此任务。 该工具支持两种不同的密钥库格式,一种是 Java 特定的 jks 格式(现已弃用)以及 PKCS12。 PKCS12 是 Java 版本 9 的默认格式,以确保无论使用的 Java 版本如何,都使用此格式 命令显式指定 PKCS12 格式。 您需要在上述命令中指定两个参数:
    > keytool -keystore {keystorefile} -alias localhost -validity {validity} -genkey -keyalg RSA -storetype pkcs12
    1. keystorefile:存储此代理的密钥(以及后来的证书)的密钥库文件。密钥库文件包含私有的 和该 broker 的公钥,因此需要保持安全。理想情况下,此步骤在密钥为 用于,因为此密钥绝不应传输/离开其目标服务器。
    2. Validity:Key 的有效时间,单位为 天。请注意,这与证书的有效期不同,后者 将在 签署证书 中确定。您可以使用同一个 key 请求多个 证书:如果您的密钥有效期为 10 年,但您的 CA 只会签署有效期为 1 年的证书,则您 随着时间的推移,可以将同一密钥用于 10 个证书。

    要获取可与刚刚创建的私有密钥一起使用的证书,需要创建证书签名请求。这 签名请求时,如果由受信任的 CA 签名,则会产生实际的证书,该证书随后可以安装在密钥库中并用于 身份验证目的。
    要生成证书签名请求,请对到目前为止创建的所有服务器密钥库运行以下命令。 此命令假定您要将主机名信息添加到证书中,如果不是这种情况,则可以省略 extension 参数
    > keytool -keystore server.keystore.jks -alias localhost -validity {validity} -genkey -keyalg RSA -destkeystoretype pkcs12 -ext SAN=DNS:{FQDN},IP:{IPADDRESS1}
    -ext SAN=DNS:{FQDN},IP:{IPADDRESS1}.有关这方面的更多信息,请参阅下文。
    主机名验证
    启用主机名验证后,是检查您所在的服务器提供的证书中的属性的过程 连接到该服务器的实际主机名或 IP 地址,以确保您确实连接到正确的服务器。
    此检查的主要原因是为了防止中间人攻击。 对于 Kafka,此检查默认处于禁用状态已很长时间,但从 Kafka 2.0.0 开始,默认情况下启用服务器的主机名验证 用于客户端连接以及代理间连接。
    可以通过设置
    ssl.endpoint.identification.algorithm转换为空字符串。
    对于动态配置的代理侦听器,可以使用
    kafka-configs.sh:
    > bin/kafka-configs.sh --bootstrap-server localhost:9093 --entity-type brokers --entity-name 0 --alter --add-config "listener.name.internal.ssl.endpoint.identification.algorithm="

    注意:

    通常,除了它是 “Just get it to work” 的最快方法之外,没有充分的理由禁用主机名验证 通过承诺 “以后有更多时间修复它 ”!
    在正确的时间完成正确的主机名验证并不难,但是一旦集群启动并且 跑步 - 帮自己一个忙,现在就去做吧!

    如果启用了主机名验证,则客户端将根据以下两个字段之一验证服务器的完全限定域名 (FQDN) 或 IP 地址:

    1. 通用名称 (CN)
    2. 使用者备用名称 (SAN)

    虽然 Kafka 会检查这两个字段,但自 2000 年以来,已弃用使用公用名字段进行主机名验证,应尽可能避免使用。此外, SAN 字段更加灵活,允许在证书中声明多个 DNS 和 IP 条目。
    另一个优点是,如果 SAN 字段用于主机名验证,则可以将 common name 设置为更有意义的值 授权目的。由于我们需要将 SAN 字段包含在签名证书中,因此在生成 签名请求。也可以在生成密钥对时指定它,但这不会自动复制到签名请求中。
    要添加 SAN 字段,请附加以下参数
    -ext SAN=DNS:{FQDN},IP:{IPADDRESS}到 keytool 命令中:
    > keytool -keystore server.keystore.jks -alias localhost -validity {validity} -genkey -keyalg RSA -destkeystoretype pkcs12 -ext SAN=DNS:{FQDN},IP:{IPADDRESS1}
  2. 创建您自己的 CA

    在此步骤之后,集群中的每台计算机都有一个公钥/私钥对,该密钥对已经可用于加密流量和一个证书 签名请求,这是创建证书的基础。要添加身份验证功能,需要对此签名请求进行签名 由受信任的颁发机构创建。

    证书颁发机构 (CA) 负责对证书进行签名。CA 的工作方式类似于颁发护照的政府 - 政府 在每本护照上盖章(签名),使护照难以伪造。其他国家政府会验证印章,以确保护照是 真实。同样,CA 对证书进行签名,而加密技术保证签名证书在计算上难以 伪造。因此,只要 CA 是真实且值得信赖的权威机构,客户就可以强烈保证他们正在连接到真实的 机器。

    在本指南中,我们将成为我们自己的证书颁发机构。在企业环境中设置生产集群时,这些证书将 通常由整个公司信任的公司 CA 签名。请参阅 常见陷阱 生产 对于这种情况需要考虑的一些事情。

    由于 OpenSSL 中的一个错误,x509 模块不会复制请求的 extension 字段添加到最终证书中。由于我们希望 SAN 扩展出现在我们的证书中以启用主机名 验证,我们将改用 CA 模块。这需要在我们生成 CA 密钥对。
    将以下清单保存到名为 openssl-ca.cnf 的文件中,并根据需要调整 validity 和 common 属性的值。

    HOME            = .
    RANDFILE        = $ENV::HOME/.rnd
    
    ####################################################################
    [ ca ]
    default_ca    = CA_default      # The default ca section
    
    [ CA_default ]
    
    base_dir      = .
    certificate   = $base_dir/cacert.pem   # The CA certifcate
    private_key   = $base_dir/cakey.pem    # The CA private key
    new_certs_dir = $base_dir              # Location for new certs after signing
    database      = $base_dir/index.txt    # Database index file
    serial        = $base_dir/serial.txt   # The current serial number
    
    default_days     = 1000         # How long to certify for
    default_crl_days = 30           # How long before next CRL
    default_md       = sha256       # Use public key default MD
    preserve         = no           # Keep passed DN ordering
    
    x509_extensions = ca_extensions # The extensions to add to the cert
    
    email_in_dn     = no            # Don't concat the email in the DN
    copy_extensions = copy          # Required to copy SANs from CSR to cert
    
    ####################################################################
    [ req ]
    default_bits       = 4096
    default_keyfile    = cakey.pem
    distinguished_name = ca_distinguished_name
    x509_extensions    = ca_extensions
    string_mask        = utf8only
    
    ####################################################################
    [ ca_distinguished_name ]
    countryName         = Country Name (2 letter code)
    countryName_default = DE
    
    stateOrProvinceName         = State or Province Name (full name)
    stateOrProvinceName_default = Test Province
    
    localityName                = Locality Name (eg, city)
    localityName_default        = Test Town
    
    organizationName            = Organization Name (eg, company)
    organizationName_default    = Test Company
    
    organizationalUnitName         = Organizational Unit (eg, division)
    organizationalUnitName_default = Test Unit
    
    commonName         = Common Name (e.g. server FQDN or YOUR name)
    commonName_default = Test Name
    
    emailAddress         = Email Address
    emailAddress_default = test@test.com
    
    ####################################################################
    [ ca_extensions ]
    
    subjectKeyIdentifier   = hash
    authorityKeyIdentifier = keyid:always, issuer
    basicConstraints       = critical, CA:true
    keyUsage               = keyCertSign, cRLSign
    
    ####################################################################
    [ signing_policy ]
    countryName            = optional
    stateOrProvinceName    = optional
    localityName           = optional
    organizationName       = optional
    organizationalUnitName = optional
    commonName             = supplied
    emailAddress           = optional
    
    ####################################################################
    [ signing_req ]
    subjectKeyIdentifier   = hash
    authorityKeyIdentifier = keyid,issuer
    basicConstraints       = CA:FALSE
    keyUsage               = digitalSignature, keyEncipherment
    然后创建一个数据库和序列号文件,这些文件将用于跟踪哪些证书是用这个 CA 签名的。两者 这些只是与 CA 密钥位于同一目录中的文本文件。 完成这些步骤后,您现在可以生成 CA,该 CA 将用于稍后对证书进行签名。 CA 只是一个公钥/私钥对和证书,它由自身签名,仅用于对其他证书进行签名。
    此密钥对应保持非常安全,如果有人获得访问权限,他们可以创建并签署您的信任证书 基础设施,这意味着当连接到信任此 CA 的任何服务时,它们将能够模拟任何人。
    下一步是将生成的 CA 添加到客户端的信任库中,以便客户端可以信任此 CA:注意:如果您通过在 Kafka 代理配置中将 ssl.client.auth 设置为“requested”或“required”来将 Kafka 代理配置为需要客户端身份验证那么,您还必须为 Kafka 代理提供一个信任库,并且它应该具有 客户端密钥签名的所有 CA 证书。 与步骤 1 中存储每台计算机自身身份的密钥库不同,客户端的信任库存储所有证书 客户应该信任的。将证书导入信任库还意味着信任由该信任库签名的所有证书 证书。如上所示,信任政府 (CA) 也意味着信任它签发的所有护照(证书)。这 属性称为信任链,在大型 Kafka 集群上部署 SSL 时,它特别有用。您可以对所有证书进行签名 在具有单个 CA 的集群中,并让所有计算机共享信任该 CA 的同一信任库。这样,所有计算机都可以对所有 其他机器。
    > echo 01 > serial.txt
    > touch index.txt
    > openssl req -x509 -config openssl-ca.cnf -newkey rsa:4096 -sha256 -nodes -out cacert.pem -outform PEM
    > keytool -keystore client.truststore.jks -alias CARoot -import -file ca-cert
    > keytool -keystore server.truststore.jks -alias CARoot -import -file ca-cert
  3. 对证书进行签名

    然后使用 CA 对其进行签名:最后,您需要将 CA 的证书和签名证书都导入到密钥库中:参数的定义如下:
    > openssl ca -config openssl-ca.cnf -policy signing_policy -extensions signing_req -out {server certificate} -infiles {certificate signing request}
    > keytool -keystore {keystore} -alias CARoot -import -file {CA certificate}
    > keytool -keystore {keystore} -alias localhost -import -file cert-signed
    1. keystore:密钥库的位置
    2. CA certificate:CA 的证书
    3. 证书签名请求:使用服务器密钥创建的 CSR
    4. 服务器证书:要将服务器的签名证书写入的文件
    这将为您留下一个名为 truststore.jks 的信任库 - 这对于所有客户端和代理都是相同的,但不会 包含任何敏感信息,因此无需保护此信息。
    此外,每个节点将有一个 server.keystore.jks 文件,其中包含该节点的密钥、证书和您的 CA 证书。 有关如何使用这些文件的信息,请参阅配置 Kafka 代理和配置 Kafka 客户端

    有关此主题的一些工具帮助,请查看 easyRSA 项目,该项目具有 有大量的脚本来帮助完成这些步骤。

    PEM 格式的 SSL 密钥和证书
    从 2.7.0 开始,可以直接在配置中以 PEM 格式为 Kafka 代理和客户端配置 SSL 密钥和信任存储。 这避免了在文件系统上存储单独文件的需要,并受益于 Kafka 配置的密码保护功能。 除了 JKS 和 PKCS12 之外,PEM 还可以用作基于文件的密钥和信任存储的存储类型。要直接在 broker 或 client 配置中,应在ssl.keystore.key和 PEM 格式的证书链 应在ssl.keystore.certificate.chain.要配置信任存储,请信任证书,例如 CA 的公有证书, 应在ssl.truststore.certificates.由于 PEM 通常存储为多行 base-64 字符串,因此配置值 可以作为多行字符串包含在 Kafka 配置中,其中行以反斜杠 ('\') 结尾以表示行继续。

    存储密码配置ssl.keystore.passwordssl.truststore.password不用于 PEM。 如果私钥使用密码加密,则必须在ssl.key.password.可以提供私钥 以未加密的形式,没有密码。在生产部署中,配置应该被加密或 在这种情况下,使用 Kafka 中的密码保护功能进行外部化。请注意,默认的 SSL 引擎工厂的解密功能有限 加密的私钥(当使用 OpenSSL 等外部工具进行加密时)。像 BouncyCastle 这样的第三方库可以与 习惯SslEngineFactory以支持更广泛的加密私钥。

  4. 生产中的常见陷阱

    以上段落显示了创建自己的 CA 并使用它为集群签署证书的过程。 虽然对于沙盒、开发、测试和类似系统非常有用,但这通常不是为生产创建证书的正确过程 企业环境中的集群。 企业通常会运营自己的 CA,用户可以发送 CSR 以使用此 CA 进行签名,这样做的好处是用户不会 负责维护 CA 的安全以及每个人都可以信任的中央机构。 但是,它也剥夺了用户对签署证书过程的大量控制权。很多时候,经营公司的人 CA 将对证书应用严格限制,这些限制在尝试将这些证书与 Kafka 一起使用时可能会导致问题。
    1. 扩展密钥使用
      证书可能包含扩展名 字段,该字段控制证书的用途。如果此字段为空,则对用法没有限制, 但是,如果此处指定了任何用法,则有效的 SSL 实现必须强制执行这些用法。
      Kafka 的相关用法包括:
      • 客户端身份验证
      • 服务器认证
      Kafka 代理需要允许这两种用法,因为对于集群内通信,每个代理都将同时充当客户端和 服务器指向其他 broker。公司 CA 拥有 Web 服务器的签名配置文件并将其用于 Kafka 的情况并不少见 嗯,它将仅包含 serverAuth 用法值,并导致 SSL 握手失败。
    2. 中间证书
      出于安全原因,公司根 CA 通常保持脱机状态。为了实现日常使用,创建了所谓的中间 CA,其中 然后用于签署最终证书。将证书导入由中间 CA 签名的密钥库时,它是 这是提供整个信任链(直至根 CA)所必需的。这可以通过简单地将证书文件合二为一来完成 合并的证书文件,然后使用 keytool 导入它。
    3. 无法复制扩展字段
      CA作员通常不愿从 CSR 复制和请求的扩展字段,并且更愿意自己指定这些字段,因为这会 恶意方更难获取具有潜在误导性或欺诈性的证书。 建议仔细检查签名证书,这些证书是否包含所有请求的 SAN 字段,以启用正确的主机名验证。 以下命令可用于将证书详细信息打印到控制台,应将其与最初请求的内容进行比较:
      > openssl x509 -in certificate.crt -text -noout
  5. 配置 Kafka 代理

    如果没有为代理间通信启用 SSL(有关如何启用它,请参阅下文),则需要 PLAINTEXT 和 SSL 端口。 代理端需要以下 SSL 配置注意:ssl.truststore.password 在技术上是可选的,但强烈建议使用。如果未设置密码,则仍然可以访问信任库,但会禁用完整性检查。 值得考虑的可选设置:
    listeners=PLAINTEXT://host.name:port,SSL://host.name:port
    ssl.keystore.location=/var/private/ssl/server.keystore.jks
    ssl.keystore.password=test1234
    ssl.key.password=test1234
    ssl.truststore.location=/var/private/ssl/server.truststore.jks
    ssl.truststore.password=test1234
    1. ssl.client.auth=none (“required” => 需要客户端身份验证,“requested” =>请求客户端身份验证,没有证书的客户端仍然可以连接。不建议使用“requested”,因为它会提供一种虚假的安全感,并且配置错误的客户端仍将成功连接。
    2. ssl.cipher.suites (可选)。密码套件是身份验证、加密、MAC 和密钥交换算法的命名组合,用于协商使用 TLS 或 SSL 网络协议的网络连接的安全设置。(默认为空列表)
    3. ssl.enabled.protocols=TLSv1.2,TLSv1.1,TLSv1 (列出您将要从客户端接受的 SSL 协议。请注意,SSL 已被弃用,取而代之的是 TLS,并且不建议在生产中使用 SSL)
    4. ssl.keystore.type=JKS
    5. ssl.truststore.type=JKS
    6. ssl.secure.random.implementation=SHA1PRNG
    如果要为 broker 间通信启用 SSL,请将以下内容添加到 server.properties 文件中(默认为 PLAINTEXT)
    security.inter.broker.protocol=SSL

    由于某些国家/地区的进口法规,Oracle 实施限制了默认情况下可用的加密算法的强度。如果需要更强的算法(例如,具有 256 位密钥的 AES),则必须获取 JCE Unlimited Strength Jurisdiction Policy 文件并将其安装在 JDK/JRE 中。有关更多信息,请参阅 JCA 提供程序文档

    JRE/JDK 将具有用于加密作的默认伪随机数生成器 (PRNG),因此不需要配置 与ssl.secure.random.implementation.但是,某些实现存在性能问题(特别是 在 Linux 系统上选择 default,NativePRNG,使用全局锁)。如果 SSL 连接的性能成为问题, 考虑显式设置要使用的 implementation 。这SHA1PRNGimplementation 是非阻塞的,并且已经显示出非常好的性能 高负载下的特征(每个代理 50 MB/秒生成的消息,加上复制流量)。

    启动代理后,您应该能够在 server.log 中看到要快速检查服务器密钥库和信任库是否设置正确,您可以运行以下命令(注意:TLSv1 应列在 ssl.enabled.protocols 下)
    在此命令的输出中,您应该看到服务器的证书:如果证书没有显示或有任何其他错误消息,则您的密钥库未正确设置。
    with addresses: PLAINTEXT -> EndPoint(192.168.64.1,9092,PLAINTEXT),SSL -> EndPoint(192.168.64.1,9093,SSL)
    > openssl s_client -debug -connect localhost:9093 -tls1
    -----BEGIN CERTIFICATE-----
    {variable sized random bytes}
    -----END CERTIFICATE-----
    subject=/C=US/ST=CA/L=Santa Clara/O=org/OU=org/CN=Sriharsha Chintalapani
    issuer=/C=US/ST=CA/L=Santa Clara/O=org/OU=org/CN=kafka/emailAddress=test@test.com
  6. 配置 Kafka 客户端

    SSL 仅支持新的 Kafka 生产者和使用者,不支持旧的 API。SSL 的配置对于生产者和使用者都是相同的。
    如果代理中不需要客户端身份验证,则下面是一个最小配置示例:注意:ssl.truststore.password 在技术上是可选的,但强烈建议使用。如果未设置密码,则仍然可以访问信任库,但会禁用完整性检查。 如果需要客户端身份验证,则必须像步骤 1 中一样创建一个密钥库,并且还必须配置以下内容:根据我们的要求和代理配置,可能还需要的其他配置设置:
    security.protocol=SSL
    ssl.truststore.location=/var/private/ssl/client.truststore.jks
    ssl.truststore.password=test1234
    ssl.keystore.location=/var/private/ssl/client.keystore.jks
    ssl.keystore.password=test1234
    ssl.key.password=test1234
    1. ssl.provider (可选)。用于 SSL 连接的安全提供程序的名称。默认值是 JVM 的默认安全提供程序。
    2. ssl.cipher.suites (可选)。密码套件是身份验证、加密、MAC 和密钥交换算法的命名组合,用于协商使用 TLS 或 SSL 网络协议的网络连接的安全设置。
    3. ssl.enabled.protocols=TLSv1.2,TLSv1.1,TLSv1。它应列出至少一个在 broker 端配置的协议
    4. ssl.truststore.type=JKS
    5. ssl.keystore.type=JKS

    使用 console-producer 和 console-consumer 的示例:
    > kafka-console-producer.sh --bootstrap-server localhost:9093 --topic test --producer.config client-ssl.properties
    > kafka-console-consumer.sh --bootstrap-server localhost:9093 --topic test --consumer.config client-ssl.properties

7.4 使用 SASL 进行身份验证

  1. JAAS 配置

    Kafka 使用 Java 身份验证和授权服务 (日本航空局) 用于 SASL 配置。

    1. Kafka 代理的 JAAS 配置

      KafkaServer 是每个 KafkaServer/Broker 的 Pod Server / Broker 中。本节提供 SASL 配置选项 对于代理,包括代理建立的任何 SASL 客户端连接 用于 broker 间通信。如果多个侦听器配置为使用 SASL 时,节名称可以以小写的侦听器名称为前缀 后跟句点,例如 sasl_ssl。KafkaServer 的服务器。

      Client 部分用于验证 SASL 连接 动物园管理员。它还允许代理在 zookeeper 上设置 SASL ACL nodes 来锁定这些节点,以便只有代理可以 修改它。所有主体名称必须相同 经纪人。如果要使用 Client 以外的区域名称,请将 系统属性 zookeeper.sasl.clientconfig 设置为相应的 name(例如-Dzookeeper.sasl.clientconfig=ZkClient)。

      默认情况下,ZooKeeper 使用 “zookeeper” 作为服务名称。如果你 要更改此设置,请将系统属性 zookeeper.sasl.client.username 设置为适当的名称 (例如-Dzookeeper.sasl.client.username=zk)。

      代理还可以使用代理配置属性配置 JAASsasl.jaas.config. 属性名称必须以侦听器前缀为前缀,包括 SASL 机制、 即listener.name.{listenerName}.{saslMechanism}.sasl.jaas.config.只有一个 login 模块可以在 config 值中指定。如果在 listener 时,必须使用 listener 和 mechanism 前缀为每个机制提供配置。 例如

      listener.name.sasl_ssl.scram-sha-256.sasl.jaas.config=org.apache.kafka.common.security.scram.ScramLoginModule required \
          username="admin" \
          password="admin-secret";
      listener.name.sasl_ssl.plain.sasl.jaas.config=org.apache.kafka.common.security.plain.PlainLoginModule required \
          username="admin" \
          password="admin-secret" \
          user_admin="admin-secret" \
          user_alice="alice-secret";
      如果在不同的级别定义了 JAAS 配置,则使用的优先顺序为:
      • 代理配置属性listener.name.{listenerName}.{saslMechanism}.sasl.jaas.config
      • {listenerName}.KafkaServer静态 JAAS 配置的部分
      • KafkaServer静态 JAAS 配置的部分
      请注意,ZooKeeper JAAS 配置只能使用静态 JAAS 配置进行配置。

      有关代理配置示例,请参阅 GSSAPI (Kerberos)、PLAIN、SCRAMOAUTHBEARER

    2. Kafka 客户端的 JAAS 配置

      客户端可以使用客户端配置属性 sasl.jaas.config 或使用类似于代理的静态 JAAS 配置文件来配置 JAAS。

      1. 使用客户端配置属性的 JAAS 配置

        客户端可以将 JAAS 配置指定为生产者或使用者属性,而无需 创建物理配置文件。此模式还支持不同的生产者 和使用者使用不同的凭证,方法是指定 每个客户端的不同属性。如果两个静态 JAAS 配置系统属性java.security.auth.login.config和 Client 属性sasl.jaas.config,则将使用 client 属性。

        有关配置示例,请参阅 GSSAPI (Kerberos)、PLAINSCRAMOAUTHBEARER

      2. 使用静态配置文件的 JAAS 配置
        要使用静态 JAAS 配置文件在客户端上配置 SASL 身份验证:
        1. 添加一个 JAAS 配置文件,其中包含名为 KafkaClient 的客户端登录部分。配置 KafkaClient 中所选机制的登录模块,如示例中所述 用于设置 GSSAPI (Kerberos)、PLAINSCRAMOAUTHBEARER。 例如,GSSAPI 凭证可以配置为:
          KafkaClient {
              com.sun.security.auth.module.Krb5LoginModule required
              useKeyTab=true
              storeKey=true
              keyTab="/etc/security/keytabs/kafka_client.keytab"
              principal="kafka-client-1@EXAMPLE.COM";
          };
        2. 将 JAAS 配置文件位置作为 JVM 参数传递给每个客户端 JVM。例如:
          -Djava.security.auth.login.config=/etc/kafka/kafka_client_jaas.conf
  2. SASL 配置

    SASL 可以与 PLAINTEXT 或 SSL 一起使用作为传输层,使用 Security 协议分别SASL_PLAINTEXT 或 SASL_SSL。如果 SASL_SSL 是 used,则还必须配置 SSL

    1. SASL 机制
      Kafka 支持以下 SASL 机制:
    2. Kafka 代理的 SASL 配置
      1. 在 server.properties 中配置 SASL 端口,方法是添加至少一个 SASL_PLAINTEXT 或 SASL_SSL 传递给 listeners 参数,该参数 包含一个或多个逗号分隔值:如果您只配置 SASL 端口(或者如果您希望 Kafka 代理使用 SASL 相互进行身份验证),然后确保 您为代理间通信设置了相同的 SASL 协议:
        listeners=SASL_PLAINTEXT://host.name:port
        security.inter.broker.protocol=SASL_PLAINTEXT (or SASL_SSL)
      2. 选择要在代理中启用的一个或多个受支持的机制,然后按照步骤为该机制配置 SASL。 要在代理中启用多个机制,请按照此处的步骤作。
    3. Kafka 客户端的 SASL 配置

      只有新的 Java Kafka 生产者才支持 SASL 身份验证,并且 consumer 的 API 时,不支持较旧的 API。

      要在客户端上配置 SASL 身份验证,请选择在 代理进行客户端身份验证,并按照步骤配置 SASL 对于所选机构。

      注意:通过 SASL 建立与 broker 的连接时,客户端可能会执行相反的作 代理地址的 DNS 查找。由于 JRE 如何反向实现 DNS 查找,如果域完全限定,则客户端可能会观察到 SASL 握手缓慢 名称,对于客户端的bootstrap.servers和经纪人的advertised.listeners.

  3. 使用 SASL/Kerberos 进行身份验证

    1. 先决条件
      1. Kerberos
        如果您的组织已在使用 Kerberos 服务器(例如,通过使用 Active Directory),则无需仅为 Kafka 安装新服务器。否则,您将需要安装一个,您的 Linux 供应商可能有 Kerberos 的软件包以及有关如何安装和配置它的简短指南(UbuntuRedhat)。请注意,如果您使用的是 Oracle Java,则需要下载适用于您的 Java 版本的 JCE 策略文件,并将其复制到 $JAVA_HOME/jre/lib/security。
      2. 创建 Kerberos 委托人
        如果您使用的是组织的 Kerberos 或 Active Directory 服务器,请向 Kerberos 管理员请求集群中的每个 Kafka 代理以及将通过 Kerberos 身份验证(通过客户端和工具)访问 Kafka 的每个作系统用户的委托人。
        如果您已安装自己的 Kerberos,则需要使用以下命令自行创建这些主体:
        > sudo /usr/sbin/kadmin.local -q 'addprinc -randkey kafka/{hostname}@{REALM}'
        > sudo /usr/sbin/kadmin.local -q "ktadd -k /etc/security/keytabs/{keytabname}.keytab kafka/{hostname}@{REALM}"
      3. 确保所有主机都可以使用主机名访问 - Kerberos 要求所有主机都可以使用其 FQDN 进行解析。
    2. 配置 Kafka 代理
      1. 将一个经过适当修改的 JAAS 文件(类似于下面的文件)添加到每个 Kafka 代理的配置目录中,在本例中,我们将其命名为 kafka_server_jaas.conf(请注意,每个代理都应该有自己的密钥表):JAAS 文件中的 KafkaServer 部分告诉代理要使用哪个主体以及存储此主体的密钥表的位置。它 允许代理使用本节中指定的 keytab 登录。有关 Zookeeper SASL 配置的更多详细信息,请参阅注释
        KafkaServer {
            com.sun.security.auth.module.Krb5LoginModule required
            useKeyTab=true
            storeKey=true
            keyTab="/etc/security/keytabs/kafka_server.keytab"
            principal="kafka/kafka1.hostname.com@EXAMPLE.COM";
        };
        
        // Zookeeper client authentication
        Client {
            com.sun.security.auth.module.Krb5LoginModule required
            useKeyTab=true
            storeKey=true
            keyTab="/etc/security/keytabs/kafka_server.keytab"
            principal="kafka/kafka1.hostname.com@EXAMPLE.COM";
        };
      2. 将 JAAS 和 krb5 文件位置(可选)作为 JVM 参数传递给每个 Kafka 代理(有关更多详细信息,请参阅此处):
        -Djava.security.krb5.conf=/etc/kafka/krb5.conf
        -Djava.security.auth.login.config=/etc/kafka/kafka_server_jaas.conf
      3. 确保在 JAAS 文件中配置的键表可由启动 Kafka 代理的作系统用户读取。
      4. 在 server.properties 中配置 SASL 端口和 SASL 机制,如此所述。例如:我们还必须在 server.properties 中配置服务名称,该名称应与 kafka 代理的主体名称匹配。在上面的例子中,principal 是 “kafka/kafka1.hostname.com@EXAMPLE.com”,所以:
        listeners=SASL_PLAINTEXT://host.name:port
        security.inter.broker.protocol=SASL_PLAINTEXT
        sasl.mechanism.inter.broker.protocol=GSSAPI
        sasl.enabled.mechanisms=GSSAPI
        sasl.kerberos.service.name=kafka
    3. 配置 Kafka 客户端
      要在客户端上配置 SASL 身份验证:
      1. 客户端(生产者、消费者、连接工作者等)将使用它们的 own principal(通常与运行客户端的用户同名),因此 get 或 create 这些主体根据需要。然后为每个客户机配置 JAAS 配置属性。 JVM 中的不同客户端可以通过指定不同的主体以不同的用户身份运行。 物业sasl.jaas.config在 producer.properties 或 consumer.properties 中描述 创建者和使用者等客户端如何连接到 Kafka 代理。下面是一个示例 使用 keytab 的客户端配置(建议用于长时间运行的进程):对于 kafka-console-consumer 或 kafka-console-producer 等命令行实用程序,可以使用 kinit 以及 “useTicketCache=true”,如下所示:客户端的 JAAS 配置也可以指定为类似于代理的 JVM 参数 如此所述。客户端使用名为 KafkaClient 的登录部分。此选项仅允许一个用户用于来自 JVM 的所有客户端连接。
        sasl.jaas.config=com.sun.security.auth.module.Krb5LoginModule required \
            useKeyTab=true \
            storeKey=true  \
            keyTab="/etc/security/keytabs/kafka_client.keytab" \
            principal="kafka-client-1@EXAMPLE.COM";
        sasl.jaas.config=com.sun.security.auth.module.Krb5LoginModule required \
            useTicketCache=true;
      2. 确保在 JAAS 配置中配置的密钥选项卡可由启动 Kafka 客户端的作系统用户读取。
      3. (可选)将 krb5 文件位置作为 JVM 参数传递给每个客户端 JVM(有关更多详细信息,请参阅此处):
        -Djava.security.krb5.conf=/etc/kafka/krb5.conf
      4. 在 producer.properties 或 consumer.properties 中配置以下属性:
        security.protocol=SASL_PLAINTEXT (or SASL_SSL)
        sasl.mechanism=GSSAPI
        sasl.kerberos.service.name=kafka
  4. 使用 SASL/PLAIN 进行身份验证

    SASL/PLAIN 是一种简单的用户名/密码身份验证机制,通常与 TLS 一起使用进行加密以实现安全身份验证。 Kafka 支持 SASL/PLAIN 的默认实现,可以扩展用于生产用途,如此所述。

    principal.builder.class,则用户名将用作已验证的Principal用于配置 ACL 等。
    1. 配置 Kafka 代理
      1. 将类似于下面那个经过适当修改的 JAAS 文件添加到每个 Kafka 代理的配置目录中,在本例中,我们将其命名为 kafka_server_jaas.conf:此配置定义了两个用户(adminalice)。代理使用 KafkaServer 部分中的 usernamepassword 属性来启动与其他代理的连接。在此示例中,admin 是代理间通信的用户。user_userName 定义的属性集 连接到代理的所有用户的密码,代理验证所有客户端连接,包括 来自使用这些属性的其他经纪人的 VPN。
        KafkaServer {
            org.apache.kafka.common.security.plain.PlainLoginModule required
            username="admin"
            password="admin-secret"
            user_admin="admin-secret"
            user_alice="alice-secret";
        };
      2. 将 JAAS 配置文件位置作为 JVM 参数传递给每个 Kafka 代理:
        -Djava.security.auth.login.config=/etc/kafka/kafka_server_jaas.conf
      3. 在 server.properties 中配置 SASL 端口和 SASL 机制,如此所述。例如:
        listeners=SASL_SSL://host.name:port
        security.inter.broker.protocol=SASL_SSL
        sasl.mechanism.inter.broker.protocol=PLAIN
        sasl.enabled.mechanisms=PLAIN
    2. 配置 Kafka 客户端
      要在客户端上配置 SASL 身份验证:
      1. 在 producer.properties 或 consumer.properties 中为每个客户端配置 JAAS 配置属性。 登录模块描述了 producer 和 consumer 等客户端如何连接到 Kafka Broker。 以下是 PLAIN 机制的客户端配置示例:
        sasl.jaas.config=org.apache.kafka.common.security.plain.PlainLoginModule required \
            username="alice" \
            password="alice-secret";

        客户端使用选项 usernamepassword 来配置 客户端连接的用户。在此示例中,客户端以用户 alice 身份连接到代理。 JVM 中的不同客户端可以通过指定不同的用户名作为不同的用户进行连接 和密码sasl.jaas.config.

        客户机的 JAAS 配置也可以指定为类似于代理的 JVM 参数 如此所述。客户端使用名为 KafkaClient 的登录部分。此选项仅允许一个用户用于来自 JVM 的所有客户端连接。

      2. 在 producer.properties 或 consumer.properties 中配置以下属性:
        security.protocol=SASL_SSL
        sasl.mechanism=PLAIN
    3. 在生产中使用 SASL/PLAIN
      • SASL/PLAIN 应仅与 SSL 一起用作传输层,以确保明文密码不会在未加密的情况下通过网络传输。
      • Kafka 中 SASL/PLAIN 的默认实现在 JAAS 配置文件中指定用户名和密码,如下所示。从 Kafka 版本 2.0 开始,您可以避免在磁盘上存储明文密码 通过配置您自己的回调处理程序,这些处理程序使用配置选项从外部源获取用户名和密码sasl.server.callback.handler.classsasl.client.callback.handler.class.
      • 在生产系统中,外部认证服务器可以实现密码认证。从 Kafka 版本 2.0 开始, 您可以插入自己的回调处理程序,这些处理程序使用外部身份验证服务器进行密码验证,方法是配置sasl.server.callback.handler.class.
  5. 使用 SASL/SCRAM 进行身份验证

    Salted Challenge Response Authentication Mechanism (SCRAM) 是 SASL 机制的一个系列,它 解决了执行用户名/密码身份验证的传统机制的安全问题 比如 PLAIN 和 DIGEST-MD5。该机制在 RFC 5802 中定义。 Kafka 支持 SCRAM-SHA-256 和 SCRAM-SHA-512,它们 可与 TLS 一起使用以执行安全身份验证。在principal.builder.class,则用户名将用作已验证的Principal用于配置 ACL 等。Kafka 中的默认 SCRAM 实现 将 SCRAM 凭据存储在 Zookeeper 中,并适用于其中 Zookeeper 位于专用网络上。有关更多详细信息,请参阅安全注意事项

    1. 创建 SCRAM 凭证

      Kafka 中的 SCRAM 实现使用 Zookeeper 作为凭证存储。可以在 使用 kafka-configs.sh 的 Zookeeper。对于每个启用的 SCRAM 机制,必须创建凭证 通过添加带有 mechanism name 的 config。必须创建用于代理间通信的凭证 在 Kafka 代理启动之前。客户端凭证可以动态创建和更新,也可以更新 凭证将用于验证新连接。

      为用户 alice 创建密码为 alice-secret 的 SCRAM 凭证:

      > bin/kafka-configs.sh --zookeeper localhost:2182 --zk-tls-config-file zk_tls_config.properties --alter --add-config 'SCRAM-SHA-256=[iterations=8192,password=alice-secret],SCRAM-SHA-512=[password=alice-secret]' --entity-type users --entity-name alice

      如果未指定迭代,则使用默认迭代计数 4096。随机生成盐 以及由 salt、iterations、StoredKey 和 ServerKey 组成的 SCRAM 身份存储在 Zookeeper 中。 请参阅 RFC 5802 以了解有关 SCRAM 身份和各个字段的详细信息。

      以下示例还需要用户管理员进行代理间通信,该通信可通过以下方式创建:

      > bin/kafka-configs.sh --zookeeper localhost:2182 --zk-tls-config-file zk_tls_config.properties --alter --add-config 'SCRAM-SHA-256=[password=admin-secret],SCRAM-SHA-512=[password=admin-secret]' --entity-type users --entity-name admin

      可以使用 --describe 选项列出现有凭证:

      > bin/kafka-configs.sh --zookeeper localhost:2182 --zk-tls-config-file zk_tls_config.properties --describe --entity-type users --entity-name alice

      可以使用 --alter --delete-config 选项删除一个或多个 SCRAM 机制的凭证:

      > bin/kafka-configs.sh --zookeeper localhost:2182 --zk-tls-config-file zk_tls_config.properties --alter --delete-config 'SCRAM-SHA-512' --entity-type users --entity-name alice
    2. 配置 Kafka 代理
      1. 将类似于下面的适当修改的 JAAS 文件添加到每个 Kafka 代理的配置目录中,在本例中,我们将其命名为 kafka_server_jaas.conf:KafkaServer 部分中的属性 usernamepassword 由 代理启动与其他代理的连接。在此示例中,admin 是 经纪人间通信。
        KafkaServer {
            org.apache.kafka.common.security.scram.ScramLoginModule required
            username="admin"
            password="admin-secret";
        };
      2. 将 JAAS 配置文件位置作为 JVM 参数传递给每个 Kafka 代理:
        -Djava.security.auth.login.config=/etc/kafka/kafka_server_jaas.conf
      3. 在 server.properties 中配置 SASL 端口和 SASL 机制,如此所述。例如:
        listeners=SASL_SSL://host.name:port
        security.inter.broker.protocol=SASL_SSL
        sasl.mechanism.inter.broker.protocol=SCRAM-SHA-256 (or SCRAM-SHA-512)
        sasl.enabled.mechanisms=SCRAM-SHA-256 (or SCRAM-SHA-512)
    3. 配置 Kafka 客户端
      要在客户端上配置 SASL 身份验证:
      1. 在 producer.properties 或 consumer.properties 中为每个客户端配置 JAAS 配置属性。 登录模块描述了 producer 和 consumer 等客户端如何连接到 Kafka Broker。 以下是 SCRAM 机制的客户端配置示例:
        sasl.jaas.config=org.apache.kafka.common.security.scram.ScramLoginModule required \
            username="alice" \
            password="alice-secret";

        客户端使用选项 usernamepassword 来配置 客户端连接的用户。在此示例中,客户端以用户 alice 身份连接到代理。 JVM 中的不同客户端可以通过指定不同的用户名作为不同的用户进行连接 和密码sasl.jaas.config.

        客户机的 JAAS 配置也可以指定为类似于代理的 JVM 参数 如此所述。客户端使用名为 KafkaClient 的登录部分。此选项仅允许一个用户用于来自 JVM 的所有客户端连接。

      2. 在 producer.properties 或 consumer.properties 中配置以下属性:
        security.protocol=SASL_SSL
        sasl.mechanism=SCRAM-SHA-256 (or SCRAM-SHA-512)
    4. SASL/SCRAM 的安全注意事项
      • Kafka 中 SASL/SCRAM 的默认实现将 SCRAM 凭证存储在 Zookeeper 中。这 适合在 Zookeeper 安全且位于专用网络上的安装中使用。
      • Kafka 仅支持具有最小迭代计数的强哈希函数 SHA-256 和 SHA-512 4096 年。强哈希函数与强密码和高迭代计数相结合,提供保护 在 Zookeeper 安全性受到威胁时抵御暴力攻击。
      • SCRAM 应仅与 TLS 加密一起使用,以防止拦截 SCRAM 交换。这 防止字典或暴力攻击,并在 Zookeeper 遭到入侵时防止冒充。
      • 从 Kafka 版本 2.0 开始,可以使用自定义回调处理程序覆盖默认的 SASL/SCRAM 凭证存储 通过配置sasl.server.callback.handler.class在 Zookeeper 不安全的安装中。
      • 有关安全注意事项的更多详细信息,请参阅 RFC 5802
  6. 使用 SASL/OAUTHBEARER 进行身份验证

    OAuth 2 授权框架“使第三方应用程序能够获得对 HTTP 服务的有限访问权限, 代表资源所有者通过编排资源所有者与 HTTP 之间的审批交互 服务,或者允许第三方应用程序代表自己获取访问权限。SASL OAUTHBEARER 机制 允许在 SASL(即非 HTTP)上下文中使用框架;它在 RFC 7628 中定义。 Kafka 中的默认 OAUTHBEARER 实现会创建并验证不安全的 JSON Web 令牌,并且仅适用于非生产 Kafka 安装。有关更多详细信息,请参阅安全注意事项

    principal.builder.class,OAuthBearerToken 的 principalName 用作经过身份验证的Principal用于配置 ACL 等。
    1. 配置 Kafka 代理
      1. 将类似于下面的适当修改的 JAAS 文件添加到每个 Kafka 代理的配置目录中,在本例中,我们将其命名为 kafka_server_jaas.conf:KafkaServer 部分中的属性 unsecuredLoginStringClaim_sub 由 代理启动与其他代理的连接时。在此示例中,admin 将出现在 subject (sub) 声明,并且将成为 Inter-Broker 通信的用户。
        KafkaServer {
            org.apache.kafka.common.security.oauthbearer.OAuthBearerLoginModule required
            unsecuredLoginStringClaim_sub="admin";
        };
      2. 将 JAAS 配置文件位置作为 JVM 参数传递给每个 Kafka 代理:
        -Djava.security.auth.login.config=/etc/kafka/kafka_server_jaas.conf
      3. 在 server.properties 中配置 SASL 端口和 SASL 机制,如此所述。例如:
        listeners=SASL_SSL://host.name:port (or SASL_PLAINTEXT if non-production)
        security.inter.broker.protocol=SASL_SSL (or SASL_PLAINTEXT if non-production)
        sasl.mechanism.inter.broker.protocol=OAUTHBEARER
        sasl.enabled.mechanisms=OAUTHBEARER
    2. 配置 Kafka 客户端
      要在客户端上配置 SASL 身份验证:
      1. 在 producer.properties 或 consumer.properties 中为每个客户端配置 JAAS 配置属性。 登录模块描述了 producer 和 consumer 等客户端如何连接到 Kafka Broker。 以下是 OAUTHBEARER 机制的客户端的示例配置:
        sasl.jaas.config=org.apache.kafka.common.security.oauthbearer.OAuthBearerLoginModule required \
            unsecuredLoginStringClaim_sub="alice";

        客户端使用选项 unsecuredLoginStringClaim_sub 来配置 主题 (sub) 声明,用于确定客户端连接的用户。 在此示例中,客户端以用户 alice 身份连接到代理。 JVM 中的不同客户端可以通过指定不同的主题 (sub) 作为不同的用户进行连接 索赔sasl.jaas.config.

        客户机的 JAAS 配置也可以指定为类似于代理的 JVM 参数 如此所述。客户端使用名为 KafkaClient 的登录部分。此选项仅允许一个用户用于来自 JVM 的所有客户端连接。

      2. 在 producer.properties 或 consumer.properties 中配置以下属性:
        security.protocol=SASL_SSL (or SASL_PLAINTEXT if non-production)
        sasl.mechanism=OAUTHBEARER
      3. SASL/OAUTHBEARER 的默认实现取决于 jackson-databind 库。 由于它是一个可选的依赖项,用户必须通过他们的构建工具将其配置为依赖项。
    3. SASL/OAUTHBEARER 的不安全令牌创建选项
      • Kafka 中 SASL/OAUTHBEARER 的默认实现会创建并验证不安全的 JSON Web 令牌。 虽然仅适用于非生产用途,但它确实提供了在 DEV 或 TEST 环境中创建任意令牌的灵活性。
      • 以下是客户端上支持的各种 JAAS 模块选项(如果 OAUTHBEARER 是代理间协议,则在代理端):
        用于创建不安全令牌的 JAAS 模块选项 文档
        unsecuredLoginStringClaim_<claimname>=“value” 创建具有给定名称和值的 String 声明。任何有效 可以指定声明名称,但 'iat' 和 'exp' 除外(这些是 自动生成)。
        unsecuredLoginNumberClaim_<claimname>=“value” 创建具有给定名称和值的 Number 声明。任何有效 可以指定声明名称,但 'iat' 和 'exp' 除外(这些是 自动生成)。
        unsecuredLoginListClaim_<claimname>=“value” 创建已解析的给定名称和值的 String List 声明 从给定值开始,其中第一个字符作为分隔符。为 示例:unsecuredLoginListClaim_fubar=“|value1|value2”。任何有效 可以指定声明名称,但 'iat' 和 'exp' 除外(这些是 自动生成)。
        unsecuredLoginExtension_<extensionname>=“value” 创建具有给定名称和值的 String 扩展。 例如:unsecuredLoginExtension_traceId=“123”。有效的扩展名 是小写或大写字母字符的任意序列。此外,“auth” 扩展名是保留的。 有效的扩展名值是具有 ASCII 代码 1-127 的字符的任意组合。
        unsecuredLoginPrincipalClaimName 如果您希望包含主体名称的 String 声明的名称不是 'sub',请设置为自定义声明名称。
        unsecuredLoginLifetimeSeconds 如果要将令牌过期时间设置为某个值,则设置为整数值 默认值 3600 秒(即 1 小时)除外。这 'exp' 声明将设置为反映过期时间。
        unsecuredLoginScopeClaimName 如果您希望包含任何令牌范围的 StringString List 声明的名称不是 '范围'。
    4. SASL/OAUTHBEARER 的不安全令牌验证选项
      • 以下是代理端支持的各种 JAAS 模块选项,用于不安全的 JSON Web 令牌验证:
        用于不安全令牌验证的 JAAS 模块选项 文档
        unsecuredValidatorPrincipalClaimName=“值” 如果您希望特定 String 声明,请设置为非空值 持有要检查是否存在的主体名称;默认为 “sub”声明的存在。
        unsecuredValidatorScopeClaimName=“值” 如果您希望包含任何令牌范围的 StringString List 声明的名称不是 '范围'。
        unsecuredValidatorRequiredScope=“值” 如果您希望将包含令牌范围的 String/String List 声明检查为 确保它包含某些值。
        unsecuredValidatorAllowableClockSkewMs=“值” 如果您希望允许最多一些 clock skew 的正毫秒数(默认值为 0)。
      • 默认的不安全的 SASL/OAUTHBEARER 实现可以被覆盖(并且必须在 生产环境中被覆盖) 使用自定义登录和 SASL 服务器回调处理程序。
      • 有关安全注意事项的更多详细信息,请参阅 RFC 6749 的第 10 节
    5. SASL/OAUTHBEARER 的令牌刷新
      Kafka 会在令牌过期之前定期刷新任何令牌,以便客户端可以继续进行 与 broker 的连接。影响刷新算法方式的参数 作作为 producer/consumer/broker 配置的一部分指定 ,如下所示。请参阅其他位置的这些属性的文档 详。默认值通常是合理的,在这种情况下,这些 不需要显式设置配置参数。
      Producer/Consumer/Broker 配置属性
      sasl.login.refresh.window.factor
      sasl.login.refresh.window.jitter
      sasl.login.refresh.min.period.seconds
      sasl.login.refresh.min.buffer.seconds
    6. SASL/OAUTHBEARER 的安全/生产使用
      生产用例需要编写 org.apache.kafka.common.security.auth.AuthenticateCallbackHandler 的实现,该实现可以处理 org.apache.kafka.common.security.oauthbearer.OAuthBearerTokenCallback 的实例,并通过 sasl.login.callback.handler.class 配置选项声明它。 非代理客户端或通过代理的 listener.name.sasl_ssl.oauthbearer.sasl.login.callback.handler.class 配置选项(当 SASL/OAUTHBEARER 是代理间 协议)。

      生产用例还需要编写 org.apache.kafka.common.security.auth.AuthenticateCallbackHandler 的实现,该实现可以处理 org.apache.kafka.common.security.oauthbearer.OAuthBearerValidatorCallback 的实例,并通过 listener.name.sasl_ssl.oauthbearer.sasl.server.callback.handler.class 代理配置选项声明它。

    7. SASL/OAUTHBEARER 的安全注意事项
      • Kafka 中 SASL/OAUTHBEARER 的默认实现会创建并验证不安全的 JSON Web 令牌。 这仅适用于非生产用途。
      • OAUTHBEARER 只能在生产环境中使用 TLS 加密,以防止拦截令牌。
      • 默认的不安全的 SASL/OAUTHBEARER 实现可以被覆盖(并且必须在 生产环境中被覆盖) 如上所述,使用自定义登录和 SASL 服务器回调处理程序。
      • 有关 OAuth 2 安全注意事项的更多详细信息,请参阅 RFC 6749 第 10 节
  7. 在代理中启用多个 SASL 机制

    1. 在 JAAS 配置文件的 KafkaServer 部分中指定所有已启用机制的登录模块的配置。例如:
      KafkaServer {
          com.sun.security.auth.module.Krb5LoginModule required
          useKeyTab=true
          storeKey=true
          keyTab="/etc/security/keytabs/kafka_server.keytab"
          principal="kafka/kafka1.hostname.com@EXAMPLE.COM";
      
          org.apache.kafka.common.security.plain.PlainLoginModule required
          username="admin"
          password="admin-secret"
          user_admin="admin-secret"
          user_alice="alice-secret";
      };
    2. 在 server.properties 中启用 SASL 机制:
      sasl.enabled.mechanisms=GSSAPI,PLAIN,SCRAM-SHA-256,SCRAM-SHA-512,OAUTHBEARER
    3. 如果需要,请在 server.properties 中指定代理间通信的 SASL 安全协议和机制:
      security.inter.broker.protocol=SASL_PLAINTEXT (or SASL_SSL)
      sasl.mechanism.inter.broker.protocol=GSSAPI (or one of the other enabled mechanisms)
    4. 按照 GSSAPI (Kerberos)、PLAIN、SCRAMOAUTHBEARER 中特定于机制的步骤为启用的机制配置 SASL。
  8. 修改正在运行的集群中的 SASL 机制

    可以使用以下顺序在正在运行的集群中修改 SASL 机制:

    1. 通过将机制添加到每个代理的 server.properties 中的 sasl.enabled.mechanisms 中来启用新的 SASL 机制。更新 JAAS 配置文件以包含两者 机制。逐步并轨群集节点。
    2. 使用新机制重新启动客户端。
    3. 要更改代理间通信的机制(如果需要),请将 server.properties 中的 sasl.mechanism.inter.broker.protocol 设置为新机制,并将 再次以增量方式退回集群。
    4. 要删除旧机制(如果需要),请从 server.properties 的 sasl.enabled.mechanisms 中删除旧机制,并删除 来自 JAAS 配置文件的 old 机制。再次以增量方式退回集群。
  9. 使用委托令牌进行身份验证

    基于委托令牌的身份验证是一种轻量级身份验证机制,用于补充现有的 SASL/SSL 方法。委托令牌是 Kafka 代理和客户端之间的共享密钥。委托令牌将有助于处理 框架将工作负载分配给安全环境中的可用工作人员,而不会增加分配成本 使用 2 向 SSL 时的 Kerberos TGT/密钥表或密钥库。有关更多详细信息,请参阅 KIP-48

    principal.builder.class,委托令牌的所有者将用作经过身份验证的Principal用于配置 ACL 等。

    使用委托令牌的典型步骤包括:

    1. 用户通过 SASL 或 SSL 对 Kafka 集群进行身份验证,并获取委托 Token。这是可以做到的 使用 Admin API 或使用 kafka-delegation-tokens.sh 脚本。
    2. 用户安全地将委托令牌传递给 Kafka 客户端,以便对 Kafka 集群进行身份验证。
    3. Token owner/renewer 可以续订委托令牌/使委托令牌过期。
    1. Token 管理

      密钥用于生成和验证委托令牌。这是使用 config 提供的 选项 delegation.token.secret.key。必须在所有代理中配置相同的密钥。 如果 secret 未设置或设置为空字符串,则 broker 将禁用委派令牌身份验证。

      在当前的实现中,令牌详细信息存储在 Zookeeper 中,适用于其中 Zookeeper 位于专用网络上。此外,目前,此 secret 以纯文本形式存储在 server.properties 中 config 文件。我们打算在未来的 Kafka 版本中使这些内容可配置。

      代币具有当前生命周期和最长可更新生命周期。默认情况下,令牌必须每 24 小时续订一次 最多 7 天。这些可以使用 delegation.token.expiry.time.msdelegation.token.max.lifetime.ms 配置选项进行配置。

      也可以显式取消令牌。如果令牌未在令牌的过期时间之前续订,或者如果令牌 超过最长生命周期,它将从所有代理缓存以及 Zookeeper 中删除。

    2. 创建委托令牌

      可以使用 Admin API 或使用 kafka-delegation-tokens.sh 脚本创建令牌。 委托令牌请求(创建/续订/过期/描述)应仅在 SASL 或 SSL 身份验证通道上发出。 如果初始身份验证是通过委托令牌完成的,则无法请求令牌。 用户可以通过指定 --owner-principal 参数为该用户或其他用户创建令牌。 所有者/续订者可以续订令牌或使令牌过期。所有者/续订者始终可以描述自己的令牌。 要描述其他令牌,需要在表示令牌所有者的 User 资源上添加 DESCRIBE_TOKEN 权限。下面给出了 kafka-delegation-tokens.sh 脚本示例。

      创建委托令牌:

      > bin/kafka-delegation-tokens.sh --bootstrap-server localhost:9092 --create   --max-life-time-period -1 --command-config client.properties --renewer-principal User:user1

      为其他所有者创建委托令牌:

      > bin/kafka-delegation-tokens.sh --bootstrap-server localhost:9092 --create   --max-life-time-period -1 --command-config client.properties --renewer-principal User:user1 --owner-principal User:owner1

      续订委托令牌:

      > bin/kafka-delegation-tokens.sh --bootstrap-server localhost:9092 --renew    --renew-time-period -1 --command-config client.properties --hmac ABCDEFGHIJK

      使委托令牌过期:

      > bin/kafka-delegation-tokens.sh --bootstrap-server localhost:9092 --expire   --expiry-time-period -1   --command-config client.properties  --hmac ABCDEFGHIJK

      可以使用 --describe 选项描述现有令牌:

      > bin/kafka-delegation-tokens.sh --bootstrap-server localhost:9092 --describe --command-config client.properties  --owner-principal User:user1
    3. Token 鉴权

      委托令牌身份验证背负在当前的 SASL/SCRAM 身份验证机制之上。我们必须启用 SASL/SCRAM 机制,如此所述。

      配置 Kafka 客户端:

      1. 在 producer.properties 或 consumer.properties 中为每个客户端配置 JAAS 配置属性。 登录模块描述了 producer 和 consumer 等客户端如何连接到 Kafka Broker。 以下是用于令牌身份验证的客户端的示例配置:
        sasl.jaas.config=org.apache.kafka.common.security.scram.ScramLoginModule required \
            username="tokenID123" \
            password="lAYYSFmLs4bTjf+lTZ1LCHR/ZZFNA==" \
            tokenauth="true";

        客户端使用选项 usernamepassword 来配置令牌 id 和 令牌 HMAC 的 HMAC 令牌。选项 tokenauth 用于指示服务器进行 token 认证。 在此示例中,客户端使用令牌 ID 连接到代理:tokenID123。一个 JVM 可以通过在sasl.jaas.config.

        客户机的 JAAS 配置也可以指定为类似于代理的 JVM 参数 如此所述。客户端使用名为 KafkaClient 的登录部分。此选项仅允许一个用户用于来自 JVM 的所有客户端连接。

    4. 手动轮换密钥的过程:

      当密钥需要轮换时,我们需要重新部署。在此过程中,已连接的客户端 将继续工作。但是,任何新的连接请求和使用旧令牌的续订/过期请求都可能失败。步骤如下。

      1. 使所有现有令牌过期。
      2. 通过滚动升级轮换密钥,以及
      3. 生成新令牌

      我们打算在未来的 Kafka 版本中实现自动化。

7.5 授权和 ACL

Kafka 附带了一个可插拔的授权框架,该框架在服务器配置中使用 authorizer.class.name 属性进行配置。 配置的实现必须扩展org.apache.kafka.server.authorizer.Authorizer. Kafka 提供了默认实现,这些实现将 ACL 存储在集群元数据(Zookeeper 或 KRaft 元数据日志)中。 对于基于 Zookeeper 的集群,提供的实现配置如下:对于 KRaft 集群,请在所有节点(代理、控制器或组合的代理/控制器节点)上使用以下配置:Kafka ACL 以“Principal {P} is [Allowed|denied] 主机 {H} 对与 ResourcePattern {RP} 匹配的任何资源 {R} 执行作 {O}”。 您可以在 KIP-11KIP-290 中的资源模式。 要添加、删除或列出 ACL,您可以使用 Kafka ACL CLI
authorizer.class.name=kafka.security.authorizer.AclAuthorizer
authorizer.class.name=org.apache.kafka.metadata.authorizer.StandardAuthorizer
kafka-acls.sh.默认情况下,如果没有 ResourcePatterns 与特定 Resource R 匹配,则 则 R 没有关联的 ACL,因此除了超级用户之外,不允许任何人访问 R。 如果要更改该行为,可以在 server.properties 中包含以下内容。 还可以在 server.properties 中添加超级用户,如下所示(请注意,分隔符是分号,因为 SSL 用户名可能包含逗号)。默认 PrincipalType 字符串 “User” 区分大小写。
allow.everyone.if.no.acl.found=true
super.users=User:Bob;User:Alice
KRaft 委托人转发
在 KRaft 集群中,管理员请求(例如CreateTopicsDeleteTopics由客户端发送到 Broker 侦听器。然后,代理通过controller.listener.names. 这些请求的授权是在 controller 节点上完成的。这是通过Enveloperequest 打包来自客户端和客户端委托人的基础请求。 当控制器收到转发的Envelope请求,它首先授权Envelope请求。 然后,它使用转发的委托人授权底层请求。
所有这些都意味着 Kafka 必须了解如何序列化和反序列化客户端主体。身份验证框架允许通过覆盖
principal.builder.class配置。 为了使自定义主体与 KRaft 一起使用,配置的类必须实现org.apache.kafka.common.security.auth.KafkaPrincipalSerde以便 Kafka 知道如何序列化和反序列化主体。 默认实现org.apache.kafka.common.security.authenticator.DefaultKafkaPrincipalBuilder使用源代码中定义的 Kafka RPC 格式:clients/src/main/resources/common/message/DefaultPrincipalData.json. 有关 KRaft 中请求转发的更多详细信息,请参阅 KIP-590
自定义 SSL 用户名
默认情况下,SSL 用户名的格式为“CN=writeuser,OU=Unknown,O=Unknown,L=Unknown,ST=Unknown,C=Unknown”。可以通过设置ssl.principal.mapping.rules添加到 server.properties 中的自定义规则。 此配置允许将 X.500 可分辨名称映射到短名称的规则列表。规则按顺序进行评估,并与可分辨名称匹配的第一个规则用于将其映射到短名称。列表中任何后续的规则都将被忽略。
格式
ssl.principal.mapping.rules是一个列表,其中每个规则都以 “RULE:” 开头,并包含以下格式的表达式。默认规则将返回 X.500 证书可分辨名称的字符串表示形式。如果可分辨名称与模式匹配,则 replacement 命令将对该名称运行。 这还支持 lowercase/uppercase 选项,以强制翻译的结果全部为小写/大写。这是通过在规则末尾添加 “/L” 或 “/U” 来完成的。 例
RULE:pattern/replacement/
RULE:pattern/replacement/[LU]
ssl.principal.mapping.rules值为:上述规则将可分辨名称“CN=serviceuser,OU=ServiceUsers,O=Unknown,L=Unknown,ST=Unknown,C=Unknown”转换为“serviceuser” 将 “CN=adminUser,OU=Admin,O=Unknown,L=Unknown,ST=Unknown,C=Unknown” 改为 “adminuser@admin”。
对于高级用例,可以通过在 server.properties 中设置自定义的 PrincipalBuilder 来自定义名称,如下所示。
RULE:^CN=(.*?),OU=ServiceUsers.*$/$1/,
RULE:^CN=(.*?),OU=(.*?),O=(.*?),L=(.*?),ST=(.*?),C=(.*?)$/$1@$2/L,
RULE:^.*[Cc][Nn]=([a-zA-Z0-9.]*).*$/$1/L,
DEFAULT
principal.builder.class=CustomizedPrincipalBuilderClass
自定义 SASL 用户名
默认情况下,SASL 用户名将是 Kerberos 主体的主要部分。可以通过设置sasl.kerberos.principal.to.local.rules添加到 server.properties 中的自定义规则。 格式sasl.kerberos.principal.to.local.rules是一个列表,其中每个规则的工作方式与 Kerberos 配置文件 (krb5.conf) 中的auth_to_local相同。这还支持其他小写/大写规则,以强制翻译的结果全部为小写/大写。这是通过在规则末尾添加 “/L” 或 “/U” 来完成的。检查下面的格式了解语法。 每个规则都以 RULE: 开头,并包含以下格式的表达式。有关更多详细信息,请参阅 kerberos 文档。 添加规则以将 user@MYDOMAIN.COM 正确转换为 user 同时保留默认规则的示例是:
RULE:[n:string](regexp)s/pattern/replacement/
RULE:[n:string](regexp)s/pattern/replacement/g
RULE:[n:string](regexp)s/pattern/replacement//L
RULE:[n:string](regexp)s/pattern/replacement/g/L
RULE:[n:string](regexp)s/pattern/replacement//U
RULE:[n:string](regexp)s/pattern/replacement/g/U
sasl.kerberos.principal.to.local.rules=RULE:[1:$1@$0](.*@MYDOMAIN.COM)s/@.*//,DEFAULT

命令行界面

Kafka 授权管理 CLI 可以在所有其他 CLI 的 bin 目录下找到。CLI 脚本称为 kafka-acls.sh。下面列出了脚本支持的所有选项:

选择 描述 违约 选项类型
--加 向脚本指示用户正在尝试添加 acl。 行动
--删除 向脚本指示用户正在尝试删除 acl。 行动
--列表 向脚本指示用户正在尝试列出 ACL。 行动
--引导服务器 用于建立与 Kafka 集群连接的主机/端口对列表。只能指定 --bootstrap-server 或 --authorizer 选项之一。 配置
--命令配置 包含要传递给 Admin Client 的配置的属性文件。此选项只能与 --bootstrap-server 选项一起使用。 配置
--簇 向脚本指示用户正在尝试与单个群集资源上的 acls 交互。 资源模式
--topic [主题名称] 向脚本指示用户正在尝试与主题资源模式上的 ACL 交互。 资源模式
--group [组名] 向脚本指示用户正在尝试与使用者组资源模式上的 ACL 交互 资源模式
--transactional-id [事务 ID] 应添加或删除 ACL 的 transactionalId。值 * 表示 ACL 应应用于所有 transactionalId。 资源模式
--delegation-token [委托令牌] 应添加或删除 ACL 的委派令牌。值 * 表示 ACL 应应用于所有令牌。 资源模式
--user-principal [用户主体] 应向其添加或删除 ACL 的用户资源。目前支持与 delegation tokens 相关的此功能。 值 * 表示 ACL 应应用于所有用户。 资源模式
--resource-pattern-type [模式类型] 向脚本指示用户希望使用的资源模式类型(对于 --add)或资源模式过滤器(对于 --list 和 --remove)。
添加 ACL 时,这应该是特定的模式类型,例如 'literal' 或 'prefixed'。
在列出或删除 ACL 时,可以使用特定模式类型过滤器来列出或删除特定类型的资源模式中的 ACL。 或者可以使用 'any' 或 'match' 的过滤器值,其中 'any' 将匹配任何模式类型,但会完全匹配资源名称, 而 'match' 将执行模式匹配,以列出或删除影响所提供资源的所有 ACL。
警告: 当 'match' 与 '--remove' 开关结合使用时,应谨慎使用。
字面 配置
--允许委托人 Principal 采用 PrincipalType:name 格式,该格式将添加到具有 Allow 权限的 ACL 中。默认 PrincipalType 字符串 “User” 区分大小写。
您可以在单个命令中指定多个 --allow-principal。
主要
--拒绝校长 Principal 采用 PrincipalType:name 格式,将添加到具有 Deny 权限的 ACL 中。默认 PrincipalType 字符串 “User” 区分大小写。
您可以在单个命令中指定多个 --deny-principal。
主要
--主要 Principal 采用 PrincipalType:name 格式,将与 --list 选项一起使用。默认 PrincipalType 字符串 “User” 区分大小写。这将列出指定委托人的 ACL。
您可以在单个命令中指定多个 --principal。
主要
--allow-host --allow-principal 中列出的主体将有权访问的 IP 地址。 如果指定了 --allow-principal,则默认为 *,即 “所有主机” 主机
--拒绝主机 --deny-principal 中列出的委托人将被拒绝访问的 IP 地址。 如果指定了 --deny-principal,则默认为 *,即 “所有主机” 主机
--操作 将允许或拒绝的作。
有效值为:
  • 创造
  • 删除
  • 改变
  • 描述
  • ClusterAction
  • DescribeConfigs 实例
  • AlterConfigs
  • IdempotentWrite
  • CreateTokens
  • 描述令牌
操作
--制作人 为生产者角色添加/删除 ACL 的便捷选项。这将生成允许 WRITE 的 ACLS, DESCRIBE 和 CREATE 在主题上。 方便
--消费者 为使用者角色添加/删除 ACL 的便捷选项。这将生成允许 READ 的 ACLS, DESCRIBE 和 consumer-group 上的 READ。 方便
--幂等 为生产者启用幂等性。这应该与 --producer 选项结合使用。
请注意,如果 producer 被授权给特定的 transactional-id,则会自动启用幂等。
方便
--力 方便选项,对所有查询都假定为 yes 并且不提示。 方便
--授权方 (已弃用:在 KRaft 中不受支持)授权方的完全限定类名。 kafka.security.authorizer.Acl授权者 配置
--authorizer-properties (已弃用:在 KRaft 中不受支持)key=val 对,该对将传递给授权方进行初始化。对于 ZK clsuters 中的默认授权方,示例值为:zookeeper.connect=localhost:2181 配置
--zk-tls-config-文件 (已弃用:在 KRaft 中不受支持)标识在其中定义授权方的 ZooKeeper 客户端 TLS 连接属性的文件。 除以下属性(带或不带 “authorizer.”前缀)之外的任何属性都将被忽略: zookeeper.clientCnxnSocket、zookeeper.ssl.cipher.suites、zookeeper.ssl.client.enable、 zookeeper.ssl.crl.enable、zookeeper.ssl.enabled.protocols、zookeeper.ssl.endpoint.identification.algorithm、 zookeeper.ssl.keystore.location、zookeeper.ssl.keystore.password、zookeeper.ssl.keystore.type、 zookeeper.ssl.ocsp.enable、zookeeper.ssl.protocol、zookeeper.ssl.truststore.location、 zookeeper.ssl.truststore.password, zookeeper.ssl.truststore.type 配置

例子

  • 添加 ACL
    :假设您要添加一个 acl:“允许主体 User:Bob 和 User:Alice 对 IP 198.51.100.0 和 IP 198.51.100.1 的主题测试主题执行读写作”。您可以通过使用以下选项执行 CLI 来执行此作:默认情况下,所有没有允许对资源进行作的显式 acl 的委托人都将被拒绝。在极少数情况下,如果定义了允许 acl 访问除某些委托人之外的所有委托人,我们将不得不使用 --deny-principal 和 --deny-host 选项。例如,如果我们想允许所有用户从 Test-topic 读取,但只拒绝来自 IP 198.51.100.3 的 User:BadBob,我们可以使用以下命令来实现:请注意,
    > bin/kafka-acls.sh --bootstrap-server localhost:9092 --add --allow-principal User:Bob --allow-principal User:Alice --allow-host 198.51.100.0 --allow-host 198.51.100.1 --operation Read --operation Write --topic Test-topic
    > bin/kafka-acls.sh --bootstrap-server localhost:9092 --add --allow-principal User:'*' --allow-host '*' --deny-principal User:BadBob --deny-host 198.51.100.3 --operation Read --topic Test-topic
    --allow-host--deny-host仅支持 IP 地址(不支持主机名)。 上面的示例通过指定 --topic [topic-name] 作为资源模式选项将 acls 添加到主题中。同样,用户可以通过指定 --cluster 将 acls 添加到集群中,通过指定 --group [group-name] 将 acls 添加到消费者组。 您可以在某种类型的任何资源上添加 acls,例如,假设您想添加一个 acl“Principal User:Peter is allowed to produce to any Topic from IP 198.51.200.0” 您可以通过使用通配符资源 '*' 来做到这一点,例如,通过使用以下选项执行 CLI:您可以在带前缀的资源模式上添加 acls,例如,假设您想添加一个 acl“Principal User:Jane is allowed to produce to any Topic that name with 'Test-' from any host”。 您可以通过使用以下选项执行 CLI 来执行此作:请注意,--resource-pattern-type 默认为 'literal',这仅影响名称完全相同的资源,或者在通配符资源名称 '*' 的情况下,影响具有任何名称的资源。
    > bin/kafka-acls.sh --bootstrap-server localhost:9092 --add --allow-principal User:Peter --allow-host 198.51.200.1 --producer --topic '*'
    > bin/kafka-acls.sh --bootstrap-server localhost:9092 --add --allow-principal User:Jane --producer --topic Test- --resource-pattern-type prefixed
  • 删除 ACLS
    删除 ACL 几乎相同。唯一的区别是用户必须指定 --remove 选项,而不是 --add 选项。要删除上面第一个示例添加的 acls,我们可以使用以下选项执行 CLI:如果要删除添加到上述前缀资源模式的 acl,我们可以使用以下选项执行 CLI:
    > bin/kafka-acls.sh --bootstrap-server localhost:9092 --remove --allow-principal User:Bob --allow-principal User:Alice --allow-host 198.51.100.0 --allow-host 198.51.100.1 --operation Read --operation Write --topic Test-topic 
    > bin/kafka-acls.sh --bootstrap-server localhost:9092 --remove --allow-principal User:Jane --producer --topic Test- --resource-pattern-type Prefixed
  • 列出 ACL
    我们可以通过在资源中指定 --list 选项来列出任何资源的 ACL。要列出文本资源模式 Test-topic 上的所有 acls,我们可以使用以下选项执行 CLI:但是,这只会返回已添加到此确切资源模式的 acls。可能存在影响对主题的访问的其他 ACL, 例如,主题通配符 '*' 上的任何 ACL,或前缀资源模式上的任何 ACL。可以显式查询通配符资源模式上的 ACL:但是,不一定能够显式查询与 Test-topic 匹配的前缀资源模式上的 ACL,因为此类模式的名称可能未知。 我们可以使用 '--resource-pattern-type match' 列出所有影响 Test-topic 的 acl,例如 这将列出所有匹配的 Literals、通配符和前缀资源模式的 acl。
    > bin/kafka-acls.sh --bootstrap-server localhost:9092 --list --topic Test-topic
    > bin/kafka-acls.sh --bootstrap-server localhost:9092 --list --topic '*'
    > bin/kafka-acls.sh --bootstrap-server localhost:9092 --list --topic Test-topic --resource-pattern-type match
  • 添加或删除作为生产者或使用者
    的委托人 ACL 管理的最常见用例是将委托人添加/删除作为生产者或消费者,因此我们添加了方便的选项来处理这些情况。为了将 User:Bob 添加为 Test-topic 的生产者,我们可以执行以下命令:类似地,要将 Alice 添加为具有使用者组 Group-1 的 Test-topic 的使用者,我们只需要传递 --consumer 选项:请注意,对于 consumer 选项,我们还必须指定使用者组。 为了从 producer 或 consumer 角色中删除 principal,我们只需要传递 --remove 选项。
    > bin/kafka-acls.sh --bootstrap-server localhost:9092 --add --allow-principal User:Bob --producer --topic Test-topic
    > bin/kafka-acls.sh --bootstrap-server localhost:9092 --add --allow-principal User:Bob --consumer --topic Test-topic --group Group-1 
  • 基于 Admin API 的 acl 管理
    对 ClusterResource 具有 Alter 权限的用户可以使用 Admin API 进行 ACL 管理。kafka-acls.sh 脚本支持 AdminClient API 来管理 ACL,而无需直接与 zookeeper/authorizer 交互。 以上所有示例都可以使用 --bootstrap-server 选项来执行。例如:
    bin/kafka-acls.sh --bootstrap-server localhost:9092 --command-config /tmp/adminclient-configs.conf --add --allow-principal User:Bob --producer --topic Test-topic
    bin/kafka-acls.sh --bootstrap-server localhost:9092 --command-config /tmp/adminclient-configs.conf --add --allow-principal User:Bob --consumer --topic Test-topic --group Group-1
    bin/kafka-acls.sh --bootstrap-server localhost:9092 --command-config /tmp/adminclient-configs.conf --list --topic Test-topic
    bin/kafka-acls.sh --bootstrap-server localhost:9092 --command-config /tmp/adminclient-configs.conf --add --allow-principal User:tokenRequester --operation CreateTokens --user-principal "owner1"

授权原语

协议调用通常是对 Kafka 中的某些资源执行一些作。需要知道 运营和资源来设置有效的保护。在本节中,我们将列出这些作和 资源,然后列出这些与协议的组合以查看有效场景。

Kafka 中的作

有一些作原语可用于构建权限。这些可以匹配 某些资源,以允许给定用户的特定协议调用。这些是:

  • 创造
  • 删除
  • 改变
  • 描述
  • ClusterAction
  • DescribeConfigs 实例
  • AlterConfigs
  • IdempotentWrite
  • CreateTokens
  • 描述令牌
Kafka 中的资源

上述作可应用于某些资源,如下所述。

  • Topic:这只是表示一个 Topic。作用于主题(例如读取、 编写它们)需要添加相应的权限。如果存在 topic 资源,则返回 TOPIC_AUTHORIZATION_FAILED(错误码:29)。
  • Group:表示 Broker 中的消费组。所有与 使用者组(如加入组)必须具有 Subject 中的组的权限。如果权限不是 给定,则协议响应中将返回一个 GROUP_AUTHORIZATION_FAILED(错误代码:30)。
  • Cluster:此资源表示群集。影响整个集群的作,例如 受控关闭受 Cluster 资源的权限保护。如果存在授权问题 在集群资源上,将返回 CLUSTER_AUTHORIZATION_FAILED(错误代码:31)。
  • TransactionalId:此资源表示与事务相关的作,例如提交。 如果发生任何错误,则经纪人将返回 TRANSACTIONAL_ID_AUTHORIZATION_FAILED(错误代码:53)。
  • DelegationToken:这表示集群中的委托 Token。作,例如描述 委派令牌可以通过对 DelegationToken 资源的权限进行保护。由于这些对象具有 Kafka 中的一些特殊行为,建议阅读 KIP-48 和相关的上游文档 使用 委托令牌进行身份验证.
  • 用户:可以将 CreateToken 和 DescribeToken作授予 User 资源,以允许创建和描述 令牌。更多信息可以在 KIP-373 中找到。
协议的作和资源

在下表中,我们将列出对 Kafka API 协议执行的资源的有效作。

协议(API 密钥) 操作 资源 注意
农产品 (0) 事务 ID 设置了 transactional.id 的事务型生产者需要此权限。
农产品 (0) IdempotentWrite 幂等 produce作需要此权限。
农产品 (0) 主题 这适用于普通的 produce作。
获取 (1) ClusterAction 追随者必须在 Cluster 资源上具有 ClusterAction 才能获取分区数据。
获取 (1) 主题 常规 Kafka 使用者需要对他们正在获取的每个分区具有 READ 权限。
LIST_OFFSETS (2) 描述 主题
元数据 (3) 描述 主题
元数据 (3) 创造 如果启用了主题自动创建,则 broker 端 API 将检查是否存在 Cluster 级别权限。如果找到,则允许创建主题,否则它将遍历 主题级别权限(请参阅下一个)。
元数据 (3) 创造 主题 如果启用,这将授权自动创建主题,但给定用户没有集群级别 权限(上文)。
LEADER_AND_ISR (4) ClusterAction
STOP_REPLICA (5) ClusterAction
UPDATE_METADATA (6) ClusterAction
CONTROLLED_SHUTDOWN (7) ClusterAction
OFFSET_COMMIT (8) 只有当偏移量被授权给给定的组和主题时,才能提交偏移量(见下文)。 首先检查组访问权限,然后检查主题访问权限。
OFFSET_COMMIT (8) 主题 由于 offset commit 是使用进程的一部分,因此它需要读取作的权限。
OFFSET_FETCH (9) 描述 与 OFFSET_COMMIT 类似,应用程序也必须具有组和主题级别的权限才能 以获取。但是,在这种情况下,它需要 describe 访问权限而不是 read。首先检查组访问权限, ,然后选择 Topic access(主题访问)。
OFFSET_FETCH (9) 描述 主题
FIND_COORDINATOR (10) 描述 FIND_COORDINATOR请求可以是 “Group” 类型,在这种情况下,它正在查找 consumergroup 协调 员。此权限将代表 Group 模式。
FIND_COORDINATOR (10) 描述 事务 ID 这仅适用于事务 producer,并在 producer 尝试查找事务时进行检查 协调者。
JOIN_GROUP (11)
心跳 (12)
LEAVE_GROUP (13)
SYNC_GROUP (14)
DESCRIBE_GROUPS (15) 描述
LIST_GROUPS (16) 描述 当 broker 检查以授权 list_groups 请求时,它首先检查此集群 级别授权。如果未找到,则继续单独检查组。此作 不会返回 CLUSTER_AUTHORIZATION_FAILED。
LIST_GROUPS (16) 描述 如果没有任何组获得授权,则只会发回空响应 的 error。此作不会返回 CLUSTER_AUTHORIZATION_FAILED。这适用于 2.1 版本。
SASL_HANDSHAKE (17) SASL 握手是身份验证过程的一部分,因此无法 在此处应用任何类型的授权。
API_VERSIONS (18) API_VERSIONS 请求是 Kafka 协议握手的一部分,在连接时发生 以及在任何身份验证之前。因此,无法通过授权来控制这一点。
CREATE_TOPICS (19) 创造 如果没有集群级别的授权,则不会返回 CLUSTER_AUTHORIZATION_FAILED 而是 回退到 Use topic level,它就在下面。如果出现问题,那会引发错误。
CREATE_TOPICS (19) 创造 主题 这从 2.0 版本开始适用。
DELETE_TOPICS (20) 删除 主题
DELETE_RECORDS (21) 删除 主题
INIT_PRODUCER_ID (22) 事务 ID
INIT_PRODUCER_ID (22) IdempotentWrite
OFFSET_FOR_LEADER_EPOCH (23) ClusterAction 如果此作没有集群级别权限,则它将检查主题级别 1。
OFFSET_FOR_LEADER_EPOCH (23) 描述 主题 这从 2.1 版本开始适用。
ADD_PARTITIONS_TO_TXN (24) 事务 ID 此 API 仅适用于事务请求。它首先检查 TransactionalId 资源,然后它会检查主题中的 Topic(如下)。
ADD_PARTITIONS_TO_TXN (24) 主题
ADD_OFFSETS_TO_TXN (25) 事务 ID 与 ADD_PARTITIONS_TO_TXN 类似,这仅适用于事务请求。它首先检查 for Write作,然后它会检查它是否可以对给定组执行 Read作 (下图)。
ADD_OFFSETS_TO_TXN (25)
END_TXN (26) 事务 ID
WRITE_TXN_MARKERS (27) ClusterAction
TXN_OFFSET_COMMIT (28) 事务 ID
TXN_OFFSET_COMMIT (28)
TXN_OFFSET_COMMIT (28) 主题
DESCRIBE_ACLS (29) 描述
CREATE_ACLS (30) 改变
DELETE_ACLS (31) 改变
DESCRIBE_CONFIGS (32) DescribeConfigs 实例 如果请求 broker configs,则 broker 将检查集群级别的权限。
DESCRIBE_CONFIGS (32) DescribeConfigs 实例 主题 如果请求主题配置,则代理将检查主题级别的权限。
ALTER_CONFIGS (33) AlterConfigs 如果 broker 配置被更改,则 broker 将检查集群级别的权限。
ALTER_CONFIGS (33) AlterConfigs 主题 如果主题配置被更改,则 broker 将检查主题级别的权限。
ALTER_REPLICA_LOG_DIRS (34) 改变
DESCRIBE_LOG_DIRS (35) 描述 授权失败时将返回空响应。
SASL_AUTHENTICATE (36) SASL_AUTHENTICATE 是身份验证过程的一部分,因此无法 在此处应用任何类型的授权。
CREATE_PARTITIONS (37) 改变 主题
CREATE_DELEGATION_TOKEN (38) 创建委托令牌有特殊规则,为此,请参阅使用委托令牌进行身份验证部分。
CREATE_DELEGATION_TOKEN (38) CreateTokens 用户 允许为 User 资源创建委派令牌。
RENEW_DELEGATION_TOKEN (39) 续订委托令牌有特殊规则,为此,请参阅使用委托令牌进行身份验证部分。
EXPIRE_DELEGATION_TOKEN (40) 过期委托令牌有特殊规则,为此,请参阅使用委托令牌进行身份验证部分。
DESCRIBE_DELEGATION_TOKEN (41) 描述 DelegationToken 代币 描述委托令牌有特殊规则,为此,请参阅使用委托令牌进行身份验证部分。
DESCRIBE_DELEGATION_TOKEN (41) 描述令牌 用户 允许描述 User 资源的委托令牌。
DELETE_GROUPS (42) 删除
ELECT_PREFERRED_LEADERS (43) ClusterAction
INCREMENTAL_ALTER_CONFIGS (44) AlterConfigs 如果 broker 配置被更改,则 broker 将检查集群级别的权限。
INCREMENTAL_ALTER_CONFIGS (44) AlterConfigs 主题 如果主题配置被更改,则 broker 将检查主题级别的权限。
ALTER_PARTITION_REASSIGNMENTS (45) 改变
LIST_PARTITION_REASSIGNMENTS (46) 描述
OFFSET_DELETE (47) 删除
OFFSET_DELETE (47) 主题
DESCRIBE_CLIENT_QUOTAS (48) DescribeConfigs 实例
ALTER_CLIENT_QUOTAS (49) AlterConfigs
DESCRIBE_USER_SCRAM_CREDENTIALS (50) 描述
ALTER_USER_SCRAM_CREDENTIALS (51) 改变
投票 (52) ClusterAction
BEGIN_QUORUM_EPOCH (53) ClusterAction
END_QUORUM_EPOCH (54) ClusterAction
DESCRIBE_QUORUM (55) 描述
ALTER_PARTITION (56) ClusterAction
UPDATE_FEATURES (57) 改变
信封 (58) ClusterAction
FETCH_SNAPSHOT (59) ClusterAction
DESCRIBE_CLUSTER (60) 描述
DESCRIBE_PRODUCERS (61) 主题
BROKER_REGISTRATION (62) ClusterAction
BROKER_HEARTBEAT (63) ClusterAction
UNREGISTER_BROKER (64) 改变
DESCRIBE_TRANSACTIONS (65) 描述 事务 ID
LIST_TRANSACTIONS (66) 描述 事务 ID
ALLOCATE_PRODUCER_IDS (67) ClusterAction
CONSUMER_GROUP_HEARTBEAT (68)

7.6 在正在运行的群集中合并安全功能

您可以通过前面讨论的一个或多个受支持的协议来保护正在运行的集群。这是分阶段完成的:

  • 逐步退回群集节点以打开其他安全端口。
  • 使用 secured 而不是 PLAINTEXT 端口重新启动客户端(假设您正在保护客户端-代理连接)。
  • 再次以增量方式退回集群以启用代理到代理安全性(如果需要)
  • 用于关闭 PLAINTEXT 端口的最后一次增量退回。

7.3 节和第 7.4 节中介绍了配置 SSL 和 SASL 的具体步骤。 按照以下步骤为所需的协议启用安全性。 安全实现允许您为 broker-client 和 broker-broker 通信配置不同的协议。 这些必须在单独的退回邮件中启用。PLAINTEXT 端口必须始终保持打开状态,以便代理和/或客户端可以继续通信。 当执行增量退回时,通过 SIGTERM 干净地停止 broker。在移动到下一个节点之前,等待重新启动的副本返回到 ISR 列表也是一种很好的做法。 例如,假设我们希望使用 SSL 加密 broker-client 和 broker-broker 通信。在第一次增量退回中,在每个节点上打开一个 SSL 端口:然后我们重新启动客户端,将其配置更改为指向新打开的安全端口:在第二次增量服务器退回中,我们指示 Kafka 使用 SSL 作为代理协议(将使用相同的 SSL 端口):在最后一次退回中,我们通过关闭 PLAINTEXT 端口来保护集群: 或者,我们可以选择开放多个端口,以便可以使用不同的协议进行 broker-broker 和 broker-client 通信。假设我们希望在整个过程中使用 SSL 加密(即用于代理-代理和代理-客户端通信),但我们也想将 SASL 身份验证添加到代理-客户端连接中。我们将通过在第一次跳出时打开两个额外的端口来实现这一点:然后我们将重新启动客户端,将其配置更改为指向新打开的SASL和SSL安全端口::第二次服务器跳出将集群切换到通过我们之前在9092端口打开的SSL端口使用加密的经纪人-代理通信: 最后一次退回通过关闭 PLAINTEXT 端口来保护集群。 ZooKeeper 可以独立于 Kafka 集群进行保护。执行此作的步骤在 Section 7.7.2 中介绍。

listeners=PLAINTEXT://broker1:9091,SSL://broker1:9092
bootstrap.servers = [broker1:9092,...]
security.protocol = SSL
...etc
listeners=PLAINTEXT://broker1:9091,SSL://broker1:9092
security.inter.broker.protocol=SSL
listeners=SSL://broker1:9092
security.inter.broker.protocol=SSL
listeners=PLAINTEXT://broker1:9091,SSL://broker1:9092,SASL_SSL://broker1:9093
bootstrap.servers = [broker1:9093,...]
security.protocol = SASL_SSL
...etc
listeners=PLAINTEXT://broker1:9091,SSL://broker1:9092,SASL_SSL://broker1:9093
security.inter.broker.protocol=SSL
listeners=SSL://broker1:9092,SASL_SSL://broker1:9093
security.inter.broker.protocol=SSL

7.7 ZooKeeper 身份验证

ZooKeeper 从 3.5.x 版本开始支持双向 TLS (mTLS) 身份验证。 Kafka 支持使用 SASL 和 mTLS 向 ZooKeeper 进行身份验证 - 单独或同时进行身份验证 - 从 2.5 版本开始。有关更多详细信息,请参阅 KIP-515:启用 ZK 客户端以使用新的 TLS 支持的身份验证

单独使用 mTLS 时,每个代理和任何 CLI 工具(例如 ZooKeeper 安全迁移工具) 应使用相同的可分辨名称 (DN) 标识自身,因为它是经过 ACL 处理的 DN。 这可以如下所述进行更改,但它涉及编写和部署自定义 ZooKeeper 身份验证提供程序。 通常,每个证书应具有相同的 DN,但具有不同的使用者备用名称 (SAN) 这样 ZooKeeper 对代理和任何 CLI 工具的主机名验证就会成功。

当对 ZooKeeper 使用 SASL 身份验证和 mTLS 时,SASL 身份和 创建 znode 的 DN(即创建代理的证书) 或 Security Migration Tool 的 DN(如果在创建 znode 后执行迁移) 将被 ACL 化,并且所有 broker 和 CLI 工具都将被授权,即使它们都使用不同的 DN ,因为它们都将使用相同的 ACL 化 SASL 身份。 只有当单独使用 mTLS 身份验证时,所有 DN 都必须匹配(并且 SAN 变得至关重要 -- 同样,在没有编写和部署自定义 ZooKeeper 身份验证提供程序的情况下,如下所述)。

使用 broker 属性文件为 broker 设置 TLS 配置,如下所述。

使用 --zk-tls-config-file <file> 选项在 Zookeeper Security Migration Tool 中设置 TLS 配置。 kafka-acls.shkafka-configs.sh CLI 工具还支持 --zk-tls-config-file <file> 选项。

使用 -zk-tls-config-file <file> 选项(注意单破折号而不是双破折号) 为 zookeeper-shell.sh CLI 工具设置 TLS 配置。

7.7.1 新集群

7.7.1.1 ZooKeeper SASL 身份验证
要在代理上启用 ZooKeeper SASL 身份验证,需要执行两个必要的步骤:
  1. 如上所述,创建一个 JAAS 登录文件并设置相应的系统属性以指向它
  2. 将每个代理中的配置属性 zookeeper.set.acl 设置为 true
Kafka 集群的 ZooKeeper 中存储的元数据是全局可读的,但只能由代理修改。此决定背后的基本原理是 ZooKeeper 中存储的数据并不敏感,但对这些数据的不当作可能会导致集群中断。我们还建议通过网络分段来限制对 ZooKeeper 的访问(只有代理和一些管理工具需要访问 ZooKeeper)。
7.7.1.2 ZooKeeper 双向 TLS 身份验证
ZooKeeper mTLS 身份验证可以在有或没有 SASL 身份验证的情况下启用。如上所述, 单独使用 mTLS 时,每个代理和任何 CLI 工具(例如 ZooKeeper Security Migration Tool) 通常必须使用相同的可分辨名称 (DN) 标识自身,因为它是经过 ACL 处理的 DN,这意味着 每个证书都应具有适当的使用者备用名称 (SAN),以便 ZooKeeper 对代理和任何 CLI 工具的主机名验证都将成功。

可以通过编写一个类来使用 DN 以外的其他内容作为 mTLS 客户端的身份 扩展了 org.apache.zookeeper.server.auth.X509AuthenticationProvider 并覆盖了受保护的方法 String getClientId(X509Certificate clientCert)。 选择 scheme 名称并设置 authProvider。scheme] 作为完全限定的类名 自定义实现;然后设置 ssl.authProvider=[scheme] 来使用它。

以下是用于启用 TLS 身份验证的 (部分) ZooKeeper 配置示例。 这些配置在 ZooKeeper 管理指南中进行了介绍。 重要说明:ZooKeeper 不支持在 ZooKeeper 服务器密钥库中设置密钥密码 设置为不同于 keystore 密码本身的值。 请务必将密钥密码设置为与密钥库密码相同。
secureClientPort=2182
serverCnxnFactory=org.apache.zookeeper.server.NettyServerCnxnFactory
authProvider.x509=org.apache.zookeeper.server.auth.X509AuthenticationProvider
ssl.keyStore.location=/path/to/zk/keystore.jks
ssl.keyStore.password=zk-ks-passwd
ssl.trustStore.location=/path/to/zk/truststore.jks
ssl.trustStore.password=zk-ts-passwd

以下是使用 mTLS 身份验证连接到 ZooKeeper 的(部分)Kafka 代理配置示例。 这些配置在上文的 Broker Config 中进行了介绍。

# connect to the ZooKeeper port configured for TLS
zookeeper.connect=zk1:2182,zk2:2182,zk3:2182
# required to use TLS to ZooKeeper (default is false)
zookeeper.ssl.client.enable=true
# required to use TLS to ZooKeeper
zookeeper.clientCnxnSocket=org.apache.zookeeper.ClientCnxnSocketNetty
# define key/trust stores to use TLS to ZooKeeper; ignored unless zookeeper.ssl.client.enable=true
zookeeper.ssl.keystore.location=/path/to/kafka/keystore.jks
zookeeper.ssl.keystore.password=kafka-ks-passwd
zookeeper.ssl.truststore.location=/path/to/kafka/truststore.jks
zookeeper.ssl.truststore.password=kafka-ts-passwd
# tell broker to create ACLs on znodes
zookeeper.set.acl=true
重要说明:ZooKeeper 不支持在 ZooKeeper 客户端(即代理)密钥库中设置密钥密码 设置为不同于 keystore 密码本身的值。 请务必将密钥密码设置为与密钥库密码相同。

7.7.2 迁移集群

如果您运行的 Kafka 版本不支持安全性或只是禁用了安全性,并且您希望确保集群安全,则需要执行以下步骤来启用 ZooKeeper 身份验证,同时将对作的中断降至最低:
  1. 在 ZooKeeper 上启用 SASL 和/或 mTLS 身份验证。如果启用 mTLS,您现在将同时拥有一个非 TLS 端口和一个 TLS 端口,如下所示:
    clientPort=2181
    secureClientPort=2182
    serverCnxnFactory=org.apache.zookeeper.server.NettyServerCnxnFactory
    authProvider.x509=org.apache.zookeeper.server.auth.X509AuthenticationProvider
    ssl.keyStore.location=/path/to/zk/keystore.jks
    ssl.keyStore.password=zk-ks-passwd
    ssl.trustStore.location=/path/to/zk/truststore.jks
    ssl.trustStore.password=zk-ts-passwd
  2. 根据需要滚动重启代理,设置 JAAS 登录文件和/或定义 ZooKeeper 双向 TLS 配置(包括连接到支持 TLS 的 ZooKeeper 端口),使代理能够向 ZooKeeper 进行身份验证。在滚动重启结束时,代理能够使用严格的 ACL作 znode,但它们不会使用这些 ACL 创建 znodes
  3. 如果启用了 mTLS,请在 ZooKeeper 中禁用非 TLS 端口
  4. 执行代理的第二次滚动重启,这次将配置参数 zookeeper.set.acl 设置为 true,这样就可以在创建 znodes 时使用安全 ACL
  5. 执行 ZkSecurityMigrator 工具。要执行该工具,可以使用以下脚本:bin/zookeeper-security-migration.sh并将 zookeeper.acl 设置为 secure。此工具遍历相应的子树,更改 znodes 的 ACL。使用--zk-tls-config-file <file>选项(如果启用 mTLS)。

还可以在安全集群中关闭身份验证。为此,请按照下列步骤作:

  1. 通过设置 JAAS 登录文件和/或定义 ZooKeeper 双向 TLS 配置来滚动重启代理,使代理能够进行身份验证,但将 zookeeper.set.acl 设置为 false。在滚动重启结束时,代理停止创建具有安全 ACL 的 znode,但仍然能够验证和作所有 znodes
  2. 执行 ZkSecurityMigrator 工具。要执行该工具,请在 zookeeper.acl 设置为 unsecure 的情况下运行此脚本 bin/zookeeper-security-migration.sh。此工具遍历相应的子树,更改 znodes 的 ACL。使用--zk-tls-config-file <file>选项(如果需要设置 TLS 配置)。
  3. 如果要禁用 mTLS,请在 ZooKeeper 中启用非 TLS 端口
  4. 执行代理的第二次滚动重启,这次省略设置 JAAS 登录文件的 system 属性和/或根据需要删除 ZooKeeper 双向 TLS 配置(包括连接到未启用 TLS 的 ZooKeeper 端口)
  5. 如果要禁用 mTLS,请在 ZooKeeper 中禁用 TLS 端口
以下是如何运行迁移工具的示例:
> bin/zookeeper-security-migration.sh --zookeeper.acl=secure --zookeeper.connect=localhost:2181

运行此命令可查看参数的完整列表:

> bin/zookeeper-security-migration.sh --help

7.7.3 迁移 ZooKeeper ensemble

还需要在 ZooKeeper 集合上启用 SASL 和/或 mTLS 身份验证。为此,我们需要执行服务器的滚动重启并设置一些属性。有关 mTLS 信息,请参阅上文。有关详细信息,请参阅 ZooKeeper 文档:
  1. Apache ZooKeeper 文档
  2. Apache ZooKeeper 维基

7.7.4 ZooKeeper Quorum 双向 TLS 身份验证

可以在 ZooKeeper 服务器本身之间启用 mTLS 身份验证。 有关更多详细信息,请参阅 ZooKeeper 文档

7.8 ZooKeeper 加密

使用双向 TLS 的 ZooKeeper 连接将被加密。 从 ZooKeeper 版本 3.5.7(Kafka 版本 2.5 附带的版本)开始,ZooKeeper 支持服务器端配置 ssl.clientAuth(不区分大小写:want/need/none 是有效选项,默认是 need), 在 ZooKeeper 中将此值设置为 none 允许客户端通过 TLS 加密连接进行连接 而无需出示自己的证书。以下是仅使用 TLS 加密连接到 ZooKeeper 的(部分)Kafka 代理配置示例。 这些配置在上文的 Broker Config 中进行了介绍。
# connect to the ZooKeeper port configured for TLS
zookeeper.connect=zk1:2182,zk2:2182,zk3:2182
# required to use TLS to ZooKeeper (default is false)
zookeeper.ssl.client.enable=true
# required to use TLS to ZooKeeper
zookeeper.clientCnxnSocket=org.apache.zookeeper.ClientCnxnSocketNetty
# define trust stores to use TLS to ZooKeeper; ignored unless zookeeper.ssl.client.enable=true
# no need to set keystore information assuming ssl.clientAuth=none on ZooKeeper
zookeeper.ssl.truststore.location=/path/to/kafka/truststore.jks
zookeeper.ssl.truststore.password=kafka-ts-passwd
# tell broker to create ACLs on znodes (if using SASL authentication, otherwise do not set this)
zookeeper.set.acl=true

8.1 概述

Kafka Connect 是一种工具,用于在 Apache Kafka 和其他系统之间可扩展且可靠地流式传输数据。它使快速定义将大量数据移入和移出 Kafka 的连接器变得简单。Kafka Connect 可以将整个数据库或所有应用程序服务器的指标收集到 Kafka 主题中,从而使数据可用于低延迟的流处理。导出作业可以将 Kafka 主题中的数据传送到辅助存储和查询系统或批处理系统以进行离线分析。

Kafka Connect 功能包括:

  • Kafka 连接器的通用框架 - Kafka Connect 标准化了其他数据系统与 Kafka 的集成,从而简化了连接器的开发、部署和管理
  • 分布式和独立模式 - 纵向扩展到支持整个组织的大型集中管理服务,或缩减到开发、测试和小型生产部署
  • REST 接口 - 通过易于使用的 REST API 向 Kafka Connect 集群提交和管理连接器
  • 自动偏移管理 - 只需来自连接器的少量信息,Kafka Connect 就可以自动管理偏移提交过程,因此连接器开发人员无需担心连接器开发中容易出错的部分
  • 默认情况下是分布式和可扩展的 - Kafka Connect 基于现有的组管理协议构建。可以添加更多工作线程来扩展 Kafka Connect 集群。
  • 流/批处理集成 - 利用 Kafka 的现有功能,Kafka Connect 是桥接流和批处理数据系统的理想解决方案

8.2 用户指南

本快速入门提供了有关如何运行 Kafka Connect 独立版本的简短示例。本节更详细地介绍如何配置、运行和管理 Kafka Connect。

运行 Kafka Connect

Kafka Connect 目前支持两种执行模式:独立(单个进程)和分布式。

在独立模式下,所有工作都在单个进程中执行。此配置更易于设置和入门,并且在只有一个工作线程有意义的情况下(例如收集日志文件)可能很有用,但它不会受益于 Kafka Connect 的某些功能,例如容错。您可以使用以下命令启动独立进程:

> bin/connect-standalone.sh config/connect-standalone.properties [connector1.properties connector2.properties ...]

第一个参数是 worker 的配置。这包括 Kafka 连接参数、序列化格式和提交偏移量的频率等设置。提供的示例应该可以很好地与使用由config/server.properties.它需要进行调整才能用于不同的配置或生产部署。所有 worker(独立和分布式)都需要一些配置:

  • bootstrap.servers- 用于引导到 Kafka 的连接的 Kafka 服务器列表
  • key.converter- Converter 类,用于在 Kafka Connect 格式和写入 Kafka 的序列化形式之间进行转换。这控制写入 Kafka 或从 Kafka 读取的消息中键的格式,并且由于这与连接器无关,因此它允许任何连接器使用任何序列化格式。常见格式的示例包括 JSON 和 Avro。
  • value.converter- Converter 类,用于在 Kafka Connect 格式和写入 Kafka 的序列化形式之间进行转换。这控制写入 Kafka 或从 Kafka 读取的消息中值的格式,并且由于这与连接器无关,因此它允许任何连接器使用任何序列化格式。常见格式的示例包括 JSON 和 Avro。
  • plugin.path(默认empty) - 包含 Connect 插件(连接器、转换器、转换)的路径列表。在运行快速入门之前,用户必须添加绝对路径,其中包含打包在connect-file-"version".jar,因为默认情况下,这些连接器不包含在CLASSPATHplugin.path的 Connect工作程序(有关示例,请参阅 plugin.path 属性)。

特定于独立模式的重要配置选项包括:

  • offset.storage.file.filename- 用于存储源连接器偏移量的文件

此处配置的参数适用于 Kafka Connect 用于访问配置、偏移和状态主题的创建者和使用者。对于 Kafka 源任务使用的生产者和 Kafka Sink 任务使用的消费者的配置,可以使用相同的参数,但需要以producer.consumer.分别。从 worker 配置中继承的唯一不带前缀的 Kafka 客户端参数是bootstrap.servers,这在大多数情况下就足够了,因为同一个集群通常用于所有目的。一个值得注意的例外是安全集群,它需要额外的参数才能允许连接。这些参数需要在工作程序配置中设置最多三次,一次用于管理访问,一次用于 Kafka 源,一次用于 Kafka 接收器。

从 2.3.0 开始,可以使用前缀为每个连接器单独配置客户端配置覆盖producer.override.consumer.override.分别用于 Kafka 源或 Kafka 接收器。这些覆盖包含在连接器的其余配置属性中。

其余参数是连接器配置文件。您可以根据需要包含任意数量的作,但所有作都将在同一进程中执行(在不同的线程上)。您还可以选择不在命令行上指定任何连接器配置文件,而是在独立工作程序启动后使用 REST API 在运行时创建连接器。

分布式模式处理工作的自动平衡,允许您动态扩展(或缩减),并在活动任务以及配置和偏移提交数据中提供容错能力。执行方式与独立模式非常相似:

> bin/connect-distributed.sh config/connect-distributed.properties

区别在于启动的类和配置参数,这些参数会改变 Kafka Connect 进程决定存储配置的位置、如何分配工作以及存储偏移量和任务状态的位置。在分布式模式下,Kafka Connect 将偏移量、配置和任务状态存储在 Kafka 主题中。建议手动创建 offset、configs 和 statuss 的主题,以实现所需的分区数和复制因子。如果在启动 Kafka Connect 时尚未创建主题,则将使用默认分区数和复制因子自动创建主题,这可能不是最适合其用途。

特别是,除了上述常见设置外,在启动集群之前,设置以下配置参数也至关重要:

  • group.id(默认connect-cluster) - 集群的唯一名称,用于形成 Connect 集群组;注意,这不能与 Consumer Group ID 冲突
  • config.storage.topic(默认connect-configs) - 用于存储连接器和任务配置的主题;请注意,这应该是一个单分区、高度复制、压缩的主题。您可能需要手动创建主题以确保正确的配置,因为自动创建的主题可能具有多个分区,或者自动配置为删除而不是压缩
  • offset.storage.topic(默认connect-offsets) - 用于存储偏移量的主题;本主题应具有许多分区、可复制并配置为压缩
  • status.storage.topic(默认connect-status) - 用于存储状态的主题;此主题可以有多个分区,应进行复制和配置以进行压缩

请注意,在分布式模式下,连接器配置不会在命令行上传递。相反,请使用下面描述的 REST API 来创建、修改和销毁连接器。

配置连接器

连接器配置是简单的键值映射。在独立模式和分布式模式下,它们都包含在创建(或修改)连接器的 REST 请求的 JSON 负载中。在独立模式下,这些也可以在属性文件中定义,并在命令行上传递给 Connect 进程。

大多数配置都依赖于连接器,因此无法在此处概述。但是,有一些常见的选项:

  • name- 连接器的唯一名称。尝试使用相同的名称再次注册将失败。
  • connector.class- 连接器的 Java 类
  • tasks.max- 应为此连接器创建的最大任务数。如果连接器无法达到此级别的并行度,则可能会创建更少的任务。
  • key.converter- (可选) 覆盖 worker 设置的默认密钥转换器。
  • value.converter- (可选) 覆盖 worker 设置的默认值转换器。

connector.classConfig 支持多种格式:此连接器的类的全名或别名。如果连接器是 org.apache.kafka.connect.file.FileStreamSinkConnector,则可以指定此全名,也可以使用 FileStreamSink 或 FileStreamSinkConnector 使配置更短一些。

Sink 连接器还有一些额外的选项来控制它们的输入。每个 sink connector 必须设置以下选项之一:

  • topics- 要用作此连接器输入的主题的逗号分隔列表
  • topics.regex- 要用作此连接器输入的主题的 Java 正则表达式

对于任何其他选项,您应该查阅连接器的文档。

转换

连接器可以配置转换,以进行轻量级的一次发送消息修改。它们可以方便地进行数据处理和事件路由。

可以在 connector 配置中指定转换链。

  • transforms- 转换的别名列表,指定转换的应用顺序。
  • transforms.$alias.type- 转换的完全限定类名。
  • transforms.$alias.$transformationSpecificConfig转换的配置属性

例如,让我们使用内置的文件源连接器,并使用转换来添加静态字段。

在整个示例中,我们将使用无架构 JSON 数据格式。为了使用 schemaless 格式,我们在connect-standalone.properties从 true 到 false:

key.converter.schemas.enable
value.converter.schemas.enable

文件源连接器将每行读取为 String。我们将每行包装在 Map 中,然后添加第二个字段来标识事件的来源。为此,我们使用两个转换:

  • HoistField 将输入行放置在 Map 中
  • InsertField 添加静态字段。在此示例中,我们将指示记录来自文件连接器

添加转换后,connect-file-source.properties文件如下所示:

name=local-file-source
connector.class=FileStreamSource
tasks.max=1
file=test.txt
topic=connect-test
transforms=MakeMap, InsertSource
transforms.MakeMap.type=org.apache.kafka.connect.transforms.HoistField$Value
transforms.MakeMap.field=line
transforms.InsertSource.type=org.apache.kafka.connect.transforms.InsertField$Value
transforms.InsertSource.static.field=data_source
transforms.InsertSource.static.value=test-file-source

所有以transforms已添加以进行转换。您可以看到我们创建的两个转换:“InsertSource”和“MakeMap”是我们选择用于提供转换的别名。转换类型基于您在下面看到的内置转换列表。每种转换类型都有额外的配置:HoistField 需要一个名为“field”的配置,该配置是映射中字段的名称,该字段将包含文件中的原始 String。InsertField 转换允许我们指定字段名称和要添加的值。

当我们在没有转换的情况下对示例文件运行文件源连接器,然后使用kafka-console-consumer.sh,结果是:

"foo"
"bar"
"hello world"

然后,我们创建一个新的文件连接器,这次是在将转换添加到配置文件之后。这一次,结果将是:

{"line":"foo","data_source":"test-file-source"}
{"line":"bar","data_source":"test-file-source"}
{"line":"hello world","data_source":"test-file-source"}

您可以看到,我们读取的行现在是 JSON map 的一部分,并且还有一个额外的字段,其中包含我们指定的 static 值。这只是您可以使用转换执行的作的一个示例。

包含的转换

Kafka Connect 包含几个广泛适用的数据和路由转换:

  • InsertField - 使用静态数据或记录元数据添加字段
  • ReplaceField - 筛选或重命名字段
  • MaskField - 将字段替换为类型的有效 null 值(0、空字符串等)或自定义替换(仅限非空字符串或数值)
  • ValueToKey - 将记录键替换为由记录值中的字段子集组成的新键
  • HoistField - 将整个事件作为单个字段包装在 Struct 或 Map 中
  • ExtractField - 从 Struct 和 Map 中提取特定字段,并在结果中仅包含此字段
  • SetSchemaMetadata - 修改架构名称或版本
  • TimestampRouter - 根据原始主题和时间戳修改记录的主题。当使用需要根据时间戳写入不同表或索引的 sink 时很有用
  • RegexRouter - 根据原始主题、替换字符串和正则表达式修改记录的主题
  • Filter - 从所有进一步处理中删除消息。这与谓词一起使用,以选择性地筛选某些消息。
  • InsertHeader - 使用静态数据添加标头
  • HeadersFrom - 将键或值中的字段复制或移动到记录标题
  • DropHeaders - 按名称删除标头

下面列出了有关如何配置每个转换的详细信息:

org.apache.kafka.connect.transforms.InsertField
使用记录元数据中的属性或配置的静态值插入字段。

使用为记录键 (org.apache.kafka.connect.transforms.InsertField$Key) 或值 (org.apache.kafka.connect.transforms.InsertField$Value).

  • offset.field

    Kafka 偏移量的字段名称 - 仅适用于接收器连接器。
    后缀
    !将此字段设为必填字段,或者?将其保持为可选 (默认)。

    类型:字符串
    默认值:
    取值:
    重要性:中等
  • 分区.字段

    Kafka 分区的字段名称。后缀!将此字段设为必填字段,或者?将其保持为可选 (默认)。

    类型:字符串
    默认值:
    取值:
    重要性:中等
  • 静态字段

    静态数据字段的字段名称。后缀!将此字段设为必填字段,或者?将其保持为可选 (默认)。

    类型:字符串
    默认值:
    取值:
    重要性:中等
  • 静态值

    静态字段值(如果配置了字段名称)。

    类型:字符串
    默认值:
    取值:
    重要性:中等
  • 时间戳.field

    记录时间戳的字段名称。后缀!将此字段设为必填字段,或者?将其保持为可选 (默认)。

    类型:字符串
    默认值:
    取值:
    重要性:中等
  • topic.field (主题字段)

    Kafka 主题的字段名称。后缀!将此字段设为必填字段,或者?将其保持为可选 (默认)。

    类型:字符串
    默认值:
    取值:
    重要性:中等
org.apache.kafka.connect.transforms.ReplaceField
筛选或重命名字段。

使用为记录键 (org.apache.kafka.connect.transforms.ReplaceField$Key) 或值 (org.apache.kafka.connect.transforms.ReplaceField$Value).

  • 排除

    要排除的字段。这优先于要包含的字段。

    类型:列表
    默认值:""
    取值:
    重要性:中等
  • 包括

    要包含的字段。如果指定,则仅使用这些字段。

    类型:列表
    默认值:""
    取值:
    重要性:中等
  • 重 命名

    字段重命名映射。

    类型:列表
    默认值:""
    取值:冒号分隔对的列表,例如foo:bar,abc:xyz
    重要性:中等
  • 黑名单

    荒废的。请改用 exclude。

    类型:列表
    默认值:
    取值:
    重要性:
  • 白名单

    荒废的。请改用 include。

    类型:列表
    默认值:
    取值:
    重要性:
org.apache.kafka.connect.transforms.MaskField
使用字段类型的有效 null 值(即 0、false、空字符串等)屏蔽指定的字段。

对于数字和字符串字段,可以指定一个可选的替换值,该值将转换为正确的类型。

使用为记录键 (org.apache.kafka.connect.transforms.MaskField$Key) 或值 (org.apache.kafka.connect.transforms.MaskField$Value).

  • 领域

    要屏蔽的字段的名称。

    类型:列表
    默认值:
    取值:非空列表
    重要性:
  • 更换

    自定义值替换,将应用于所有 'fields' 值(仅限数字或非空字符串值)。

    类型:字符串
    默认值:
    取值:非空字符串
    重要性:
org.apache.kafka.connect.transforms.ValueToKey
将记录键替换为由记录值中的字段子集组成的新键。

  • 领域

    要提取为记录键的记录值上的字段名称。

    类型:列表
    默认值:
    取值:非空列表
    重要性:
org.apache.kafka.connect.transforms.HoistField
如果存在 schema,则使用 Struct 中的指定字段名称包装数据,如果是无 schema数据,则使用 Map。

使用为记录键 (org.apache.kafka.connect.transforms.HoistField$Key) 或值 (org.apache.kafka.connect.transforms.HoistField$Value).

  • 将在生成的 Struct 或 Map 中创建的单个字段的字段名称。

    类型:字符串
    默认值:
    取值:
    重要性:中等
org.apache.kafka.connect.transforms.ExtractField
如果存在 Schema,则从 Struct 中提取指定的字段,如果是 Schemaless 数据,则从 Map 中提取指定的字段。任何 null 值都以未修改的方式传递。

使用为记录键 (org.apache.kafka.connect.transforms.ExtractField$Key) 或值 (org.apache.kafka.connect.transforms.ExtractField$Value).

  • 要提取的字段名称。

    类型:字符串
    默认值:
    取值:
    重要性:中等
org.apache.kafka.connect.transforms.SetSchemaMetadata
在记录的键 (org.apache.kafka.connect.transforms.SetSchemaMetadata$Key) 或值 (org.apache.kafka.connect.transforms.SetSchemaMetadata$Value) 架构。

  • schema.name

    要设置的 Schema name。

    类型:字符串
    默认值:
    取值:
    重要性:
  • 架构版本(schema.version)

    要设置的 Schema 版本。

    类型:int
    默认值:
    取值:
    重要性:
org.apache.kafka.connect.transforms.TimestampRouter
将记录的 topic 字段更新为原始 topic 值和记录时间戳的函数。

这主要对接收器连接器有用,因为 topic 字段通常用于确定目标系统中的等效实体名称(例如数据库表或搜索索引名称)。

  • 时间戳.format

    与 兼容的时间戳的格式字符串java.text.SimpleDateFormat.

    类型:字符串
    默认值:yyyyMMdd
    取值:
    重要性:
  • topic.format 格式

    格式字符串,可以包含${topic}${timestamp}分别作为 topic 和 timestamp 的占位符。

    类型:字符串
    默认值:${topic}-${timestamp}
    取值:
    重要性:
org.apache.kafka.connect.transforms.RegexRouter
使用配置的正则表达式和替换字符串更新记录主题。

在后台,正则表达式被编译为java.util.regex.Pattern.如果模式与输入主题匹配,则java.util.regex.Matcher#replaceFirst()与替换字符串一起使用,以获取新 Topic。

  • 正则表达式

    用于匹配的正则表达式。

    类型:字符串
    默认值:
    取值:有效的正则表达式
    重要性:
  • 更换

    替换字符串。

    类型:字符串
    默认值:
    取值:
    重要性:
org.apache.kafka.connect.transforms.Flatten
拼合嵌套数据结构,通过将每个级别的字段名称与可配置的分隔符字符连接起来,为每个字段生成名称。当 schema 存在时适用于 Struct,如果是 schemaless,则适用于 Map。数组字段及其内容不会被修改。默认分隔符为 '.'。

使用为记录键 (org.apache.kafka.connect.transforms.Flatten$Key) 或值 (org.apache.kafka.connect.transforms.Flatten$Value).

  • 定界符

    为输出记录生成字段名称时,用于在输入记录的字段名称之间插入的分隔符

    类型:字符串
    默认值:.
    取值:
    重要性:中等
org.apache.kafka.connect.transforms.Cast
将字段或整个键或值转换为特定类型,例如,强制将整数字段转换为较小的宽度。从整数、浮点数、布尔值和字符串转换为任何其他类型,并将二进制文件转换为字符串(base64 编码)。

使用为记录键 (org.apache.kafka.connect.transforms.Cast$Key) 或值 (org.apache.kafka.connect.transforms.Cast$Value).

  • 规范

    字段列表和要将它们转换为的类型 field1:type,field2:type 格式为 Maps,或者 Structs。用于强制转换整个值的单个类型。有效类型包括 int8、int16、int32、int64、float32、float64、boolean 和 string。请注意,二进制字段只能转换为 string。

    类型:列表
    默认值:
    取值:冒号分隔对的列表,例如foo:bar,abc:xyz
    重要性:
org.apache.kafka.connect.transforms.TimestampConverter
在不同格式之间转换时间戳,例如 Unix 纪元、字符串和 Connect Date/Timestamp 类型。适用于单个字段或整个值。

使用为记录键 (org.apache.kafka.connect.transforms.TimestampConverter$Key) 或值 (org.apache.kafka.connect.transforms.TimestampConverter$Value).

  • target.type

    所需的时间戳表示形式:string、unix、Date、Time 或 Timestamp

    类型:字符串
    默认值:
    取值:[字符串、unix、日期、时间、时间戳]
    重要性:
  • 包含时间戳的字段,如果整个值是时间戳,则为空

    类型:字符串
    默认值:""
    取值:
    重要性:
  • 格式

    时间戳的 SimpleDateFormat 兼容格式。用于在 type=string 时生成输出,如果 input 是字符串,则用于解析 Importing。

    类型:字符串
    默认值:""
    取值:
    重要性:中等
  • unix.precision

    时间戳所需的 Unix 精度:秒、毫秒、微秒或纳秒。用于在 type=unix 时生成输出,如果输入为 Long,则用于解析输入。注意:此 SMT 将在与具有亚毫秒分量的值之间的转换过程中导致精度损失。

    类型:字符串
    默认值:毫秒
    取值:[纳秒、微秒、毫秒、秒]
    重要性:
org.apache.kafka.connect.transforms.Filter
删除所有记录,从链中的后续转换中筛选这些记录。这旨在有条件地用于筛选出与特定 Predicate 匹配(或不匹配)的记录。

org.apache.kafka.connect.transforms.InsertHeader
向每条记录添加标题。

  • 页眉

    标头的名称。

    类型:字符串
    默认值:
    取值:非 null 字符串
    重要性:
  • value.literal

    要设置为所有记录的标头值的 Literal 值。

    类型:字符串
    默认值:
    取值:非 null 字符串
    重要性:
org.apache.kafka.connect.transforms.DropHeaders
从每条记录中删除一个或多个标题。

  • 要删除的标头的名称。

    类型:列表
    默认值:
    取值:非空列表
    重要性:
org.apache.kafka.connect.transforms.HeaderFrom
将记录的键/值中的字段移动或复制到该记录的标题中。的相应元素fieldsheaders一起标识字段及其应移动或复制到的标题。使用为记录键 (org.apache.kafka.connect.transforms.HeaderFrom$Key) 或值 (org.apache.kafka.connect.transforms.HeaderFrom$Value).

  • 领域

    记录中其值将被复制或移动到标题的字段名称。

    类型:列表
    默认值:
    取值:非空列表
    重要性:
  • 标头名称,与 fields 配置属性中列出的字段名称的顺序相同。

    类型:列表
    默认值:
    取值:非空列表
    重要性:
  • 操作

    move如果要将字段移动到标题(从 Key/Value 中删除),或者copy如果要将字段复制到标题(保留在键/值中)。

    类型:字符串
    默认值:
    取值:[移动、复制]
    重要性:
谓词

可以使用谓词配置转换,以便仅将转换应用于满足某些条件的消息。特别是,当与 Filter 转换结合使用时,可以使用谓词选择性地筛选出某些消息。

谓词在连接器配置中指定。

  • predicates- 要应用于某些转换的谓词的别名集。
  • predicates.$alias.type- 谓词的完全限定类名。
  • predicates.$alias.$predicateSpecificConfig- 谓词的配置属性。

所有转换都具有隐式 config 属性predicatenegate.通过设置转换的predicateconfig 设置为谓词的别名。谓词的值可以使用negateconfiguration 属性。

例如,假设您有一个源连接器,该连接器会生成针对许多不同主题的邮件,并且您希望:

  • 完全过滤掉 'foo' 主题中的消息
  • 将字段名称为“other_field”的 ExtractField 转换应用于除主题“bar”之外的所有主题中的记录

为此,我们首先需要过滤掉目标为 'foo' 主题的记录。Filter 转换从进一步处理中删除记录,并且可以使用 TopicNameMatches 谓词仅将转换应用于与特定正则表达式匹配的主题中的记录。TopicNameMatches 的唯一配置属性是pattern,这是一个 Java 正则表达式,用于匹配主题名称。配置将如下所示:

transforms=Filter
transforms.Filter.type=org.apache.kafka.connect.transforms.Filter
transforms.Filter.predicate=IsFoo

predicates=IsFoo
predicates.IsFoo.type=org.apache.kafka.connect.transforms.predicates.TopicNameMatches
predicates.IsFoo.pattern=foo

接下来,我们只需要在记录的主题名称不是 'bar' 时应用 ExtractField。我们不能直接使用 TopicNameMatches,因为这会将转换应用于匹配的主题名称,而不是不匹配的主题名称。转换的隐式negateconfig 属性允许我们反转谓词匹配的记录集。将 this 的配置添加到前面的示例中,我们得到:

transforms=Filter,Extract
transforms.Filter.type=org.apache.kafka.connect.transforms.Filter
transforms.Filter.predicate=IsFoo

transforms.Extract.type=org.apache.kafka.connect.transforms.ExtractField$Key
transforms.Extract.field=other_field
transforms.Extract.predicate=IsBar
transforms.Extract.negate=true

predicates=IsFoo,IsBar
predicates.IsFoo.type=org.apache.kafka.connect.transforms.predicates.TopicNameMatches
predicates.IsFoo.pattern=foo

predicates.IsBar.type=org.apache.kafka.connect.transforms.predicates.TopicNameMatches
predicates.IsBar.pattern=bar

Kafka Connect 包括以下谓词:

  • TopicNameMatches- 匹配名称与特定 Java 正则表达式匹配的主题中的记录。
  • HasHeaderKey- 匹配具有具有给定键的标头的记录。
  • RecordIsTombstone- 匹配逻辑删除记录,即具有 null 值的记录。

下面列出了有关如何配置每个谓词的详细信息:

org.apache.kafka.connect.transforms.predicates.HasHeaderKey
谓词,对于至少具有一个具有已配置名称的标头的记录,该谓词为 true。

  • 名字

    标头名称。

    类型:字符串
    默认值:
    取值:非空字符串
    重要性:中等
org.apache.kafka.connect.transforms.predicates.RecordIsTombstone
一个谓词,对于逻辑删除 (即具有 null 值) 的记录为 true。

org.apache.kafka.connect.transforms.predicates.TopicNameMatches
一个谓词,对于主题名称与配置的正则表达式匹配的记录,该谓词为 true。

  • 模式

    一个 Java 正则表达式,用于与记录的主题名称进行匹配。

    类型:字符串
    默认值:
    取值:非空字符串,有效正则表达式
    重要性:中等

REST API

由于 Kafka Connect 旨在作为服务运行,因此它还提供了一个 REST API 来管理连接器。此 REST API 在独立模式和分布式模式下均可用。REST API 服务器可以使用listenersconfiguration 选项。 此字段应包含以下格式的侦听器列表:protocol://host:port,protocol2://host2:port2.当前支持的协议包括httphttps. 例如:

listeners=http://localhost:8080,https://localhost:8443

默认情况下,如果为 nolisteners,REST 服务器将使用 HTTP 协议在端口 8083 上运行。使用 HTTPS 时,配置必须包括 SSL 配置。 默认情况下,它将使用ssl.*设置。如果需要对 REST API 使用与连接到 Kafka 代理不同的配置,则可以在字段前加上前缀listeners.https. 使用前缀时,将仅使用带前缀的选项,并且ssl.*没有前缀的选项将被忽略。以下字段可用于为 REST API 配置 HTTPS:

  • ssl.keystore.location
  • ssl.keystore.password
  • ssl.keystore.type
  • ssl.key.password
  • ssl.truststore.location
  • ssl.truststore.password
  • ssl.truststore.type
  • ssl.enabled.protocols
  • ssl.provider
  • ssl.protocol
  • ssl.cipher.suites
  • ssl.keymanager.algorithm
  • ssl.secure.random.implementation
  • ssl.trustmanager.algorithm
  • ssl.endpoint.identification.algorithm
  • ssl.client.auth

REST API 不仅被用户用于监控 / 管理 Kafka Connect。在分布式模式下,它还用于 Kafka Connect 跨集群通信。在从属节点 REST API 上收到的一些请求将被转发到领导节点 REST API。 如果给定主机可访问的 URI 与它侦听的 URI 不同,则配置选项rest.advertised.host.name,rest.advertised.portrest.advertised.listener可用于更改 URI,follower 节点将使用该 URI 与 leader 连接。当同时使用 HTTP 和 HTTPS 侦听器时,rest.advertised.listeneroption 还可用于定义哪个侦听器 将用于跨集群通信。使用 HTTPS 在节点之间进行通信时,相同的ssl.*listeners.https选项将用于配置 HTTPS 客户端。

以下是当前支持的 REST API 端点:

  • GET /connectors- 返回活动连接器的列表
  • POST /connectors- 创建一个新的连接器;请求正文应为包含字符串的 JSON 对象namefield 和一个 Objectconfig字段,其中包含连接器配置参数
  • GET /connectors/{name}- 获取有关特定连接器的信息
  • GET /connectors/{name}/config- 获取特定连接器的配置参数
  • PUT /connectors/{name}/config- 更新特定连接器的配置参数
  • GET /connectors/{name}/status- 获取连接器的当前状态,包括连接器是否正在运行、失败、暂停等、分配给哪个工作程序、错误信息(如果失败)以及其所有任务的状态
  • GET /connectors/{name}/tasks- 获取当前为连接器运行的任务列表
  • GET /connectors/{name}/tasks/{taskid}/status- 获取任务的当前状态,包括任务是否正在运行、失败、暂停等,任务分配给哪个工作程序,以及失败时的错误信息
  • PUT /connectors/{name}/pause- 暂停连接器及其任务,这将停止消息处理,直到连接器恢复为止。其任务请求的任何资源都将保持分配状态,这允许连接器在恢复后快速开始处理数据。
  • PUT /connectors/{name}/stop- 停止连接器并关闭其任务,从而解除分配其任务请求的任何资源。从资源使用的角度来看,这比暂停连接器更有效,但可能会导致恢复后需要更长的时间才能开始处理数据。
  • PUT /connectors/{name}/resume- 恢复已暂停或已停止的连接器(如果连接器未暂停或停止,则不执行任何作)
  • POST /connectors/{name}/restart?includeTasks=<true|false>&onlyFailed=<true|false>- 重新启动连接器及其任务实例。
    • “includeTasks”参数指定是重新启动连接器实例和任务实例 (“includeTasks=true”) 还是仅重新启动连接器实例 (“includeTasks=false”),默认值 (“false”) 保留与早期版本相同的行为。
    • “onlyFailed”参数指定是仅重新启动状态为 FAILED 的实例 (“onlyFailed=true”) 还是重新启动所有实例 (“onlyFailed=false”),默认实例 (“false”) 保留与早期版本相同的行为。
  • POST /connectors/{name}/tasks/{taskId}/restart- 重新启动单个任务(通常是因为它已失败)
  • DELETE /connectors/{name}- 删除连接器,停止所有任务并删除其配置
  • GET /connectors/{name}/topics- 获取特定连接器自创建连接器或发出重置其活动主题集的请求以来正在使用的主题集
  • PUT /connectors/{name}/topics/reset- 发送请求以清空连接器的活动主题集
  • GET /connectors/{name}/offsets- 获取连接器的当前偏移量(有关详细信息,请参阅 KIP-875

Kafka Connect 还提供了一个 REST API,用于获取有关连接器插件的信息:

  • GET /connector-plugins- 返回 Kafka Connect 集群中安装的连接器插件列表。请注意,API 仅检查处理请求的 worker 上的连接器,这意味着您可能会看到不一致的结果,尤其是在滚动升级期间,如果您添加新的连接器 jar
  • PUT /connector-plugins/{connector-type}/config/validate- 根据配置定义验证提供的配置值。此 API 按配置执行验证,在验证期间返回建议的值和错误消息。

以下是顶级(根)终端节点支持的 REST 请求:

  • GET /- 返回有关 Kafka Connect 集群的基本信息,例如为 REST 请求提供服务的 Connect 工作程序的版本(包括源代码的 git 提交 ID)和连接到的 Kafka 集群 ID。

有关 REST API 的完整规范,请参阅 OpenAPI 文档

Connect 中的错误报告

Kafka Connect 提供错误报告,以处理在各个处理阶段遇到的错误。默认情况下,在转换期间或转换过程中遇到的任何错误都会导致连接器失败。每个连接器配置还可以通过跳过此类错误来允许容忍这些错误,可以选择将每个错误以及失败作和有问题的记录的详细信息(具有不同级别的详细信息)写入 Connect 应用程序日志。当接收器连接器处理从其 Kafka 主题使用的消息时,这些机制还会捕获错误,并且所有错误都可以写入可配置的“死信队列”(DLQ) Kafka 主题。

要将连接器的 converter、transforms 或 sink 连接器本身中的错误报告到日志中,请将errors.log.enable=true在 Connector 配置中,记录每个错误和问题记录的主题、分区和偏移量的详细信息。出于其他调试目的,将errors.log.include.messages=true将问题记录 key、value 和 headers 也记录到日志中(请注意,这可能会记录敏感信息)。

要将连接器的 converter、transforms 或 sink 连接器本身中的错误报告为死信队列主题,请将errors.deadletterqueue.topic.name和可选的errors.deadletterqueue.context.headers.enable=true.

默认情况下,连接器在出现错误或异常时会立即表现出“快速失败”行为。这相当于将以下配置属性及其默认值添加到连接器配置中:

# disable retries on failure
errors.retry.timeout=0

# do not log the error and their contexts
errors.log.enable=false

# do not record errors in a dead letter queue topic
errors.deadletterqueue.topic.name=

# Fail on first error
errors.tolerance=none

可以更改这些和其他相关的连接器配置属性以提供不同的行为。例如,可以将以下配置属性添加到连接器配置中,以设置多次重试的错误处理、记录到应用程序日志和my-connector-errorsKafka 主题,并通过报告错误而不是使连接器任务失败来容忍所有错误:

# retry for at most 10 minutes times waiting up to 30 seconds between consecutive failures
errors.retry.timeout=600000
errors.retry.delay.max.ms=30000

# log error context along with application logs, but do not include configs and messages
errors.log.enable=true
errors.log.include.messages=false

# produce error context into the Kafka topic
errors.deadletterqueue.topic.name=my-connector-errors

# Tolerate all errors.
errors.tolerance=all

Exactly-once 支持

Kafka Connect 能够为 Sink 连接器(自版本 0.11.0 起)和源连接器(自版本 3.3.0 起)提供 Exactly-once 语义。请注意,对 exactly-once 语义的支持在很大程度上取决于您运行的连接器类型。即使您在配置中为集群中的每个节点设置了所有正确的工作线程属性,如果连接器不是为或无法利用 Kafka Connect 框架的功能而设计的,则可能无法实现恰好一次。

Sink 连接器

如果接收器连接器支持恰好一次语义,要在 Connect 工作线程级别启用恰好一次,您必须确保将其使用者组配置为忽略中止事务中的记录。您可以通过设置 worker 属性consumer.isolation.levelread_committed或者,如果运行的 Kafka Connect 版本支持它,请使用允许consumer.override.isolation.level属性设置为read_committed在单个连接器配置中。没有额外的 ACL 要求。

源连接器

如果源连接器支持恰好一次语义,则必须配置 Connect 集群,以启用对恰好一次源连接器的框架级支持。如果针对受保护的 Kafka 集群运行,则可能需要额外的 ACL。请注意,对源连接器的 exactly-once 支持目前仅在分布式模式下可用;独立的 Connect 工作程序无法提供 exactly-once 语义。

Worker 配置

对于新的 Connect 集群,请将exactly.once.source.supportproperty 设置为enabled在集群中每个节点的 worker 配置中。对于现有集群,需要进行两次滚动升级。在第一次升级期间,exactly.once.source.supportproperty 应设置为preparing,在第二个 API 中,应将其设置为enabled.

ACL 要求

启用恰好一次源支持后,每个 Connect 工作程序的主体将需要以下 ACL:

操作 资源类型 资源名称 注意
事务 ID connect-cluster-${groupId}哪里${groupId}group.id集群的
描述 事务 ID connect-cluster-${groupId}哪里${groupId}group.id集群的
IdempotentWrite 托管 worker 的 config 主题的 Kafka 集群的 ID IdempotentWrite ACL 自 2.8 起已弃用,仅对于在 2.8 之前的 Kafka 集群上运行的 Connect 集群是必需的

每个连接器的主体将需要以下 ACL:

操作 资源类型 资源名称 注意
事务 ID ${groupId}-${connector}-${taskId},对于连接器将创建的每个任务,其中${groupId}group.id中,${connector}是连接器的名称,而${taskId}是任务的 ID(从零开始) 通配符前缀${groupId}-${connector}*如果没有与其他事务 ID 冲突的风险,或者用户可接受冲突,则可以使用。
描述 事务 ID ${groupId}-${connector}-${taskId},对于连接器将创建的每个任务,其中${groupId}group.id中,${connector}是连接器的名称,而${taskId}是任务的 ID(从零开始) 通配符前缀${groupId}-${connector}*如果没有与其他事务 ID 冲突的风险,或者用户可接受冲突,则可以使用。
主题 Offsets 主题,该主题是offsets.storage.topic属性(如果提供)或offsets.storage.topic属性。
主题 Offsets 主题,该主题是offsets.storage.topic属性(如果提供)或offsets.storage.topic属性。
描述 主题 Offsets 主题,该主题是offsets.storage.topic属性(如果提供)或offsets.storage.topic属性。
创造 主题 Offsets 主题,该主题是offsets.storage.topic属性(如果提供)或offsets.storage.topic属性。 仅当连接器的 offsets 主题尚不存在时才需要
IdempotentWrite 源连接器写入的 Kafka 集群的 ID IdempotentWrite ACL 自 2.8 起已弃用,仅对于在 2.8 之前的 Kafka 集群上运行的 Connect 集群是必需的

8.3 连接器开发指南

本指南介绍了开发人员如何为 Kafka Connect 编写新的连接器,以便在 Kafka 和其他系统之间移动数据。它简要回顾了几个关键概念,然后介绍了如何创建简单的连接器。

核心概念和 API

连接器和任务

要在 Kafka 和其他系统之间复制数据,用户需要一个Connector对于他们要从中提取数据或将数据推送到的系统。连接器有两种类型:SourceConnectors从另一个系统导入数据(例如JDBCSourceConnector会将关系数据库导入到 Kafka 中),而SinkConnectors导出数据(例如HDFSSinkConnector会将 Kafka 主题的内容导出到 HDFS 文件)。

Connectors不自行执行任何数据复制:它们的配置描述了要复制的数据,并且Connector负责将该作业分解为一组Tasks可以分发给 worker。这些Tasks也有两种相应的口味:SourceTaskSinkTask.

手头有任务,每个Task必须将其数据子集复制到 Kafka 或从 Kafka 复制数据。在 Kafka Connect 中,应该始终可以将这些分配构建为一组输入和输出流,这些流由具有一致架构的记录组成。有时这种映射是显而易见的:一组日志文件中的每个文件都可以被视为一个流,每个解析的行使用相同的架构形成一条记录,偏移量作为字节偏移量存储在文件中。在其他情况下,可能需要更多的努力才能映射到此模型:JDBC 连接器可以将每个表映射到一个流,但偏移量不太清楚。一种可能的映射使用 timestamp 列生成以增量方式返回新数据的查询,最后查询的 timestamp 可用作偏移量。

流和记录

每个流都应该是一个键值记录序列。键和值都可以具有复杂的结构 —— 提供了许多基元类型,但也可以表示数组、对象和嵌套数据结构。运行时数据格式不采用任何特定的序列化格式;此转换由框架内部处理。

除了 key 和 value 之外,记录(由 source 生成的记录和传送到 sink 的记录)还具有关联的 stream ID 和 offsets。框架使用这些偏移量定期提交已处理的数据偏移量,以便在发生故障时,可以从上次提交的偏移量恢复处理,从而避免不必要的重新处理和事件重复。

动态连接器

并非所有作业都是静态的,因此Connectorimplementations 还负责监视 external system 是否有任何可能需要 reconfiguration 的更改。例如,在JDBCSourceConnector示例中,Connector可能会为每个Task.创建新表时,它必须发现此表,以便将新表分配给Tasks通过更新其配置。当它注意到需要重新配置的更改(或Tasks),它会通知框架,并且框架会更新任何相应的Tasks.

开发简单的连接器

开发连接器只需要实现两个接口,即ConnectorTask.Kafka 的源代码中包含一个简单的示例,位于file包。此连接器旨在用于独立模式,并具有SourceConnector/SourceTask读取文件的每一行并将其作为记录发出,并使用SinkConnector/SinkTask将每条记录写入一个文件。

本节的其余部分将介绍一些代码来演示创建连接器的关键步骤,但开发人员还应参考完整的示例源代码,因为为简洁起见,省略了许多细节。

连接器示例

我们将介绍SourceConnector作为一个简单的例子。SinkConnector实现非常相似。首先创建继承自SourceConnector并添加一个字段,该字段将存储要传播到任务的配置信息(要向其发送数据的主题,以及可选的 - 要读取的文件名和最大批量大小):

public class FileStreamSourceConnector extends SourceConnector {
    private Map<String, String> props;

最简单的填写方法是taskClass(),它定义了应该在 worker 进程中实例化以实际读取数据的类:

@Override
public Class<? extends Task> taskClass() {
    return FileStreamSourceTask.class;
}

我们将定义FileStreamSourceTask类。接下来,我们添加一些标准的生命周期方法,start()stop():

@Override
public void start(Map<String, String> props) {
    // Initialization logic and setting up of resources can take place in this method.
    // This connector doesn't need to do any of that, but we do log a helpful message to the user.

    this.props = props;
    AbstractConfig config = new AbstractConfig(CONFIG_DEF, props);
    String filename = config.getString(FILE_CONFIG);
    filename = (filename == null || filename.isEmpty()) ? "standard input" : config.getString(FILE_CONFIG);
    log.info("Starting file source connector reading from {}", filename);
}

@Override
public void stop() {
    // Nothing to do since no background monitoring is required.
}

最后,实现的真正核心在于taskConfigs().在这种情况下,我们只是 处理单个文件,因此即使我们可能被允许按照maxTasks参数,我们返回一个只有一个条目的列表:

@Override
public List<Map<String, String>> taskConfigs(int maxTasks) {
    // Note that the task configs could contain configs additional to or different from the connector configs if needed. For instance,
    // if different tasks have different responsibilities, or if different tasks are meant to process different subsets of the source data stream).
    ArrayList<Map<String, String>> configs = new ArrayList<>();
    // Only one input stream makes sense.
    configs.add(props);
    return configs;
}

即使有多个任务,此方法的实现通常也非常简单。它只需要确定输入任务的数量,这可能需要联系它从中提取数据的远程服务,然后对它们进行划分。由于在任务之间拆分工作的某些模式非常常见,因此在ConnectorUtils来简化这些情况。

请注意,这个简单的示例不包括 dynamic input。请参阅下一节中的讨论,了解如何触发任务配置的更新。

任务示例 - 源任务

接下来,我们将描述相应的SourceTask.实现时间很短,但太长,无法在本指南中完全介绍。我们将使用伪代码来描述大部分实现,但您可以参考源代码以获取完整示例。

就像连接器一样,我们需要创建一个从适当的基继承的类Task类。它还具有一些标准的生命周期方法:

public class FileStreamSourceTask extends SourceTask {
    private String filename;
    private InputStream stream;
    private String topic;
    private int batchSize;

    @Override
    public void start(Map<String, String> props) {
        filename = props.get(FileStreamSourceConnector.FILE_CONFIG);
        stream = openOrThrowError(filename);
        topic = props.get(FileStreamSourceConnector.TOPIC_CONFIG);
        batchSize = props.get(FileStreamSourceConnector.TASK_BATCH_SIZE_CONFIG);
    }

    @Override
    public synchronized void stop() {
        stream.close();
    }

这些是略微简化的版本,但表明这些方法应该相对简单,并且它们应该执行的唯一工作是分配或释放资源。关于此实现,有两点需要注意。首先,start()method 尚未处理从上一个偏移量恢复的问题,这将在后面的部分中解决。其次,stop()method 的 intent 被同步。这将是必要的,因为SourceTasks被赋予一个专用线程,它们可以无限期地阻止该线程,因此需要通过调用 Worker 中的其他线程来停止它们。

接下来,我们实现任务的主要功能poll()方法,该方法从输入系统获取事件并返回List<SourceRecord>:

@Override
public List<SourceRecord> poll() throws InterruptedException {
    try {
        ArrayList<SourceRecord> records = new ArrayList<>();
        while (streamValid(stream) && records.isEmpty()) {
            LineAndOffset line = readToNextLine(stream);
            if (line != null) {
                Map<String, Object> sourcePartition = Collections.singletonMap("filename", filename);
                Map<String, Object> sourceOffset = Collections.singletonMap("position", streamOffset);
                records.add(new SourceRecord(sourcePartition, sourceOffset, topic, Schema.STRING_SCHEMA, line));
                if (records.size() >= batchSize) {
                    return records;
                }
            } else {
                Thread.sleep(1);
            }
        }
        return records;
    } catch (IOException e) {
        // Underlying stream was killed, probably as a result of calling stop. Allow to return
        // null, and driving thread will handle any shutdown if necessary.
    }
    return null;
}

同样,我们省略了一些细节,但我们可以看到重要的步骤:poll()方法将被重复调用,并且对于每次调用,它都会循环尝试从文件中读取记录。对于它读取的每一行,它还会跟踪文件偏移量。它使用此信息创建输出SourceRecord包含四条信息:源分区(只有一个,即正在读取的单个文件)、源偏移量(文件中的字节偏移量)、输出主题名称和输出值(该行,我们包含一个架构,指示此值将始终为字符串)。其他SourceRecordconstructor 还可以包含特定的 output partition、key 和 headers。

请注意,此实现使用普通的 JavaInputStream接口,如果数据不可用,则可能会休眠。这是可以接受的,因为 Kafka Connect 为每个任务提供专用线程。虽然任务实现必须符合基本的poll()interface 的 API 中,它们在实现方式上具有很大的灵活性。在这种情况下,基于 NIO 的实现会更高效,但这种简单的方法有效,实现速度快,并且与旧版本的 Java 兼容。

虽然示例中未使用,SourceTask还提供了两个 API 来提交源系统中的偏移量:commitcommitRecord.API 是为具有消息确认机制的源系统提供的。覆盖这些方法允许源连接器在将消息写入 Kafka 后,批量或单独确认源系统中的消息。 这commitAPI 将偏移量存储在源系统中,最大为poll.此 API 的实现应阻止,直到提交完成。这commitRecordAPI 将每个 API 的偏移量保存在源系统中SourceRecord在写入 Kafka 之后。由于 Kafka Connect 会自动记录偏移量,SourceTask不需要实现它们。如果连接器确实需要确认源系统中的消息,则通常只需要其中一个 API。

Sink 任务

上一节介绍了如何实现简单的SourceTask.与SourceConnectorSinkConnector,SourceTaskSinkTask具有非常不同的接口,因为SourceTask使用 pull 接口和SinkTask使用推送接口。两者都共享通用的生命周期方法,但SinkTaskinterface 则完全不同:

public abstract class SinkTask implements Task {
    public void initialize(SinkTaskContext context) {
        this.context = context;
    }

    public abstract void put(Collection<SinkRecord> records);

    public void flush(Map<TopicPartition, OffsetAndMetadata> currentOffsets) {
    }

SinkTask文档包含完整的详细信息,但此接口几乎与SourceTask.这put()method 应该包含大部分的实现,接受SinkRecords,执行任何所需的翻译,并将其存储在目标系统中。此方法不需要确保在返回之前数据已完全写入目标系统。事实上,在许多情况下,内部缓冲将非常有用,因此可以一次发送整批记录,从而减少将事件插入下游数据存储的开销。这SinkRecords包含的信息与SourceRecords:Kafka 主题、分区、偏移量、事件键和值以及可选标头。

flush()method 在偏移提交过程中使用,它允许任务从失败中恢复并从安全点恢复,这样就不会错过任何事件。该方法应将任何未完成的数据推送到目标系统,然后阻塞,直到确认写入。这offsetsparameter 通常可以忽略,但在某些情况下很有用,因为 implementation 希望将偏移信息存储在目标存储中以提供 exactly-once 交货。例如,HDFS 连接器可以执行此作,并使用原子移动作来确保flush()作以原子方式将数据和偏移量提交到 HDFS 中的最终位置。

Errant Record Reporter

为连接器启用错误报告后,连接器可以使用ErrantRecordReporter报告发送到 Sink Connector 的单个记录的问题。以下示例显示了连接器的SinkTask子类可能会获取并使用ErrantRecordReporter,当 DLQ 未启用或连接器安装在没有此报告器功能的旧 Connect 运行时中时,可以安全地处理空报告器:

private ErrantRecordReporter reporter;

@Override
public void start(Map<String, String> props) {
    ...
    try {
        reporter = context.errantRecordReporter(); // may be null if DLQ not enabled
    } catch (NoSuchMethodException | NoClassDefFoundError e) {
        // Will occur in Connect runtimes earlier than 2.6
        reporter = null;
    }
}

@Override
public void put(Collection<SinkRecord> records) {
    for (SinkRecord record: records) {
        try {
            // attempt to process and send record to data sink
            process(record);
        } catch(Exception e) {
            if (reporter != null) {
                // Send errant record to error reporter
                reporter.report(record, e);
            } else {
                // There's no error reporter, so fail
                throw new ConnectException("Failed on record", e);
            }
        }
    }
}
从以前的偏移量恢复

SourceTaskimplementation 包括每条记录的流 ID(输入文件名)和 offset(在文件中的位置)。框架使用它来定期提交偏移量,以便在发生故障时,任务可以恢复并最大限度地减少重新处理和可能重复的事件数量(或者,如果 Kafka Connect 正常停止,例如在独立模式下或由于作业重新配置,则从最近的偏移量恢复)。此提交过程完全由框架自动执行,但只有连接器知道如何查找回输入流中的正确位置,以便从该位置恢复。

要在启动时正确恢复,任务可以使用SourceContext传递到其initialize()方法来访问偏移数据。在initialize(),我们将添加更多代码来读取偏移量(如果存在)并查找该位置:

stream = new FileInputStream(filename);
Map<String, Object> offset = context.offsetStorageReader().offset(Collections.singletonMap(FILENAME_FIELD, filename));
if (offset != null) {
    Long lastRecordedOffset = (Long) offset.get("position");
    if (lastRecordedOffset != null)
        seekToOffset(stream, lastRecordedOffset);
}

当然,您可能需要为每个 input 流读取许多 key。这OffsetStorageReaderinterface 还允许您发出批量读取以有效地加载所有偏移量,然后通过将每个 input 流查找到适当的位置来应用它们。

恰好一次源连接器
支持 exactly-once

随着 KIP-618 的发布,Kafka Connect 从版本 3.3.0 开始支持恰好一次源连接器。为了使源连接器利用此支持,它必须能够为其发出的每条记录提供有意义的源偏移量,并在与任何这些偏移量对应的确切位置从外部系统恢复使用,而不会删除或复制消息。

定义事务边界

默认情况下,Kafka Connect 框架将为源任务从其poll方法。但是,连接器也可以定义自己的事务边界,用户可以通过设置transaction.boundaryproperty 设置为connector在连接器的配置中。

如果启用,连接器的任务将有权访问TransactionContext从他们的SourceTaskContext,他们可以使用它来控制何时中止和提交事务。

例如,要至少每 10 条记录提交一个事务:

private int recordsSent;

@Override
public void start(Map<String, String> props) {
    this.recordsSent = 0;
}

@Override
public List<SourceRecord> poll() {
    List<SourceRecord> records = fetchRecords();
    boolean shouldCommit = false;
    for (SourceRecord record : records) {
        if (++this.recordsSent >= 10) {
            shouldCommit = true;
        }
    }
    if (shouldCommit) {
        this.recordsSent = 0;
        this.context.transactionContext().commitTransaction();
    }
    return records;
}

或者为每十条记录提交一个事务:

private int recordsSent;

@Override
public void start(Map<String, String> props) {
    this.recordsSent = 0;
}

@Override
public List<SourceRecord> poll() {
    List<SourceRecord> records = fetchRecords();
    for (SourceRecord record : records) {
        if (++this.recordsSent % 10 == 0) {
            this.context.transactionContext().commitTransaction(record);
        }
    }
    return records;
}

大多数连接器不需要定义自己的事务边界。但是,如果源系统中的文件或对象被分解为多个源记录,则可能会很有用,但应该以原子方式交付。此外,如果无法为每个源记录提供唯一的源偏移量,并且具有给定偏移量的每条记录都在单个事务中交付,则它可能很有用。

请注意,如果用户尚未在连接器配置中启用连接器定义的事务边界,则TransactionContext返回者context.transactionContext()将是null.

验证 API

源连接器开发人员可以实现一些其他的印前验证 API。

某些用户可能需要连接器的 exactly-once 语义。在这种情况下,他们可以将exactly.once.supportproperty 设置为required在连接器的配置中。发生这种情况时,Kafka Connect 框架将询问连接器是否可以使用指定的配置提供恰好一次语义。这是通过调用exactlyOnceSupport方法。

如果连接器不支持 exactly-once 语义,它仍应实现此方法,以让用户确定它无法提供 exactly-once 语义:

@Override
public ExactlyOnceSupport exactlyOnceSupport(Map<String, String> props) {
    // This connector cannot provide exactly-once semantics under any conditions
    return ExactlyOnceSupport.UNSUPPORTED;
}

否则,连接器应检查配置,并返回ExactlyOnceSupport.SUPPORTED如果它可以提供 Exactly-once 语义:

@Override
public ExactlyOnceSupport exactlyOnceSupport(Map<String, String> props) {
    // This connector can always provide exactly-once semantics
    return ExactlyOnceSupport.SUPPORTED;
}

此外,如果用户已将连接器配置为定义自己的事务边界,则 Kafka Connect 框架将询问连接器是否可以使用指定的配置定义自己的事务边界,使用canDefineTransactionBoundaries方法:

@Override
public ConnectorTransactionBoundaries canDefineTransactionBoundaries(Map<String, String> props) {
    // This connector can always define its own transaction boundaries
    return ConnectorTransactionBoundaries.SUPPORTED;
}

在某些情况下,应仅对可以定义自己的事务边界的连接器实现此方法。如果连接器永远无法定义自己的事务边界,则它不需要实现此方法。

动态输入/输出流

Kafka Connect 旨在定义批量数据复制作业,例如复制整个数据库,而不是创建多个作业来单独复制每个表。这种设计的一个结果是连接器的输入或输出流集会随时间而变化。

源连接器需要监控源系统的更改,例如数据库中的表添加/删除。当他们发现更改时,他们应该通过ConnectorContextobject,该对象是必要的。例如,在SourceConnector:

if (inputsChanged())
    this.context.requestTaskReconfiguration();

框架将立即请求新的配置信息并更新任务,从而允许它们在重新配置任务之前正常提交进度。请注意,在SourceConnector此监视目前留给 Connector 实现。如果需要额外的线程来执行此监视,则连接器必须自行分配该线程。

理想情况下,此用于监控更改的代码将与Connector任务不需要担心它们。但是,更改也会影响任务,最常见的情况是当其中一个输入流在 Importing 系统中被销毁时,例如,如果从数据库中删除了一个表。如果TaskConnector,如果Connector需要轮询更改,则Task将需要处理后续错误。值得庆幸的是,这通常可以通过捕获和处理适当的异常来处理。

SinkConnectors通常只需要处理 streams 的添加,这可能会转化为其输出中的新条目(例如,新的 Database Table)。该框架管理对 Kafka 输入的任何更改,例如当输入主题集因正则表达式订阅而更改时。SinkTasks应该需要新的 Importing 流,这可能需要在下游系统中创建新资源,例如数据库中的新 table。在这些情况下,最棘手的情况可能是多个SinkTasks首次看到新的 input 流,同时尝试创建新资源。SinkConnectors,则通常不需要特殊代码来处理一组动态流。

配置验证

Kafka Connect 允许您在提交要执行的连接器之前验证连接器配置,并可以提供有关错误和建议值的反馈。为了利用这一点,连接器开发人员需要提供config()向框架公开配置定义。

以下代码FileStreamSourceConnector定义配置并将其公开给框架。

static final ConfigDef CONFIG_DEF = new ConfigDef()
    .define(FILE_CONFIG, Type.STRING, null, Importance.HIGH, "Source filename. If not specified, the standard input will be used")
    .define(TOPIC_CONFIG, Type.STRING, ConfigDef.NO_DEFAULT_VALUE, new ConfigDef.NonEmptyString(), Importance.HIGH, "The topic to publish data to")
    .define(TASK_BATCH_SIZE_CONFIG, Type.INT, DEFAULT_TASK_BATCH_SIZE, Importance.LOW,
        "The maximum number of records the source task can read from the file each time it is polled");

public ConfigDef config() {
    return CONFIG_DEF;
}

ConfigDefclass 用于指定预期配置的集合。对于每个配置,您可以指定名称、类型、默认值、文档、组信息、组中的顺序、配置值的宽度以及适合在 UI 中显示的名称。此外,您还可以通过覆盖Validator类。此外,由于配置之间可能存在依赖关系,例如,配置的有效值和可见性可能会根据其他配置的值而变化。为了解决这个问题,ConfigDef允许您指定配置的依赖项并提供Recommender获取有效值并设置给定当前配置值的配置的可见性。

此外,validate()method 中Connector提供默认验证实施,该实施返回允许的配置列表以及每个配置的配置错误和建议值。但是,它不使用建议的值进行配置验证。您可以为自定义配置验证提供默认实现的覆盖,该实现可能会使用建议的值。

使用 Schema

FileStream 连接器是很好的示例,因为它们很简单,但它们也具有简单的结构化数据 —— 每行只是一个字符串。几乎所有实际的连接器都需要具有更复杂数据格式的架构。

要创建更复杂的数据,您需要使用 Kafka Connectdata应用程序接口。除了基元类型之外,大多数结构化记录还需要与两个类交互:SchemaStruct.

API 文档提供了完整的参考,但这里有一个创建SchemaStruct:

Schema schema = SchemaBuilder.struct().name(NAME)
    .field("name", Schema.STRING_SCHEMA)
    .field("age", Schema.INT_SCHEMA)
    .field("admin", SchemaBuilder.bool().defaultValue(false).build())
    .build();

Struct struct = new Struct(schema)
    .put("name", "Barbara Liskov")
    .put("age", 75);

如果要实现源连接器,则需要决定何时以及如何创建架构。在可能的情况下,您应该尽可能避免重新计算它们。例如,如果保证连接器具有固定架构,请静态创建该架构并重用单个实例。

但是,许多连接器将具有动态架构。一个简单的示例是数据库连接器。即使只考虑一个表,也不会为整个连接器预定义架构(因为它因表而异)。但是,在连接器的生命周期内,它也可能不会针对单个表进行修复,因为用户可能会执行ALTER TABLE命令。连接器必须能够检测到这些更改并做出适当的反应。

接收器连接器通常更简单,因为它们正在使用数据,因此不需要创建架构。但是,他们应该同样小心地验证他们收到的架构是否具有预期的格式。当架构不匹配时(通常表示上游生产者正在生成无法正确转换为目标系统的无效数据),sink 连接器应引发异常,以向系统指示此错误。

8.4 管理

Kafka Connect 的 REST 层提供了一组 API 来支持集群的管理。这包括用于查看连接器配置及其任务状态以及更改其当前行为(例如更改配置和重新启动任务)的 API。

首次将连接器提交到集群时,将在 Connect 工作程序之间触发再平衡,以分配由新连接器的任务组成的负载。 当连接器增加或减少它们所需的任务数量、更改连接器的配置或 worker 是 Connect 集群有意升级的一部分,或者是由于故障而在组中添加或删除的。

在 2.3.0 之前的版本中,Connect 工作程序将重新平衡集群中的全套连接器及其任务,以确保每个工作程序的工作量大致相同。 此行为仍可以通过设置connect.protocol=eager.

从 2.3.0 开始,Kafka Connect 默认使用一种协议来执行增量协作再平衡,该协议在 Connect 工作线程之间增量平衡连接器和任务,仅影响新的、要删除的或需要从一个工作线程移动到另一个工作线程的任务。 其他任务在重新平衡期间不会停止和重新启动,就像使用旧协议时那样。

如果 Connect 工作程序有意或由于故障而离开组,Connect 会等待scheduled.rebalance.max.delay.ms在触发 Rebalance 之前。 此延迟默认为 5 分钟 (300000ms) 来容忍工作程序的故障或升级,而无需立即重新分配离职工作程序的负载。 如果此 worker 在配置的延迟内返回,它将完整获取之前分配的任务。 但是,这意味着任务将保持未分配状态,直到scheduled.rebalance.max.delay.ms流逝。 如果工作程序未在该时间限制内返回,Connect 将在 Connect 集群中的其余工作程序之间重新分配这些任务。

当组成 Connect 集群的所有工作程序都配置了connect.protocol=compatible,这也是缺少此属性时的默认值。 因此,当所有工作程序都升级到 2.3.0 时,会自动升级到新的 Connect 协议。 Connect 集群的滚动升级将在版本 2.3.0 上的最后一个 worker 加入时激活增量协作再平衡。

您可以使用 REST API 查看连接器及其任务的当前状态,包括每个任务分配到的工作程序的 ID。例如,GET /connectors/file-source/statusrequest 显示名为file-source:

{
    "name": "file-source",
    "connector": {
        "state": "RUNNING",
        "worker_id": "192.168.1.208:8083"
    },
    "tasks": [
        {
        "id": 0,
        "state": "RUNNING",
        "worker_id": "192.168.1.209:8083"
        }
    ]
}

连接器及其任务将状态更新发布到共享主题(配置了status.storage.topic),集群中的所有 worker 都会监控。由于 worker 异步使用此主题,因此在通过状态 API 看到状态更改之前,通常会有一个(短暂的)延迟。连接器或其任务之一可能出现以下状态:

  • UNASSIGNED: 未分配:连接器/任务尚未分配给工作人员。
  • 运行:连接器/任务正在运行。
  • 暂停:连接器/任务已被管理性暂停。
  • 停止:连接器已停止。请注意,此状态不适用于任务,因为已停止连接器的任务已关闭,并且不会在状态 API 中显示。
  • 失败:连接器/任务失败(通常是通过引发异常,该异常在 status 输出中报告)。
  • 重新 启动:连接器/任务正在主动重启或预计很快重启

在大多数情况下,连接器和任务状态将匹配,但在发生更改或任务失败时,它们可能会在短时间内有所不同。例如,当连接器首次启动时,在连接器及其任务全部转换为 RUNNING 状态之前,可能会有明显的延迟。当任务失败时,状态也会发散,因为 Connect 不会自动重启失败的任务。要手动重启连接器/任务,您可以使用上面列出的重启 API。请注意,如果您尝试在进行再平衡时重新启动任务,Connect 将返回 409 (Conflict) 状态代码。您可以在再平衡完成后重试,但这可能不是必需的,因为再平衡会有效地重新启动集群中的所有连接器和任务。

从 2.5.0 开始,Kafka Connect 使用status.storage.topic还存储与每个连接器正在使用的主题相关的信息。Connect Worker 使用这些每个连接器的主题状态更新来响应对 REST 终端节点的请求GET /connectors/{name}/topics通过返回连接器正在使用的主题名称集。对 REST 端点的请求PUT /connectors/{name}/topics/reset重置连接器的活动主题集,并允许根据连接器的最新主题使用模式填充新的主题集。删除连接器后,连接器的活动主题集也会被删除。主题跟踪默认启用,但可以通过设置topic.tracking.enable=false.如果要禁止在运行时重置连接器的活动主题的请求,请将 Worker 属性topic.tracking.allow.reset=false.

有时,暂时停止连接器的消息处理很有用。例如,如果远程系统正在进行维护,则源连接器最好停止轮询新数据,而不是在日志中填充异常垃圾邮件。对于此使用案例,Connect 提供了暂停/恢复 API。当源连接器暂停时,Connect 将停止轮询它以获取其他记录。当接收器连接器暂停时,Connect 将停止向其推送新消息。暂停状态是持久的,因此即使您重新启动集群,连接器也不会再次开始消息处理,直到任务恢复。请注意,在连接器的所有任务都转换为 PAUSED 状态之前,可能会有延迟,因为它们可能需要一些时间才能完成暂停时正在进行的任何处理。此外,失败的任务在重新启动之前不会转换为 PAUSED 状态。

在 3.5.0 中,Connect 引入了一个停止 API,该 API 可完全关闭连接器的任务并解除分配连接器请求的任何资源。这与暂停连接器不同,在连接器中,任务处于空闲状态,并且它们所占用的任何资源都保持分配状态(这允许连接器在恢复后快速开始处理数据)。从资源使用的角度来看,停止连接器比暂停连接器更有效,但可能会导致恢复后需要更长的时间才能开始处理数据。

1.4 生态系统

在主发行版之外,还有大量工具与 Kafka 集成。 生态系统页面列出了其中的许多工具,包括流处理系统、Hadoop 集成、监控和部署工具。

1.5 从以前的版本升级

从任何版本 0.8.x 到 3.4.x 升级到 3.5.2

所有升级步骤与升级到 3.5.0 相同
3.5.2 中的显著变化
  • 当将生产者 ID 区块从 ZK 迁移到 KRaft 时,可能会有重复的生产者 ID 被赋予 事务性或幂等生产者。这可能会导致长期问题,因为生产者 ID 是 保留并重用了很长时间。 有关更多详细信息,请参阅 KAFKA-15552
  • 在 3.5.0 和 3.5.1 中,可能存在在 AlterPartition 请求后从控制器返回空 ISR 的问题 在滚动升级期间。此问题将影响 topic 分区的可用性。 有关更多详细信息,请参阅 KAFKA-15353

从任何版本 0.8.x 到 3.4.x 升级到 3.5.1

所有升级步骤与升级到 3.5.0 相同
3.5.1 中的显著变化
  • 将依赖项 snappy-java 升级到不易受 CVE-2023-34455 攻击的版本。您可以在 Kafka CVE 列表中找到有关 CVE 的更多信息。
  • 修复了 3.3.0 中引入的回归,该回归导致security.protocol要限制为的配置值 仅限大写。修复后,security.protocol值不区分大小写。 有关详细信息,请参阅 KAFKA-15053

从任何版本 0.8.x 到 3.4.x 升级到 3.5.0

3.5.0 中的显著更改
  • Kafka Streams 引入了一种新的状态存储类型,即版本化的键值存储、 用于为每个键存储多个记录版本,从而启用时间戳检索 作返回截至指定时间戳的最新记录(每个键)。 有关更多详细信息,请参阅 KIP-889KIP-914。 如果在 DSL 中使用新的存储类型化,则会应用 KIP-914 中所述的改进处理语义。
  • KTable 聚合语义通过 KIP-904 得到了进一步改进, 现在避免虚假的中间结果。
  • Kafka Streams 的ProductionExceptionHandler通过 KIP-399 得到改进, 现在还涵盖序列化错误。
  • MirrorMaker 现在默认使用 incrementalAlterConfigs API 来同步主题配置,而不是已弃用的 alterConfigs API。 一个名为use.incremental.alter.configs允许用户控制要使用的 API。 此新设置被标记为已弃用,并且当始终使用 incrementalAlterConfigs API 时,将在下一个主要版本中删除该设置。 有关详细信息,请参阅 KIP-894
  • JmxTool、EndToEndLatency、StreamsResetter、ConsumerPerformance 和 ClusterTool 已迁移到 tools 模块。 “kafka.tools”包已弃用,在下一个主要版本中将更改为“org.apache.kafka.tools”。 有关更多详细信息,请参阅 KAFKA-14525
升级基于 ZooKeeper 的集群

如果您从 2.1.x 之前的版本升级,请参阅下面步骤 5 中有关用于存储使用者偏移量的架构的更改的说明。 将 inter.broker.protocol.version 更改为最新版本后,将无法降级到 2.1 之前的版本。

对于滚动升级:

  1. 更新所有代理上的 server.properties 并添加以下属性。CURRENT_KAFKA_VERSION 是指您 正在升级。CURRENT_MESSAGE_FORMAT_VERSION 是指当前正在使用的消息格式版本。如果您之前有 覆盖了 Message Format version,则应保留其当前值。或者,如果您要从之前的版本升级 设置为 0.11.0.x,则CURRENT_MESSAGE_FORMAT_VERSION应设置为 MATCH CURRENT_KAFKA_VERSION。
    • inter.broker.protocol.version=CURRENT_KAFKA_VERSION 的3.4,3.3等)
    • log.message.format.version=CURRENT_MESSAGE_FORMAT_VERSION (查看潜在的性能影响) 有关此配置的作用的详细信息。
    如果您从版本 0.11.0.x 或更高版本升级,并且您没有覆盖消息格式,则只需覆盖 Inter-Broker 协议版本。
    • inter.broker.protocol.version=CURRENT_KAFKA_VERSION 的3.4,3.3等)
  2. 一次升级一个代理:关闭代理,更新代码,然后重新启动它。完成此作后, Broker 将运行最新版本,您可以验证集群的行为和性能是否符合预期。 如果有任何问题,此时仍然可以降级。
  3. 验证集群的行为和性能后,通过编辑来增加协议版本inter.broker.protocol.version并将其设置为3.5.
  4. 逐个重启 broker,新协议版本才能生效。一旦代理开始使用最新的 协议版本,则无法再将集群降级到旧版本。
  5. 如果您已按照上述说明覆盖了消息格式版本,则需要再执行一次滚动重启,以 将其升级到最新版本。所有(或大多数)消费者都升级到 0.11.0 或更高版本后, 将 log.message.format.version 更改为 3.5,然后逐个重启。请注意,较旧的 Scala 客户端 不再维护,不支持 0.11 中引入的 message 格式,从而避免转换成本 (或利用 Exactly once 语义)、 必须使用较新的 Java 客户端。
升级基于 KRaft 的集群

如果您要从 3.3.0 之前的版本升级,请参阅下面第 3 步中的说明。将 metadata.version 更改为最新版本后,将无法降级到 3.3-IV0 之前的版本。

对于滚动升级:

  1. 一次升级一个代理:关闭代理,更新代码,然后重新启动它。完成此作后, Broker 将运行最新版本,您可以验证集群的行为和性能是否符合预期。
  2. 验证集群的行为和性能后,通过运行 ./bin/kafka-features.sh upgrade --metadata 3.5
  3. 请注意,集群元数据版本升级后,无法降级到预生产 3.0.x、3.1.x 或 3.2.x 版本。 但是,可以降级到生产版本,例如 3.3-IV0、3.3-IV1 等。

从任何版本 0.8.x 到 3.3.x 升级到 3.4.0

如果您从 2.1.x 之前的版本升级,请参阅下面的说明,了解用于存储使用者偏移量的架构的更改。 将 inter.broker.protocol.version 更改为最新版本后,将无法降级到 2.1 之前的版本。

对于滚动升级:

  1. 更新所有代理上的 server.properties 并添加以下属性。CURRENT_KAFKA_VERSION 是指您 正在升级。CURRENT_MESSAGE_FORMAT_VERSION 是指当前正在使用的消息格式版本。如果您之前有 覆盖了 Message Format version,则应保留其当前值。或者,如果您要从之前的版本升级 设置为 0.11.0.x,则CURRENT_MESSAGE_FORMAT_VERSION应设置为 MATCH CURRENT_KAFKA_VERSION。
    • inter.broker.protocol.version=CURRENT_KAFKA_VERSION 的3.3,3.2等)
    • log.message.format.version=CURRENT_MESSAGE_FORMAT_VERSION (查看潜在的性能影响) 有关此配置的作用的详细信息。
    如果您从版本 0.11.0.x 或更高版本升级,并且您没有覆盖消息格式,则只需覆盖 Inter-Broker 协议版本。
    • inter.broker.protocol.version=CURRENT_KAFKA_VERSION 的3.3,3.2等)
  2. 一次升级一个代理:关闭代理,更新代码,然后重新启动它。完成此作后, Broker 将运行最新版本,您可以验证集群的行为和性能是否符合预期。 如果有任何问题,此时仍然可以降级。
  3. 验证集群的行为和性能后,通过编辑来增加协议版本inter.broker.protocol.version并将其设置为3.4.
  4. 逐个重启 broker,新协议版本才能生效。一旦代理开始使用最新的 协议版本,则无法再将集群降级到旧版本。
  5. 如果您已按照上述说明覆盖了消息格式版本,则需要再执行一次滚动重启,以 将其升级到最新版本。所有(或大多数)消费者都升级到 0.11.0 或更高版本后, 将每个代理的 log.message.format.version 更改为 3.4,然后逐个重新启动它们。请注意,较旧的 Scala 客户端 不再维护,不支持 0.11 中引入的 message 格式,从而避免转换成本 (或利用 Exactly once 语义)、 必须使用较新的 Java 客户端。

将基于 KRaft 的集群从任何版本 3.0.x 升级到 3.4.0 到 3.3.x

如果您从 3.3.0 之前的版本升级,请参阅下面的说明。将 metadata.version 更改为最新版本后,将无法降级到 3.3-IV0 之前的版本。

对于滚动升级:

  1. 一次升级一个代理:关闭代理,更新代码,然后重新启动它。完成此作后, Broker 将运行最新版本,您可以验证集群的行为和性能是否符合预期。
  2. 验证集群的行为和性能后,通过运行 ./bin/kafka-features.sh upgrade --metadata 3.4
  3. 请注意,集群元数据版本升级后,无法降级到预生产 3.0.x、3.1.x 或 3.2.x 版本。 但是,可以降级到生产版本,例如 3.3-IV0、3.3-IV1 等。
3.4.0 中的显著更改
  • 从 Apache Kafka 3.4.0 开始,我们添加了一个系统属性(“org.apache.kafka.disallowed.login.modules”)来禁用有问题的 SASL JAAS 配置中的登录模块使用情况。此外,默认情况下,Apache Kafka 3.4.0 中禁用了 “com.sun.security.auth.module.JndiLoginModule”。

从任何版本 0.8.x 到 3.2.x 升级到 3.3.1

如果您从 2.1.x 之前的版本升级,请参阅下面的说明,了解用于存储使用者偏移量的架构的更改。 将 inter.broker.protocol.version 更改为最新版本后,将无法降级到 2.1 之前的版本。

对于滚动升级:

  1. 更新所有代理上的 server.properties 并添加以下属性。CURRENT_KAFKA_VERSION 是指您 正在升级。CURRENT_MESSAGE_FORMAT_VERSION 是指当前正在使用的消息格式版本。如果您之前有 覆盖了 Message Format version,则应保留其当前值。或者,如果您要从之前的版本升级 设置为 0.11.0.x,则CURRENT_MESSAGE_FORMAT_VERSION应设置为 MATCH CURRENT_KAFKA_VERSION。
    • inter.broker.protocol.version=CURRENT_KAFKA_VERSION 的3.2,3.1等)
    • log.message.format.version=CURRENT_MESSAGE_FORMAT_VERSION (查看潜在的性能影响) 有关此配置的作用的详细信息。
    如果您从版本 0.11.0.x 或更高版本升级,并且您没有覆盖消息格式,则只需覆盖 Inter-Broker 协议版本。
    • inter.broker.protocol.version=CURRENT_KAFKA_VERSION 的3.2,3.1等)
  2. 一次升级一个代理:关闭代理,更新代码,然后重新启动它。完成此作后, Broker 将运行最新版本,您可以验证集群的行为和性能是否符合预期。 如果有任何问题,此时仍然可以降级。
  3. 验证集群的行为和性能后,通过编辑来增加协议版本inter.broker.protocol.version并将其设置为3.3.
  4. 逐个重启 broker,新协议版本才能生效。一旦代理开始使用最新的 协议版本,则无法再将集群降级到旧版本。
  5. 如果您已按照上述说明覆盖了消息格式版本,则需要再执行一次滚动重启,以 将其升级到最新版本。所有(或大多数)消费者都升级到 0.11.0 或更高版本后, 将 log.message.format.version 更改为 3.3,然后逐个重启。请注意,较旧的 Scala 客户端 不再维护,不支持 0.11 中引入的 message 格式,从而避免转换成本 (或利用 Exactly once 语义)、 必须使用较新的 Java 客户端。

将基于 KRaft 的集群从任何版本 3.0.x 升级到 3.3.1 到 3.2.x

如果您从 3.3.1 之前的版本升级,请参阅下面的说明。将 metadata.version 更改为最新版本后,将无法降级到 3.3-IV0 之前的版本。

对于滚动升级:

  1. 一次升级一个代理:关闭代理,更新代码,然后重新启动它。完成此作后, Broker 将运行最新版本,您可以验证集群的行为和性能是否符合预期。
  2. 验证集群的行为和性能后,通过运行 ./bin/kafka-features.sh upgrade --metadata 3.3
  3. 请注意,集群元数据版本升级后,无法降级到预生产 3.0.x、3.1.x 或 3.2.x 版本。但是,可以降级到生产版本,例如 3.3-IV0、3.3-IV1 等。
3.3.1 中的显著更改
  • KRaft 模式可用于新集群的生产环境。有关更多详细信息(包括限制),请参阅 KIP-833
  • 默认情况下用于无键记录的分区程序已得到改进,以避免在一个或多个代理速度较慢时出现病态行为。 新逻辑可能会影响批处理行为,可以使用batch.size和/或linger.ms配置设置。 可以通过设置partitioner.class=org.apache.kafka.clients.producer.internals.DefaultPartitioner. 有关更多详细信息,请参阅 KIP-794
  • 如上所述,现在 KRaft 集群的升级过程与基于 ZK 的集群略有不同。
  • 引入了新的 APIaddMetricIfAbsentMetrics这将创建一个新的 Metric(如果不存在)或返回相同的 Metric 如果已经注册。请注意,此行为与addMetricAPI 会抛出一个IllegalArgumentException什么时候 尝试创建已存在的量度。(有关详细信息,请参阅 KIP-843)。

从任何版本 0.8.x 到 3.1.x 升级到 3.2.0

如果您从 2.1.x 之前的版本升级,请参阅下面的说明,了解用于存储使用者偏移量的架构的更改。 将 inter.broker.protocol.version 更改为最新版本后,将无法降级到 2.1 之前的版本。

对于滚动升级:

  1. 更新所有代理上的 server.properties 并添加以下属性。CURRENT_KAFKA_VERSION 是指您 正在升级。CURRENT_MESSAGE_FORMAT_VERSION 是指当前正在使用的消息格式版本。如果您之前有 覆盖了 Message Format version,则应保留其当前值。或者,如果您要从之前的版本升级 设置为 0.11.0.x,则CURRENT_MESSAGE_FORMAT_VERSION应设置为 MATCH CURRENT_KAFKA_VERSION。
    • inter.broker.protocol.version=CURRENT_KAFKA_VERSION 的3.1,3.0等)
    • log.message.format.version=CURRENT_MESSAGE_FORMAT_VERSION (查看潜在的性能影响) 有关此配置的作用的详细信息。
    如果您从版本 0.11.0.x 或更高版本升级,并且您没有覆盖消息格式,则只需覆盖 Inter-Broker 协议版本。
    • inter.broker.protocol.version=CURRENT_KAFKA_VERSION 的3.1,3.0等)
  2. 一次升级一个代理:关闭代理,更新代码,然后重新启动它。完成此作后, Broker 将运行最新版本,您可以验证集群的行为和性能是否符合预期。 如果有任何问题,此时仍然可以降级。
  3. 验证集群的行为和性能后,通过编辑来增加协议版本inter.broker.protocol.version并将其设置为3.2.
  4. 逐个重启 broker,新协议版本才能生效。一旦代理开始使用最新的 协议版本,则无法再将集群降级到旧版本。
  5. 如果您已按照上述说明覆盖了消息格式版本,则需要再执行一次滚动重启,以 将其升级到最新版本。所有(或大多数)消费者都升级到 0.11.0 或更高版本后, 将 log.message.format.version 更改为 3.2,然后逐个重启。请注意,较旧的 Scala 客户端 不再维护,不支持 0.11 中引入的 message 格式,从而避免转换成本 (或利用 Exactly once 语义)、 必须使用较新的 Java 客户端。
3.2.0 中的显著变化
  • 如果未设置冲突配置,则默认情况下会启用生产者的幂等性。当向 2.8.0 之前的 broker 生产时, 这IDEMPOTENT_WRITE需要权限。检查兼容性 部分了解 KIP-679 的 THE MissAV.com 的 MissAV.com 的 MissAV.com |在 3.0.0 和 3.1.0 中,一个错误阻止了这个默认值的应用。 这意味着幂等性将保持禁用状态,除非用户明确设置enable.idempotence设置为 true (有关更多详细信息,请参阅 KAFKA-13598)。 此问题已修复,默认值已在 3.0.1、3.1.1 和 3.2.0 中正确应用。
  • 一个值得注意的例外是 Connect,默认情况下,它对其所有 producer 来统一支持使用各种 Kafka 代理版本。 用户可以更改此行为,以便为部分或全部生产者启用幂等性 通过 Connect worker 和/或 connector 配置。Connect 可以启用幂等生产者 在将来的主要版本中默认。
  • 出于安全考虑,Kafka 已将 log4j 替换为 reload4j。 这仅影响指定日志记录后端 (connect-runtimekafka-tools就是两个这样的例子)。 许多模块,包括kafka-clients,请让应用程序指定日志记录后端。 更多信息可以在 reload4j 上找到。 依赖于 Kafka 项目中受影响的模块的项目应使用 slf4j-log4j12 版本 1.7.35 或更高版本,或者 slf4j-reload4j 以避免由日志记录框架引起的可能兼容性问题
  • 示例连接器FileStreamSourceConnectorFileStreamSinkConnector一直 从默认 Classpath 中删除。要在 Kafka Connect 独立或分布式模式下使用它们,它们需要 显式添加,例如CLASSPATH=./libs/connect-file-3.2.0.jar ./bin/connect-distributed.sh.

从任何版本 0.8.x 升级到 3.1.0 到 3.0.x

如果您从 2.1.x 之前的版本升级,请参阅下面的说明,了解用于存储使用者偏移量的架构的更改。 将 inter.broker.protocol.version 更改为最新版本后,将无法降级到 2.1 之前的版本。

对于滚动升级:

  1. 更新所有代理上的 server.properties 并添加以下属性。CURRENT_KAFKA_VERSION 是指您 正在升级。CURRENT_MESSAGE_FORMAT_VERSION 是指当前正在使用的消息格式版本。如果您之前有 覆盖了 Message Format version,则应保留其当前值。或者,如果您要从之前的版本升级 设置为 0.11.0.x,则CURRENT_MESSAGE_FORMAT_VERSION应设置为 MATCH CURRENT_KAFKA_VERSION。
    • inter.broker.protocol.version=CURRENT_KAFKA_VERSION 的3.0,2.8等)
    • log.message.format.version=CURRENT_MESSAGE_FORMAT_VERSION (查看潜在的性能影响) 有关此配置的作用的详细信息。
    如果您从版本 0.11.0.x 或更高版本升级,并且您没有覆盖消息格式,则只需覆盖 Inter-Broker 协议版本。
    • inter.broker.protocol.version=CURRENT_KAFKA_VERSION 的3.0,2.8等)
  2. 一次升级一个代理:关闭代理,更新代码,然后重新启动它。完成此作后, Broker 将运行最新版本,您可以验证集群的行为和性能是否符合预期。 如果有任何问题,此时仍然可以降级。
  3. 验证集群的行为和性能后,通过编辑来增加协议版本inter.broker.protocol.version并将其设置为3.1.
  4. 逐个重启 broker,新协议版本才能生效。一旦代理开始使用最新的 协议版本,则无法再将集群降级到旧版本。
  5. 如果您已按照上述说明覆盖了消息格式版本,则需要再执行一次滚动重启,以 将其升级到最新版本。所有(或大多数)消费者都升级到 0.11.0 或更高版本后, 将 log.message.format.version 更改为 3.1,然后逐个重启。请注意,较旧的 Scala 客户端 不再维护,不支持 0.11 中引入的 message 格式,从而避免转换成本 (或利用 Exactly once 语义)、 必须使用较新的 Java 客户端。
3.1.1 中的显著更改
  • 如果未设置冲突配置,则默认情况下会启用生产者的幂等性。当向 2.8.0 之前的 broker 生产时, 这IDEMPOTENT_WRITE需要权限。检查兼容性 部分了解 KIP-679 的 THE MissAV.com 的 MissAV.com 的 MissAV.com |一个错误阻止了生产者幂等默认值的应用,这意味着除非用户 显式设置enable.idempotence设置为 true。请参阅 KAFKA-13598 更多细节。此问题已修复,默认值已正确应用。
  • 一个值得注意的例外是 Connect,默认情况下,它对其所有 producer 来统一支持使用各种 Kafka 代理版本。 用户可以更改此行为,以便为部分或全部生产者启用幂等性 通过 Connect worker 和/或 connector 配置。Connect 可以启用幂等生产者 在将来的主要版本中默认。
  • 出于安全考虑,Kafka 已将 log4j 替换为 reload4j。 这仅影响指定日志记录后端 (connect-runtimekafka-tools就是两个这样的例子)。 许多模块,包括kafka-clients,请让应用程序指定日志记录后端。 更多信息可以在 reload4j 上找到。 依赖于 Kafka 项目中受影响的模块的项目应使用 slf4j-log4j12 版本 1.7.35 或更高版本,或者 slf4j-reload4j 以避免由日志记录框架引起的可能兼容性问题
3.1.0 中的显著更改
  • Apache Kafka 支持 Java 17。
  • 以下指标已被弃用:bufferpool-wait-time-total,io-waittime-total, 和iotime-total.请使用bufferpool-wait-time-ns-total,io-wait-time-ns-total, 和io-time-ns-total相反。有关更多详细信息,请参阅 KIP-773
  • IBP 3.1 将主题 ID 作为 KIP-516 的一部分引入 FetchRequest。

从任何版本 0.8.x 到 2.8.x 升级到 3.0.1

如果您从 2.1.x 之前的版本升级,请参阅下面的说明,了解用于存储使用者偏移量的架构的更改。 将 inter.broker.protocol.version 更改为最新版本后,将无法降级到 2.1 之前的版本。

对于滚动升级:

  1. 更新所有代理上的 server.properties 并添加以下属性。CURRENT_KAFKA_VERSION 是指您 正在升级。CURRENT_MESSAGE_FORMAT_VERSION 是指当前正在使用的消息格式版本。如果您之前有 覆盖了 Message Format version,则应保留其当前值。或者,如果您要从之前的版本升级 设置为 0.11.0.x,则CURRENT_MESSAGE_FORMAT_VERSION应设置为 MATCH CURRENT_KAFKA_VERSION。
    • inter.broker.protocol.version=CURRENT_KAFKA_VERSION 的2.8,2.7等)
    • log.message.format.version=CURRENT_MESSAGE_FORMAT_VERSION (查看潜在的性能影响) 有关此配置的作用的详细信息。
    如果您从版本 0.11.0.x 或更高版本升级,并且您没有覆盖消息格式,则只需覆盖 Inter-Broker 协议版本。
    • inter.broker.protocol.version=CURRENT_KAFKA_VERSION 的2.8,2.7等)
  2. 一次升级一个代理:关闭代理,更新代码,然后重新启动它。完成此作后, Broker 将运行最新版本,您可以验证集群的行为和性能是否符合预期。 如果有任何问题,此时仍然可以降级。
  3. 验证集群的行为和性能后,通过编辑来增加协议版本inter.broker.protocol.version并将其设置为3.0.
  4. 逐个重启 broker,新协议版本才能生效。一旦代理开始使用最新的 协议版本,则无法再将集群降级到旧版本。
  5. 如果您已按照上述说明覆盖了消息格式版本,则需要再执行一次滚动重启,以 将其升级到最新版本。所有(或大多数)消费者都升级到 0.11.0 或更高版本后, 将 log.message.format.version 修改为 3.0,然后逐个重启。请注意,较旧的 Scala 客户端 不再维护,不支持 0.11 中引入的 message 格式,从而避免转换成本 (或利用 Exactly once 语义)、 必须使用较新的 Java 客户端。
3.0.1 中的显著更改
  • 如果未设置冲突配置,则默认情况下会启用生产者的幂等性。当向 2.8.0 之前的 broker 生产时, 这IDEMPOTENT_WRITE需要权限。检查兼容性 部分了解 KIP-679 的 THE MissAV.com 的 MissAV.com 的 MissAV.com |一个错误阻止了生产者幂等默认值的应用,这意味着除非用户 显式设置enable.idempotence设置为 true。请参阅 KAFKA-13598 更多细节。此问题已修复,默认值已正确应用。
3.0.0 中的显著更改
  • 默认情况下,创建者具有更强的传输保证:idempotence已启用,并且acks设置为all而不是1. 有关详细信息,请参阅 KIP-679。 在 3.0.0 和 3.1.0 中,一个错误阻止了幂等默认值的应用,这意味着除非用户明确设置enable.idempotence设置为 true。请注意,该 bug 不会影响acks=all改变。有关更多详细信息,请参阅 KAFKA-13598。 此问题已修复,默认值已在 3.0.1、3.1.1 和 3.2.0 中正确应用。
  • Java 8 和 Scala 2.12 支持自 Apache Kafka 3.0 起已弃用,并将在 Apache Kafka 4.0 中删除。 有关更多详细信息,请参阅 KIP-750KIP-751
  • ZooKeeper 已升级到版本 3.6.3。
  • KRaft 模式的预览版可用,但无法从 2.8 Early Access 版本升级到它。看 这config/kraft/README.md文件了解详细信息。
  • 发布 tarball 不再包含 test、sources、javadoc 和 test sources jar。这些仍会发布到 Maven Central 存储库。
  • 现在,运行时类路径中提供了许多实现依赖项 jar 而不是 compile 和 runtime 类路径。升级后的编译错误可以通过显式添加缺少的依赖项 jar 来修复 或更新应用程序以不使用内部类。
  • 使用者配置的默认值session.timeout.ms由 10 秒增加至 45 秒。有关更多详细信息,请参阅 KIP-735
  • 代理配置log.message.format.version和 Topic 配置message.format.version已被弃用。 这两个配置的值始终假定为3.0如果inter.broker.protocol.version3.0或更高。 如果log.message.format.versionmessage.format.version设置,我们建议在清除inter.broker.protocol.version升级到 3.0。这将避免潜在的兼容性问题,如果inter.broker.protocol.version被降级。有关更多详细信息,请参阅 KIP-724
  • Streams API 删除了版本 2.5.0 或更早版本中不推荐使用的所有已弃用的 API。 有关已删除 API 的完整列表,请参阅详细的 Kafka Streams 升级说明。
  • Kafka Streams 不再依赖于 “connect:json” 模块 (KAFKA-5146)。 依赖此传递依赖项的项目必须显式声明它。
  • 通过principal.builder.class现在必须实现KafkaPrincipalSerde接口以允许在 broker 之间进行转发。有关使用 KafkaPrincipalSerde 的更多详细信息,请参阅 KIP-590
  • 许多已弃用的类、方法和工具已从clients,connect,coretools模块:
    • The ScalaAuthorizer,SimpleAclAuthorizer,并且已删除相关类。请使用 JavaAuthorizerAclAuthorizer相反。
    • Metric#value()方法已删除 (KAFKA-12573)。
    • SumTotal类已删除 (KAFKA-12584)。 请使用WindowedSumCumulativeSum相反。
    • CountSampledTotal类被删除。请使用WindowedCountWindowedSum相反。
    • PrincipalBuilder,DefaultPrincipalBuilderResourceFilter类被删除。
    • SslConfigs,SaslConfigs,AclBindingAclBindingFilter.
    • Admin.electedPreferredLeaders()方法。请使用Admin.electLeaders相反。
    • kafka-preferred-replica-election命令行工具已删除。请使用kafka-leader-election相反。
    • --zookeeper选项已从kafka-topicskafka-reassign-partitions命令行工具。 请使用--bootstrap-server相反。
    • kafka-configs命令行工具、--zookeeper选项仅支持更新 SCRAM 凭证配置描述/更新代理未运行时的动态代理配置。请使用--bootstrap-server用于其他配置作。
    • ConfigEntry构造函数已删除 (KAFKA-12577)。 请改用剩余的 public 构造函数。
    • config 值default对于客户端配置client.dns.lookup已被删除。在不太可能的情况下 如果您显式设置了此配置,我们建议将配置保留为未设置 (use_all_dns_ips默认使用)。
    • ExtendedDeserializerExtendedSerializer类已被删除。请使用DeserializerSerializer相反。
    • close(long, TimeUnit)方法已从 producer、consumer 和 admin 客户端中删除。请使用close(Duration).
    • ConsumerConfig.addDeserializerToConfigProducerConfig.addSerializerToConfig方法 被删除。这些方法不是公共 API,因此没有替代方法。
    • NoOffsetForPartitionException.partition()方法已删除。请使用partitions()相反。
    • 默认的partition.assignment.strategy更改为 “[RangeAssignor, CooperativeStickyAssignor]”, 默认情况下,它将使用 RangeAssignor,但允许升级到 CooperativeStickyAssignor,只需一次滚动反弹即可从列表中删除 RangeAssignor。 有关更多详细信息,请在此处查看客户端升级路径指南。
    • The Scalakafka.common.MessageFormatter已删除。请使用 Javaorg.apache.kafka.common.MessageFormatter.
    • MessageFormatter.init(Properties)方法已删除。请使用configure(Map)相反。
    • checksum()方法已从ConsumerRecordRecordMetadata.信息 格式 v2(自 0.11 起一直是默认值)将校验和从记录批次移动到记录批次。因此,这些方法 没有意义,也没有替代品。
    • ChecksumMessageFormatter类已删除。它不是公共 API 的一部分,但可能已被使用 跟kafka-console-consumer.sh.它报告了每条记录的校验和,但一直不支持 从 Message Format V2.
    • org.apache.kafka.clients.consumer.internals.PartitionAssignor类已被删除。请使用org.apache.kafka.clients.consumer.ConsumerPartitionAssignor相反。
    • quota.producer.defaultquota.consumer.default配置已删除 (KAFKA-12591)。 必须改用动态配额默认值。
    • porthost.name配置已删除。请使用listeners相反。
    • advertised.portadvertised.host.name配置已删除。请使用advertised.listeners相反。
    • 已弃用的 worker 配置rest.host.namerest.port已从 Kafka Connect 工作程序配置中删除 (KAFKA-12482)。 请使用listeners相反。
  • Producer#sendOffsetsToTransaction(Map offsets, String consumerGroupId)方法已弃用。请使用Producer#sendOffsetsToTransaction(Map offsets, ConsumerGroupMetadata metadata)相反,其中ConsumerGroupMetadata可以通过以下方式检索KafkaConsumer#groupMetadata()以获得更强的语义。请注意,完整的使用者组元数据集仅为 被 broker 或 2.5 或更高版本理解,因此您必须升级 Kafka 集群以获得更强的语义。否则,你可以直接通过 在new ConsumerGroupMetadata(consumerGroupId)与较老的经纪人合作。有关更多详细信息,请参阅 KIP-732
  • 连接internal.key.converterinternal.value.converter属性已被完全删除。 自版本 2.0.0 起,这些 Connect 工作线程属性的使用已被弃用。 Worker 现在被硬编码为使用 JSON 转换器schemas.enable设置为false.如果您的集群一直在使用 使用不同的内部密钥或值转换器,您可以按照 KIP-738 中概述的迁移步骤安全地将 Connect 集群升级到 3.0。
  • 基于 Connect 的 MirrorMaker (MM2) 包括对支持的更改IdentityReplicationPolicy,在不重命名主题的情况下启用复制。 现有的DefaultReplicationPolicy仍默认使用,但可以通过replication.policyconfiguration 属性。这对于从旧版 MirrorMaker (MM1) 迁移的用户或 具有简单单向复制拓扑的用例,其中不需要主题重命名。请注意,IdentityReplicationPolicyDefaultReplicationPolicy无法阻止基于主题名称的复制周期,因此在构建 复制拓扑。
  • 原始 MirrorMaker (MM1) 和相关类已被弃用。请使用基于 Connect 的 MirrorMaker (MM2),如异地复制部分所述。

从任何版本 0.8.x 升级到 2.7.x 到 2.7.1

如果您从 2.1.x 之前的版本升级,请参阅下面的说明,了解用于存储使用者偏移量的架构的更改。 将 inter.broker.protocol.version 更改为最新版本后,将无法降级到 2.1 之前的版本。

对于滚动升级:

  1. 更新所有代理上的 server.properties 并添加以下属性。CURRENT_KAFKA_VERSION 是指您 正在升级。CURRENT_MESSAGE_FORMAT_VERSION 是指当前正在使用的消息格式版本。如果您之前有 覆盖了 Message Format version,则应保留其当前值。或者,如果您要从之前的版本升级 设置为 0.11.0.x,则CURRENT_MESSAGE_FORMAT_VERSION应设置为 MATCH CURRENT_KAFKA_VERSION。
    • inter.broker.protocol.version=CURRENT_KAFKA_VERSION 的2.7,2.6等)
    • log.message.format.version=CURRENT_MESSAGE_FORMAT_VERSION (查看潜在的性能影响) 有关此配置的作用的详细信息。
    如果您从版本 0.11.0.x 或更高版本升级,并且您没有覆盖消息格式,则只需覆盖 Inter-Broker 协议版本。
    • inter.broker.protocol.version=CURRENT_KAFKA_VERSION 的2.7,2.6等)
  2. 一次升级一个代理:关闭代理,更新代码,然后重新启动它。完成此作后, Broker 将运行最新版本,您可以验证集群的行为和性能是否符合预期。 如果有任何问题,此时仍然可以降级。
  3. 验证集群的行为和性能后,通过编辑来增加协议版本inter.broker.protocol.version并将其设置为2.8.
  4. 逐个重启 broker,新协议版本才能生效。一旦代理开始使用最新的 协议版本,则无法再将集群降级到旧版本。
  5. 如果您已按照上述说明覆盖了消息格式版本,则需要再执行一次滚动重启,以 将其升级到最新版本。所有(或大多数)消费者都升级到 0.11.0 或更高版本后, 将每个代理上的 log.message.format.version 更改为 2.8,然后逐个重新启动它们。请注意,较旧的 Scala 客户端 不再维护,不支持 0.11 中引入的 message 格式,从而避免转换成本 (或利用 Exactly once 语义)、 必须使用较新的 Java 客户端。
2.8.0 中的显著变化
  • 2.8.0 版本向 KIP-679 中引入的授权方接口添加了一种新方法。 动机是解锁我们的未来计划,以默认启用最强的消息传递保证。 自定义授权方应考虑提供更高效的实现,以支持审核日志记录和任何自定义配置或访问规则。
  • IBP 2.8 作为 KIP-516 的一部分,为主题引入了主题 ID。 使用 ZooKeeper 时,此信息存储在 TopicZNode 中。如果集群已降级到以前的 IBP 或版本, 将来的主题不会获得主题 ID,并且不能保证主题将在 ZooKeeper 中保留其主题 ID。 这意味着在再次升级时,某些主题或所有主题将被分配新的 ID。
  • Kafka Streams 引入了类型安全的split()运算符作为 deprecated 的替代品KStream#branch()方法 (参见 KIP-418)。

从任何版本 0.8.x 升级到 2.7.0 到 2.6.x

如果您从 2.1.x 之前的版本升级,请参阅下面的说明,了解用于存储使用者偏移量的架构的更改。 将 inter.broker.protocol.version 更改为最新版本后,将无法降级到 2.1 之前的版本。

对于滚动升级:

  1. 更新所有代理上的 server.properties 并添加以下属性。CURRENT_KAFKA_VERSION 是指您 正在升级。CURRENT_MESSAGE_FORMAT_VERSION 是指当前正在使用的消息格式版本。如果您之前有 覆盖了 Message Format version,则应保留其当前值。或者,如果您要从之前的版本升级 设置为 0.11.0.x,则CURRENT_MESSAGE_FORMAT_VERSION应设置为 MATCH CURRENT_KAFKA_VERSION。
    • inter.broker.protocol.version=CURRENT_KAFKA_VERSION 的2.6,2.5等)
    • log.message.format.version=CURRENT_MESSAGE_FORMAT_VERSION (查看潜在的性能影响) 有关此配置的作用的详细信息。
    如果您从版本 0.11.0.x 或更高版本升级,并且您没有覆盖消息格式,则只需覆盖 Inter-Broker 协议版本。
    • inter.broker.protocol.version=CURRENT_KAFKA_VERSION 的2.6,2.5等)
  2. 一次升级一个代理:关闭代理,更新代码,然后重新启动它。完成此作后, Broker 将运行最新版本,您可以验证集群的行为和性能是否符合预期。 如果有任何问题,此时仍然可以降级。
  3. 验证集群的行为和性能后,通过编辑来增加协议版本inter.broker.protocol.version并将其设置为2.7.
  4. 逐个重启 broker,新协议版本才能生效。一旦代理开始使用最新的 协议版本,则无法再将集群降级到旧版本。
  5. 如果您已按照上述说明覆盖了消息格式版本,则需要再执行一次滚动重启,以 将其升级到最新版本。所有(或大多数)消费者都升级到 0.11.0 或更高版本后, 将 log.message.format.version 更改为 2.7,然后逐个重启。请注意,较旧的 Scala 客户端 不再维护,不支持 0.11 中引入的 message 格式,从而避免转换成本 (或利用 Exactly once 语义)、 必须使用较新的 Java 客户端。
2.7.0 中的显著变化
  • 2.7.0 版本包括 KIP-595 中指定的核心 Raft 实现。 有一个单独的 “raft” 模块,包含大部分 logic。在与 controller 完成后,用户可以使用一个独立的服务器来测试 性能。有关详细信息,请参阅 raft 模块中的 README.md
  • KIP-651 增加了对将 PEM 文件用于密钥和信任存储的支持。
  • KIP-612 增加了对强制执行代理范围和每个侦听器连接创建速率的支持。2.7.0 版本包含 KIP-612 的第一部分,动态配置将在 2.8.0 版本中推出。
  • 能够限制主题和分区创建,或者 主题删除以防止集群受到 KIP-599 的损害
  • 当 Kafka 中提供新功能时,有两个主要问题:
    1. Kafka 客户端如何了解代理功能?
    2. 经纪人如何决定启用哪些功能?
    KIP-584 为客户端发现、功能门控和滚动升级提供了灵活且作简单的解决方案,只需重新启动一次即可。
  • 能够使用ConsoleConsumer现在可以 通过 KIP-431
  • KIP-554 的加入继续朝着从 Kafka 中删除 Zookeeper 的目标迈进。KIP-554 的加入 意味着您不必再直接连接到 ZooKeeper 来管理 SCRAM 凭证。
  • 更改现有侦听器的 non-re-configurable configs 导致InvalidRequestException. 相比之下,之前的(意外的)行为会导致更新的配置被持久化。 但事实并非如此 生效,直到 Broker 重新启动。有关更多讨论,请参阅 KAFKA-10479。 看DynamicBrokerConfig.DynamicSecurityConfigsSocketServer.ListenerReconfigurableConfigs对于现有侦听器支持的 reconfigurable configs。
  • Kafka Streams 在 KStreams DSL 中添加了对滑动窗口聚合的支持。
  • 对状态存储进行反向迭代,使用 KIP-617 实现更高效的最新更新搜索
  • Kafka Steams 中的端到端延迟指标,请参阅 KIP-613 了解更多详情
  • Kafka Streams 使用 KIP-607 添加了报告默认 RocksDB 属性的指标
  • KIP-616 中更好的 Scala 隐式 Serdes 支持

从任何版本 0.8.x 升级到 2.6.0 到 2.5.x

如果您从 2.1.x 之前的版本升级,请参阅下面的说明,了解用于存储使用者偏移量的架构的更改。 将 inter.broker.protocol.version 更改为最新版本后,将无法降级到 2.1 之前的版本。

对于滚动升级:

  1. 更新所有代理上的 server.properties 并添加以下属性。CURRENT_KAFKA_VERSION 是指您 正在升级。CURRENT_MESSAGE_FORMAT_VERSION 是指当前正在使用的消息格式版本。如果您之前有 覆盖了 Message Format version,则应保留其当前值。或者,如果您要从之前的版本升级 设置为 0.11.0.x,则CURRENT_MESSAGE_FORMAT_VERSION应设置为 MATCH CURRENT_KAFKA_VERSION。
    • inter.broker.protocol.version=CURRENT_KAFKA_VERSION 的2.5,2.4等)
    • log.message.format.version=CURRENT_MESSAGE_FORMAT_VERSION (查看潜在的性能影响) 有关此配置的作用的详细信息。
    如果您从版本 0.11.0.x 或更高版本升级,并且您没有覆盖消息格式,则只需覆盖 Inter-Broker 协议版本。
    • inter.broker.protocol.version=CURRENT_KAFKA_VERSION 的2.5,2.4等)
  2. 一次升级一个代理:关闭代理,更新代码,然后重新启动它。完成此作后, Broker 将运行最新版本,您可以验证集群的行为和性能是否符合预期。 如果有任何问题,此时仍然可以降级。
  3. 验证集群的行为和性能后,通过编辑来增加协议版本inter.broker.protocol.version并将其设置为2.6.
  4. 逐个重启 broker,新协议版本才能生效。一旦代理开始使用最新的 协议版本,则无法再将集群降级到旧版本。
  5. 如果您已按照上述说明覆盖了消息格式版本,则需要再执行一次滚动重启,以 将其升级到最新版本。所有(或大多数)消费者都升级到 0.11.0 或更高版本后, 将 log.message.format.version 修改为 2.6,然后逐个重启。请注意,较旧的 Scala 客户端 不再维护,不支持 0.11 中引入的 message 格式,从而避免转换成本 (或利用 Exactly once 语义)、 必须使用较新的 Java 客户端。
2.6.0 中的显著变化
  • Kafka Streams 添加了一种新的处理模式(需要代理 2.5 或更高版本),以改进应用程序 使用 Exactly-Once 保证的可扩展性 (参见 KIP-447)
  • 默认情况下,Java 11 或更高版本已启用 TLSv1.3。如果 两者都支持它,否则回退到 TLSv1.2。有关更多详细信息,请参阅 KIP-573
  • client.dns.lookup配置已从defaultuse_all_dns_ips.如果主机名解析为多个 IP 地址,则客户端和代理现在将 尝试按顺序连接到每个 IP,直到成功建立连接。有关更多详细信息,请参阅 KIP-602
  • NotLeaderForPartitionException已弃用并替换为NotLeaderOrFollowerException. Fetch 请求和其他仅用于 leader 或 follower 的请求返回 NOT_LEADER_OR_FOLLOWER(6) 而不是 REPLICA_NOT_AVAILABLE(9) 如果代理不是副本,请确保所有客户端在重新分配期间将此暂时性错误作为可重试异常处理。

从任何版本 0.8.x 到 2.4.x 升级到 2.5.0

如果您从 2.1.x 之前的版本升级,请参阅下面的说明,了解用于存储使用者偏移量的架构的更改。 将 inter.broker.protocol.version 更改为最新版本后,将无法降级到 2.1 之前的版本。

对于滚动升级:

  1. 更新所有代理上的 server.properties 并添加以下属性。CURRENT_KAFKA_VERSION 是指您 正在升级。CURRENT_MESSAGE_FORMAT_VERSION 是指当前正在使用的消息格式版本。如果您之前有 覆盖了 Message Format version,则应保留其当前值。或者,如果您要从之前的版本升级 设置为 0.11.0.x,则CURRENT_MESSAGE_FORMAT_VERSION应设置为 MATCH CURRENT_KAFKA_VERSION。
    • inter.broker.protocol.version=CURRENT_KAFKA_VERSION 的2.4,2.3等)
    • log.message.format.version=CURRENT_MESSAGE_FORMAT_VERSION (查看潜在的性能影响) 有关此配置的作用的详细信息。
    如果您从版本 0.11.0.x 或更高版本升级,并且您没有覆盖消息格式,则只需覆盖 Inter-Broker 协议版本。
    • inter.broker.protocol.version=CURRENT_KAFKA_VERSION 的2.4,2.3等)
  2. 一次升级一个代理:关闭代理,更新代码,然后重新启动它。完成此作后, Broker 将运行最新版本,您可以验证集群的行为和性能是否符合预期。 如果有任何问题,此时仍然可以降级。
  3. 验证集群的行为和性能后,通过编辑来增加协议版本inter.broker.protocol.version并将其设置为2.5.
  4. 逐个重启 broker,新协议版本才能生效。一旦代理开始使用最新的 协议版本,则无法再将集群降级到旧版本。
  5. 如果您已按照上述说明覆盖了消息格式版本,则需要再执行一次滚动重启,以 将其升级到最新版本。所有(或大多数)消费者都升级到 0.11.0 或更高版本后, 将每个代理上的 log.message.format.version 更改为 2.5,然后逐个重新启动它们。请注意,较旧的 Scala 客户端 不再维护,不支持 0.11 中引入的 message 格式,从而避免转换成本 (或利用 Exactly once 语义)、 必须使用较新的 Java 客户端。
  6. 重新分配工具有几项显著变化kafka-reassign-partitions.shKIP-455 完成后。 此工具现在需要--additional标志,以便在更改 主动重新分配。现在可以使用--cancel命令。最后,使用--zookeeper已被弃用,取而代之的是--bootstrap-server.有关更多详细信息,请参阅 KIP。
2.5.0 中的显著更改
  • 什么时候RebalanceProtocol#COOPERATIVEConsumer#poll仍可返回数据 当它处于消费者仍然拥有的那些分区的再平衡过程中;另外Consumer#commitSync现在可能会抛出一个非致命的RebalanceInProgressException通知 用户此类事件,为了区分致命的CommitFailedException并允许 users 完成正在进行的再平衡,然后重新尝试为那些仍然拥有的分区提交偏移量。
  • 为了提高典型网络环境中的弹性,默认值zookeeper.session.timeout.ms由 6 秒增加到 18 秒,并且replica.lag.time.max.ms从 10 秒到 30 秒。
  • 新的 DSL 运算符cogroup()已添加,以便一次将多个流聚合在一起。
  • 添加了一个新的KStream.toTable()用于将输入事件流转换为 KTable 的 API。
  • 添加了新的 Serde 类型Void表示 Input 主题中的 Null 键或 Null 值。
  • 荒废的UsePreviousTimeOnInvalidTimestamp并将其替换为UsePartitionTimeOnInvalidTimeStamp.
  • 通过添加待处理的偏移隔离机制和更强的事务提交,改进了 exactly-once 语义 一致性检查,这大大简化了可扩展的 Exactly-Once 应用程序的实现。 我们还在 examples 文件夹下添加了一个新的 exactly-once 语义代码示例。查看 KIP-447 了解完整详细信息。
  • 添加了新的公共 APIKafkaStreams.queryMetadataForKey(String, K, Serializer) to get detailed information on the key being queried. It provides information about the partition number where the key resides in addition to hosts containing the active and standby partitions for the key.
  • 通过弃用,支持查询过时的存储(以实现高可用性)和属于特定分区的存储KafkaStreams.store(String, QueryableStoreType)并将其替换为KafkaStreams.store(StoreQueryParameters).
  • 添加了一个新的公共 API,用于访问实例本地存储的滞后信息,其中包含KafkaStreams.allLocalStorePartitionLags().
  • Scala 2.11 不再受支持。有关详细信息,请参阅 KIP-531
  • 包中的所有 Scala 类kafka.security.auth已被弃用。请参阅 KIP-504,了解 2.4.0 中添加的新 Java 授权方 API 的详细信息。请注意,kafka.security.auth.Authorizerkafka.security.auth.SimpleAclAuthorizer在 2.4.0 中已弃用。
  • TLSv1 和 TLSv1.1 默认处于禁用状态,因为它们具有已知的安全漏洞。现在只有 TLSv1.2 默认启用。您可以通过在配置选项中显式启用 TLSv1 和 TLSv1.1 来继续使用它们ssl.protocolssl.enabled.protocols.
  • ZooKeeper 已升级到 3.5.7,如果 3.4 数据目录中没有快照文件,则从 3.4.X 到 3.5.7 的 ZooKeeper 升级可能会失败。 这通常发生在测试升级中,其中 ZooKeeper 3.5.7 尝试加载尚未创建快照文件的现有 3.4 数据目录。 有关此问题的更多详细信息,请参阅 ZOOKEEPER-3056ZOOKEEPER-3056 中给出了一个修复方法,即将snapshot.trust.empty=trueconfig 中zookeeper.properties升级前。
  • ZooKeeper 版本 3.5.7 支持与 ZooKeeper 的 TLS 加密连接,无论是否使用客户端证书, 以及其他 Kafka 配置可用于利用这一点。 有关详细信息,请参阅 KIP-515

从 0.8.x、0.9.x、0.10.0.x、0.10.1.x、0.10.2.x、0.11.0.x、1.0.x、1.1.x、2.0.x 或 2.1.x 或 2.2.x 或 2.3.x 升级到 2.4.0

如果您从 2.1.x 之前的版本升级,请参阅下面的说明,了解用于存储使用者偏移量的架构的更改。 将 inter.broker.protocol.version 更改为最新版本后,将无法降级到 2.1 之前的版本。

对于滚动升级:

  1. 更新所有代理上的 server.properties 并添加以下属性。CURRENT_KAFKA_VERSION 是指您 正在升级。CURRENT_MESSAGE_FORMAT_VERSION 是指当前正在使用的消息格式版本。如果您之前有 覆盖了 Message Format version,则应保留其当前值。或者,如果您要从之前的版本升级 设置为 0.11.0.x,则CURRENT_MESSAGE_FORMAT_VERSION应设置为 MATCH CURRENT_KAFKA_VERSION。
    • inter.broker.protocol.version=CURRENT_KAFKA_VERSION (例如 0.10.0、0.11.0、1.0、2.0、2.2)。
    • log.message.format.version=CURRENT_MESSAGE_FORMAT_VERSION (查看潜在的性能影响) 有关此配置的作用的详细信息。
    如果您从版本 0.11.0.x 或更高版本升级,并且您没有覆盖消息格式,则只需覆盖 Inter-Broker 协议版本。
    • inter.broker.protocol.version=CURRENT_KAFKA_VERSION (0.11.0, 1.0, 1.1, 2.0, 2.1, 2.2, 2.3).
  2. 一次升级一个代理:关闭代理,更新代码,然后重新启动它。完成此作后, Broker 将运行最新版本,您可以验证集群的行为和性能是否符合预期。 如果有任何问题,此时仍然可以降级。
  3. 验证集群的行为和性能后,通过编辑来增加协议版本inter.broker.protocol.version并将其设置为 2.4。
  4. 逐个重启 broker,新协议版本才能生效。一旦代理开始使用最新的 协议版本,则无法再将集群降级到旧版本。
  5. 如果您已按照上述说明覆盖了消息格式版本,则需要再执行一次滚动重启,以 将其升级到最新版本。所有(或大多数)消费者都升级到 0.11.0 或更高版本后, 将 log.message.format.version 更改为 2.4,然后逐个重启。请注意,较旧的 Scala 客户端 不再维护,不支持 0.11 中引入的 message 格式,从而避免转换成本 (或利用 Exactly once 语义)、 必须使用较新的 Java 客户端。

其他升级说明:

  1. ZooKeeper 已升级到 3.5.6。如果 3.4 数据目录中没有快照文件,则 ZooKeeper 从 3.4.X 升级到 3.5.6 可能会失败。 这通常发生在测试升级中,其中 ZooKeeper 3.5.6 尝试加载尚未创建快照文件的现有 3.4 数据目录。 有关此问题的更多详细信息,请参阅 ZOOKEEPER-3056ZOOKEEPER-3056 中给出了一个修复方法,即将snapshot.trust.empty=trueconfig 中zookeeper.properties升级前。但是,我们在使用snapshot.trust.empty=trueconfig。有关该问题的更多详细信息,请参阅 ZOOKEEPER-3644。 因此,我们建议将空快照文件复制到 3.4 数据目录 如果 3.4 数据目录中没有快照文件。有关解决方法的更多详细信息,请参阅 ZooKeeper 升级常见问题解答
  2. 在 ZooKeeper 3.5 中添加的基于 Jetty 的嵌入式 AdminServer。 AdminServer 在 ZooKeeper 中默认启用,并在端口 8080 上启动。 默认情况下,AdminServer 在 ZooKeeper 配置(zookeeper.properties) 由 Apache Kafka 发行版提供。 请务必更新您的本地zookeeper.properties文件替换为admin.enableServer=false如果您希望禁用 AdminServer。 请参考 AdminServer 配置 AdminServer。
2.4.0 中的显著变化
  • 添加了用于分区重新分配的新 Admin API。由于 Kafka 传播重新分配信息的方式发生了变化, 升级到新版本时,在失败的边缘情况下可能会丢失重新分配状态。建议不要在升级时开始重新分配。
  • ZooKeeper 已从 3.4.14 升级到 3.5.6。新版本支持 TLS 和动态重新配置。
  • bin/kafka-preferred-replica-election.sh命令行工具已弃用。它已被bin/kafka-leader-election.sh.
  • 方法electPreferredLeaders在 Java 中AdminClientclass 已被弃用,取而代之的是electLeaders.
  • Scala 代码利用NewTopic(String, int, short)构造函数将需要显式调用toShort在第二个文本上。
  • 构造函数中的参数GroupAuthorizationException(String)现在用于指定异常消息。 以前,它指的是授权失败的组。这样做是为了与其他异常类型保持一致,并 避免潜在的误用。构造函数TopicAuthorizationException(String)之前用于单个 未授权的话题也被类似地改变了。
  • 内部的PartitionAssignorinterface 已弃用并替换为新的ConsumerPartitionAssignor在公共 API 中。一些 方法/签名在两个接口之间略有不同。实现自定义 PartitionAssignor 的用户应尽快迁移到新接口。
  • DefaultPartitioner现在使用粘性分区策略。这意味着特定主题的记录具有 null 键且没有分配的分区 将发送到同一分区,直到该批次准备好发送为止。创建新批处理时,将选择新分区。这减少了 produce 的延迟,但 在边缘情况下,它可能会导致记录在分区之间的分布不均匀。通常,用户不会受到影响,但这种差异在测试和 其他情况会在很短的时间内生成记录。
  • 阻塞KafkaConsumer#committed方法已扩展为允许将分区列表作为输入参数,而不是单个分区。 它可以减少客户端和代理之间获取使用者组提交的偏移量的请求/响应迭代。 旧的重载函数已弃用,我们建议用户更改代码以利用新方法(详细信息 可以在 KIP-520 中找到)。
  • 我们引入了一个新的INVALID_RECORDerror 与CORRUPT_MESSAGE错误。 更具体地说,以前,当一批记录作为单个请求的一部分发送到 broker 并且一个或多个记录失败时 由于各种原因(魔术字节不匹配、CRC 校验和错误、日志压缩主题的空键等)导致的验证,整个批次将被拒绝 具有相同的误导性CORRUPT_MESSAGE,并且创建者客户端的调用方将看到来自以下任一 的未来对象RecordMetadatasendcall 以及Callback#onCompletion(RecordMetadata metadata, Exception exception)现在,有了新的错误代码和改进的异常错误消息,创建者调用者可以更好地了解其发送记录失败的根本原因。
  • 我们正在将增量协作再平衡引入客户端的组协议,这允许消费者在再平衡期间保留所有分配的分区 最后,仅撤销那些必须迁移到另一个使用者以实现整体集群平衡的 API。这ConsumerCoordinator将选择最新的RebalanceProtocol这通常受到 Consumer 的所有支持的 assignor 的支持。您可以使用新的内置CooperativeStickyAssignor或插入您自己的自定义 Cooperative Assignor。待办事项 因此,您必须实现ConsumerPartitionAssignor接口和 includeRebalanceProtocol.COOPERATIVE在 return by 返回的列表中ConsumerPartitionAssignor#supportedProtocols. 然后,您的自定义分配器可以利用ownedPartitions字段在每个使用者的Subscription尽可能将分区归还给以前的所有者。请注意,当 分区要重新分配给另一个消费者,必须将其从新分配中删除,直到它从其原始所有者处撤销。任何必须撤销分区的消费者都将触发 后续再平衡,以允许将已撤销的分区安全地分配给其新所有者。有关更多信息,请参见ConsumerPartitionAssignor RebalanceProtocol javadocs
    要从旧的 (eager) 协议(总是在重新平衡之前撤销所有分区)升级到协作式重新平衡,您必须遵循特定的升级路径以使所有客户端位于同一
    ConsumerPartitionAssignor支持合作协议。这可以通过两次滚动弹跳来完成,使用CooperativeStickyAssignor例如:在第一个作中,将 “cooperative-sticky” 添加到支持的分配器列表中 对于每个成员(不删除前一个分配者 - 请注意,如果以前使用默认值,则还必须显式包含该分配器)。然后,您可以退回和/或升级它。 一旦整个组都处于 2.4+ 状态,并且所有成员在其支持的分配器中都有 “cooperative-sticky”,则删除其他分配器并执行第二次滚动退回,以便到最后所有成员都只支持 合作协议。有关协作式再平衡协议和升级路径的更多详细信息,请参阅 KIP-429
  • 有一些行为变化ConsumerRebalanceListener以及新的 API。在侦听器的三个回调中的任何一个期间引发的异常将不再被吞噬,而是被重新引发 一直到Consumer.poll()叫。这onPartitionsLost方法,以允许用户对消费者可能失去其分区所有权的异常情况做出反应 (例如错过了 rebalance)并且无法提交偏移量。默认情况下,这将简单地调用现有的onPartitionsRevokedAPI 与之前的行为保持一致。但请注意,onPartitionsLost不会 当 LOST PARTITIONS 集为空时调用。这意味着,在加入组的新 Consumer 的第一次再平衡开始时,不会调用任何回调。
    的语义
    ConsumerRebalanceListener's当遵循上述 Cooperative Rebalancing 协议时,回调会进一步更改。除了onPartitionsLost,onPartitionsRevoked当已撤销的分区集为空时,也永远不会调用。回调通常仅在再平衡结束时调用,并且仅在要移动到另一个使用者的分区集上调用。这onPartitionsAssigned然而,即使分区集为空,也将始终调用 callback 作为通知用户 Rebalance 事件的一种方式(对于 cooperative 和 eager 都是如此)。有关详细信息 新的回调语义,请参见 ConsumerRebalanceListener javadocs
  • Scala 特征kafka.security.auth.Authorizer已弃用并替换为新的 Java APIorg.apache.kafka.server.authorizer.Authorizer.鉴权方实现类kafka.security.auth.SimpleAclAuthorizer也被弃用并替换为新的 实现kafka.security.authorizer.AclAuthorizer.AclAuthorizer使用功能 受新 API 支持,以改进授权日志记录,并与SimpleAclAuthorizer. 有关更多详细信息,请参阅 KIP-504

从 0.8.x、0.9.x、0.10.0.x、0.10.1.x、0.10.2.x、0.11.0.x、1.0.x、1.1.x、2.0.x 或 2.1.x 或 2.2.x 升级到 2.3.0

如果您从 2.1.x 之前的版本升级,请参阅下面的说明,了解用于存储使用者偏移量的架构的更改。 将 inter.broker.protocol.version 更改为最新版本后,将无法降级到 2.1 之前的版本。

对于滚动升级:

  1. 更新所有代理上的 server.properties 并添加以下属性。CURRENT_KAFKA_VERSION 是指您 正在升级。CURRENT_MESSAGE_FORMAT_VERSION 是指当前正在使用的消息格式版本。如果您之前有 覆盖了 Message Format version,则应保留其当前值。或者,如果您要从之前的版本升级 设置为 0.11.0.x,则CURRENT_MESSAGE_FORMAT_VERSION应设置为 MATCH CURRENT_KAFKA_VERSION。
    • inter.broker.protocol.version=CURRENT_KAFKA_VERSION(例如 0.8.2、0.9.0、0.10.0、0.10.1、0.10.2、0.11.0、1.0、1.1)。
    • log.message.format.version=CURRENT_MESSAGE_FORMAT_VERSION (查看潜在的性能影响) 有关此配置的作用的详细信息。
    如果要从 0.11.0.x、1.0.x、1.1.x、2.0.x 或 2.1.x 升级,并且尚未覆盖消息格式,则只需覆盖 Inter-Broker 协议版本。
    • inter.broker.protocol.version=CURRENT_KAFKA_VERSION (0.11.0, 1.0, 1.1, 2.0, 2.1, 2.2).
  2. 一次升级一个代理:关闭代理,更新代码,然后重新启动它。完成此作后, Broker 将运行最新版本,您可以验证集群的行为和性能是否符合预期。 如果有任何问题,此时仍然可以降级。
  3. 验证集群的行为和性能后,通过编辑来增加协议版本inter.broker.protocol.version并将其设置为 2.3。
  4. 逐个重启 broker,新协议版本才能生效。一旦代理开始使用最新的 协议版本,则无法再将集群降级到旧版本。
  5. 如果您已按照上述说明覆盖了消息格式版本,则需要再执行一次滚动重启,以 将其升级到最新版本。所有(或大多数)消费者都升级到 0.11.0 或更高版本后, 将每个代理上的 log.message.format.version 更改为 2.3,然后逐个重新启动它们。请注意,较旧的 Scala 客户端 不再维护,不支持 0.11 中引入的 message 格式,从而避免转换成本 (或利用 Exactly once 语义)、 必须使用较新的 Java 客户端。
2.3.0 中的显著变化
  • 我们正在为 Kafka Connect 引入一种基于增量协作再平衡的新再平衡协议。 新协议不要求在 Connect 工作程序之间的再平衡阶段停止所有任务。相反,只需要交换的任务 在 worker 之间停止,并在后续 rebalance 中启动。从 2.3.0 开始,新的 Connect 协议默认启用。 有关其工作原理以及如何启用预先再平衡的旧行为的更多详细信息,请查看增量协作再平衡设计
  • 我们正在向消费者用户引入静态成员资格。此功能可减少正常应用程序升级或滚动退回期间不必要的重新平衡。 有关如何使用它的更多详细信息,请查看静态成员资格设计
  • Kafka Streams DSL 会切换其使用的存储类型。虽然此更改主要对用户透明,但在某些极端情况下可能需要更改代码。 有关更多详细信息,请参阅 Kafka Streams 升级部分
  • Kafka Streams 2.3.0 需要 0.11 格式或更高版本的消息格式,并且不适用于较旧的消息格式。

从 0.8.x、0.9.x、0.10.0.x、0.10.1.x、0.10.2.x、0.11.0.x、1.0.x、1.1.x、2.0.x 或 2.1.x 升级到 2.2.0

如果您从 2.1.x 之前的版本升级,请参阅下面的说明,了解用于存储使用者偏移量的架构的更改。 将 inter.broker.protocol.version 更改为最新版本后,将无法降级到 2.1 之前的版本。

对于滚动升级:

  1. 更新所有代理上的 server.properties 并添加以下属性。CURRENT_KAFKA_VERSION 是指您 正在升级。CURRENT_MESSAGE_FORMAT_VERSION 是指当前正在使用的消息格式版本。如果您之前有 覆盖了 Message Format version,则应保留其当前值。或者,如果您要从之前的版本升级 设置为 0.11.0.x,则CURRENT_MESSAGE_FORMAT_VERSION应设置为 MATCH CURRENT_KAFKA_VERSION。
    • inter.broker.protocol.version=CURRENT_KAFKA_VERSION(例如 0.8.2、0.9.0、0.10.0、0.10.1、0.10.2、0.11.0、1.0、1.1)。
    • log.message.format.version=CURRENT_MESSAGE_FORMAT_VERSION (查看潜在的性能影响) 有关此配置的作用的详细信息。
    如果要从 0.11.0.x、1.0.x、1.1.x 或 2.0.x 升级,并且尚未覆盖消息格式,则只需覆盖 Inter-Broker 协议版本。
    • inter.broker.protocol.version=CURRENT_KAFKA_VERSION (0.11.0, 1.0, 1.1, 2.0).
  2. 一次升级一个代理:关闭代理,更新代码,然后重新启动它。完成此作后, Broker 将运行最新版本,您可以验证集群的行为和性能是否符合预期。 如果有任何问题,此时仍然可以降级。
  3. 验证集群的行为和性能后,通过编辑来增加协议版本inter.broker.protocol.version并将其设置为 2.2。
  4. 逐个重启 broker,新协议版本才能生效。一旦代理开始使用最新的 协议版本,则无法再将集群降级到旧版本。
  5. 如果您已按照上述说明覆盖了消息格式版本,则需要再执行一次滚动重启,以 将其升级到最新版本。所有(或大多数)消费者都升级到 0.11.0 或更高版本后, 将 log.message.format.version 修改为 2.2,然后逐个重启。请注意,较旧的 Scala 客户端 不再维护,不支持 0.11 中引入的 message 格式,从而避免转换成本 (或利用 Exactly once 语义)、 必须使用较新的 Java 客户端。
2.2.1 中的显著更改
  • Kafka Streams 2.2.1 需要 0.11 或更高的消息格式,并且不适用于较旧的消息格式。
2.2.0 中的显著变化
  • 默认消费组 ID 由空字符串 () 改为""null.使用新的默认 Group ID 的 Consumer 将无法订阅 Topic, 以及 fetch 或 commit offsets。作为使用者组 ID 的空字符串已弃用,但在将来的主要版本之前将受支持。依赖空字符串组 ID 的旧客户端现在将 必须显式地将其作为其 consumer 配置的一部分提供。有关更多信息,请参阅 KIP-289
  • bin/kafka-topics.sh命令行工具现在能够直接连接到代理--bootstrap-server而不是 Zookeeper。旧的--zookeeper选项目前仍然可用。请阅读 KIP-377 了解更多信息。
  • Kafka Streams 依赖于需要 MacOS 10.13 或更高版本的较新版本的 RocksDB。

从 0.8.x、0.9.x、0.10.0.x、0.10.1.x、0.10.2.x、0.11.0.x、1.0.x、1.1.x 或 2.0.0 升级到 2.1.0

请注意,2.1.x 包含对用于存储使用者偏移量的内部架构的更改。升级后 complete,则无法降级到以前的版本。有关更多详细信息,请参阅下面的滚动升级说明。

对于滚动升级:

  1. 更新所有代理上的 server.properties 并添加以下属性。CURRENT_KAFKA_VERSION 是指您 正在升级。CURRENT_MESSAGE_FORMAT_VERSION 是指当前正在使用的消息格式版本。如果您之前有 覆盖了 Message Format version,则应保留其当前值。或者,如果您要从之前的版本升级 设置为 0.11.0.x,则CURRENT_MESSAGE_FORMAT_VERSION应设置为 MATCH CURRENT_KAFKA_VERSION。
    • inter.broker.protocol.version=CURRENT_KAFKA_VERSION(例如 0.8.2、0.9.0、0.10.0、0.10.1、0.10.2、0.11.0、1.0、1.1)。
    • log.message.format.version=CURRENT_MESSAGE_FORMAT_VERSION (查看潜在的性能影响) 有关此配置的作用的详细信息。
    如果要从 0.11.0.x、1.0.x、1.1.x 或 2.0.x 升级,并且尚未覆盖消息格式,则只需覆盖 Inter-Broker 协议版本。
    • inter.broker.protocol.version=CURRENT_KAFKA_VERSION (0.11.0, 1.0, 1.1, 2.0).
  2. 一次升级一个代理:关闭代理,更新代码,然后重新启动它。完成此作后, Broker 将运行最新版本,您可以验证集群的行为和性能是否符合预期。 如果有任何问题,此时仍然可以降级。
  3. 验证集群的行为和性能后,通过编辑来增加协议版本inter.broker.protocol.version并将其设置为 2.1。
  4. 逐个重启 broker,新协议版本才能生效。一旦代理开始使用最新的 协议版本,则无法再将集群降级到旧版本。
  5. 如果您已按照上述说明覆盖了消息格式版本,则需要再执行一次滚动重启,以 将其升级到最新版本。所有(或大多数)消费者都升级到 0.11.0 或更高版本后, 将每个代理上的 log.message.format.version 更改为 2.1,然后逐个重新启动它们。请注意,较旧的 Scala 客户端 不再维护,不支持 0.11 中引入的 message 格式,从而避免转换成本 (或利用 Exactly once 语义)、 必须使用较新的 Java 客户端。

其他升级说明:

  1. 此版本中的偏移过期语义略有变化。根据新的语义,组中分区的偏移量将 当组订阅了相应的主题并且仍然处于活动状态(具有活跃的使用者)时,不会被删除。如果 group 变为 empty 在默认偏移保持期(或代理设置的保持期)过后,将删除其所有偏移量(除非该组变为 再次激活)。默认情况下,与不使用 Kafka 组管理的独立(简单)消费者关联的偏移量将被删除 offset 保留期(或 Broker 设置的保留期)自上次提交以来已过去。
  2. 控制台使用者的enable.auto.commitproperty (当 nogroup.id现在设置为false. 这是为了避免污染使用者协调器缓存,因为自动生成的组不太可能被其他使用者使用。
  3. 生产者retriesconfig 已更改为Integer.MAX_VALUE,正如我们介绍delivery.timeout.msKIP-91 中, 它为发送记录和从 broker 接收确认之间的总时间设置上限。默认情况下, 传输超时设置为 2 分钟。
  4. 默认情况下,MirrorMaker 现在会覆盖delivery.timeout.msInteger.MAX_VALUE什么时候 配置 Producer。如果您已覆盖retries为了更快地失败, 您将需要重写delivery.timeout.ms.
  5. ListGroupAPI 现在期望作为推荐的替代方案Describe Group对用户应能够列出的组的访问权限。 即使旧的Describe Cluster为了向后兼容,仍然支持 access,不建议将其用于此 API。
  6. KIP-336 弃用了 ExtendedSerializer 和 ExtendedDeserializer 接口以及 传播 Serializer 和 Deserializer 的用法。ExtendedSerializer 和 ExtendedDeserializer 随 KIP-82 一起引入,用于为序列化器和反序列化程序提供记录标头 以 Java 7 兼容的方式。现在,我们整合了这些接口,因为 Java 7 支持已经被放弃了。
2.1.0 中的显著更改
  • Jetty 已升级到 9.4.12,默认情况下不包括 TLS_RSA_* 密码,因为它们不支持转发 保密性,请参阅 https://github.com/eclipse/jetty.project/issues/2807 了解更多信息。
  • 在以下情况下,控制器会自动启用 Unclean leader 选举unclean.leader.election.enableconfig 使用按主题的 config override 动态更新。
  • AdminClient添加了一个方法AdminClient#metrics().现在,任何使用AdminClient可以获取更多信息 和 insight 通过查看从AdminClient.了解更多信息 参见 KIP-324
  • Kafka 现在支持从 KIP-110 开始的 Zstandard 压缩。 您必须升级代理和客户端才能使用它。2.1.0 之前的使用者将无法从使用 Z标准压缩,因此在所有下游使用者都升级之前,您不应为主题启用它。有关更多详细信息,请参阅 KIP。

从 0.8.x、0.9.x、0.10.0.x、0.10.1.x、0.10.2.x、0.11.0.x、1.0.x 或 1.1.x 升级到 2.0.0

Kafka 2.0.0 引入了有线协议更改。通过遵循下面推荐的滚动升级计划, 您保证在升级期间不会出现停机时间。但是,请在升级之前查看 2.0.0 中的显著更改

对于滚动升级:

  1. 更新所有代理上的 server.properties 并添加以下属性。CURRENT_KAFKA_VERSION 是指您 正在升级。CURRENT_MESSAGE_FORMAT_VERSION 是指当前正在使用的消息格式版本。如果您之前有 覆盖了 Message Format version,则应保留其当前值。或者,如果您要从之前的版本升级 设置为 0.11.0.x,则CURRENT_MESSAGE_FORMAT_VERSION应设置为 MATCH CURRENT_KAFKA_VERSION。
    • inter.broker.protocol.version=CURRENT_KAFKA_VERSION(例如 0.8.2、0.9.0、0.10.0、0.10.1、0.10.2、0.11.0、1.0、1.1)。
    • log.message.format.version=CURRENT_MESSAGE_FORMAT_VERSION (查看潜在的性能影响) 有关此配置的作用的详细信息。
    如果要从 0.11.0.x、1.0.x 或 1.1.x 升级,并且尚未覆盖消息格式,则只需覆盖 Inter-Broker 协议格式。
    • inter.broker.protocol.version=CURRENT_KAFKA_VERSION (0.11.0, 1.0, 1.1).
  2. 一次升级一个代理:关闭代理,更新代码,然后重新启动它。
  3. 升级整个集群后,通过编辑来增加协议版本inter.broker.protocol.version并将其设置为 2.0。
  4. 逐个重启 broker,新协议版本才能生效。
  5. 如果您已按照上述说明覆盖了消息格式版本,则需要再执行一次滚动重启,以 将其升级到最新版本。所有(或大多数)消费者都升级到 0.11.0 或更高版本后, 将 log.message.format.version 修改为 2.0,然后逐个重启。请注意,较旧的 Scala 使用者 不支持 0.11 中引入的新消息格式,因此为了避免下转换(或 利用 Exactly Once 语义),则必须使用较新的 Java 使用者。

其他升级说明:

  1. 如果您愿意接受停机,您可以简单地关闭所有代理,更新代码并重新启动它们。他们将开始 默认使用新协议。
  2. 升级 broker 后,可以随时更新协议版本并重新启动。它不必紧随其后。 消息格式版本也是如此。
  3. 如果您在 Kafka Streams 代码中使用 Java8 方法引用,则可能需要更新代码以解决方法歧义。 仅热交换 jar 文件可能不起作用。
  4. 不应将 ACL 添加到带前缀的资源中, (在 KIP-290 中添加), 直到集群中的所有代理都已更新。

    注意:如果集群再次降级,则即使在集群完全升级后,添加到集群的任何带前缀的 ACL 也将被忽略。

2.0.0 中的显著更改
  • KIP-186 将默认偏移保留时间从 1 天增加到 7 天。这使得在不经常提交的应用程序中 “丢失” 偏移量的可能性较小。它还会增加活动的偏移量集,因此会增加代理的内存使用量。请注意,控制台使用者目前默认启用偏移量提交,并且可能是大量偏移量的来源,此更改现在将保留 7 天,而不是 1 天。您可以通过设置 broker config 来保留现有行为offsets.retention.minutes到 1440 年。
  • 已删除对 Java 7 的支持,Java 8 现在是所需的最低版本。
  • 的默认值ssl.endpoint.identification.algorithm已更改为https执行主机名验证(否则可能会发生中间人攻击)。设置ssl.endpoint.identification.algorithm转换为空字符串以恢复之前的行为。
  • KAFKA-5674 延长了max.connections.per.ipminimum 到 0,因此允许对入站连接进行基于 IP 的筛选。
  • KIP-272 向指标添加了 API 版本标签kafka.network:type=RequestMetrics,name=RequestsPerSec,request={Produce|FetchConsumer|FetchFollower|...}. 此指标现在变为kafka.network:type=RequestMetrics,name=RequestsPerSec,request={Produce|FetchConsumer|FetchFollower|...},version={0|1|2|3|...}.这将影响 JMX 监控工具,这些工具不会自动聚合。要获取特定请求类型的总数,该工具需要为 更新为跨不同版本聚合。
  • KIP-225 更改了指标“records.lag”,以使用主题和分区的标签。名称格式为 “{topic}-{partition}.records-lag” 的原始版本已被删除。
  • 自 0.11.0.0 起已弃用的 Scala 使用者已被删除。Java 使用者是推荐的选项 从 0.10.0.0 开始。请注意,即使代理升级到 2.0.0,1.1.0(及更早版本)中的 Scala 使用者也将继续工作。
  • 自 0.10.0.0 起已弃用的 Scala 生产者已被删除。Java 生产者是推荐选项 从 0.9.0.0 开始。请注意,Java 生产者中默认分区程序的行为与默认分区程序不同 在 Scala 生产者中。迁移的用户应考虑配置一个保留先前行为的自定义分区程序。 请注意,即使代理升级到 2.0.0,1.1.0(及更早版本)中的 Scala 创建者也将继续工作。
  • MirrorMaker 和 ConsoleConsumer 不再支持 Scala 使用者,它们始终使用 Java 使用者。
  • ConsoleProducer 不再支持 Scala 生产者,它始终使用 Java 生产者。
  • 许多依赖于 Scala 客户端的已弃用工具已被删除:ReplayLogProducer、SimpleConsumerPerformance、SimpleConsumerShell、ExportZkOffsets、ImportZkOffsets、UpdateOffsetsInZK、VerifyConsumerRebalance。
  • 已弃用的 kafka.tools.ProducerPerformance 已被删除,请使用 org.apache.kafka.tools.ProducerPerformance。
  • 新的 Kafka Streams 配置参数upgrade.from添加了允许从旧版本进行滚动弹跳升级的功能。
  • KIP-284 通过将 Kafka Streams 重新分区主题的默认值设置为Long.MAX_VALUE.
  • 更新ProcessorStateManagerKafka Streams 中用于将状态存储注册到处理器拓扑的 API。有关更多详细信息,请阅读 Streams 升级指南
  • 在早期版本中,Connect 的工作程序配置需要internal.key.converterinternal.value.converter性能。 在 2.0 中,这些不再是必需的,并且默认为 JSON 转换器。 您可以安全地从 Connect 独立和分布式工作程序配置中删除这些属性:
    internal.key.converter=org.apache.kafka.connect.json.JsonConverter internal.key.converter.schemas.enable=false internal.value.converter=org.apache.kafka.connect.json.JsonConverter internal.value.converter.schemas.enable=false
  • KIP-266 添加了新的使用者配置default.api.timeout.ms指定要用于的默认超时KafkaConsumer可能阻止的 API。KIP 还为此类阻塞添加了重载 API 支持指定用于每个 API 的特定超时,而不是使用default.api.timeout.ms. 特别是,新的poll(Duration)添加了 API,它不会阻止动态分区分配。 旧的poll(long)API 已弃用,并将在未来版本中删除。还添加了重载 对于其他KafkaConsumer方法,如partitionsFor,listTopics,offsetsForTimes,beginningOffsets,endOffsetsclose那 take in aDuration.
  • 此外,作为 KIP-266 的一部分,默认值request.timeout.ms已更改为 30 秒。 之前的值略高于 5 分钟,以考虑再平衡所需的最长时间。 现在,我们将再平衡中的 JoinGroup 请求视为特殊情况,并使用从max.poll.interval.ms对于请求超时。所有其他请求类型都使用定义的超时 由request.timeout.ms
  • 内部方法kafka.admin.AdminClient.deleteRecordsBefore已被删除。鼓励用户迁移到org.apache.kafka.clients.admin.AdminClient.deleteRecords.
  • AclCommand 工具--producerconvenience 选项在给定主题上使用 KIP-277 更细粒度的 ACL。
  • KIP-176 去除 这--new-consumer所有基于消费者的工具的选项。此选项是多余的,因为新使用者会自动 如果定义了 --bootstrap-server,则使用。
  • KIP-290 增加了能力 在带前缀的资源上定义 ACL,例如任何以 'foo' 开头的主题。
  • KIP-283 改进了消息下转换 处理,这通常是一项占用大量内存的作。KIP 添加了一种机制,通过该机制,作将变得不那么占用内存 通过一次向下转换分区数据块,这有助于设置内存消耗的上限。随着这一改进,发生了FetchResponse协议行为,其中代理可能会在响应末尾发送具有无效偏移量的超大消息批次。 使用者客户端必须忽略此类超大消息,就像KafkaConsumer.

    KIP-283 还添加了新的主题和代理配置message.downconversion.enablelog.message.downconversion.enable分别 以控制是否启用下转换。禁用后,broker 不会执行任何下转换,而是发送UNSUPPORTED_VERSION错误。

  • 动态代理配置选项可以在启动代理之前使用 kafka-configs.sh 存储在 ZooKeeper 中。 此选项可用于避免在 server.properties 中存储明文密码,因为所有密码配置都可以加密存储在 ZooKeeper 中。
  • 现在,如果连接尝试失败,将重新解析 ZooKeeper 主机。但是,如果您的 ZooKeeper 主机名解析 添加到多个地址,并且其中一些地址无法访问,那么您可能需要增加连接超时zookeeper.connection.timeout.ms.
新协议版本
  • KIP-279:OffsetsForLeaderEpochResponse v1 引入了分区级别leader_epoch田。
  • KIP-219:提高因违反配额而受到限制的非集群作请求和响应的协议版本。
  • KIP-290:提高 ACL 创建、描述和删除请求和响应的协议版本。
升级 1.1 Kafka Streams 应用程序
  • 将 Streams 应用程序从 1.1 升级到 2.0 不需要升级代理。 Kafka Streams 2.0 应用程序可以连接到 2.0、1.1、1.0、0.11.0、0.10.2 和 0.10.1 代理(但无法连接到 0.10.0 代理)。
  • 请注意,在 2.0 中,我们删除了 1.0 之前已弃用的公共 API;利用这些已弃用的 API 的用户需要相应地更改代码。 有关更多详细信息,请参阅 2.0.0 中的 Streams API 更改

从 0.8.x、0.9.x、0.10.0.x、0.10.1.x、0.10.2.x、0.11.0.x 或 1.0.x 升级到 1.1.x

Kafka 1.1.0 引入了有线协议更改。通过遵循下面推荐的滚动升级计划, 您保证在升级期间不会出现停机时间。但是,请在升级之前查看 1.1.0 中的显著更改

对于滚动升级:

  1. 更新所有代理上的 server.properties 并添加以下属性。CURRENT_KAFKA_VERSION 是指您 正在升级。CURRENT_MESSAGE_FORMAT_VERSION 是指当前正在使用的消息格式版本。如果您之前有 覆盖了 Message Format version,则应保留其当前值。或者,如果您要从之前的版本升级 设置为 0.11.0.x,则CURRENT_MESSAGE_FORMAT_VERSION应设置为 MATCH CURRENT_KAFKA_VERSION。
    • inter.broker.protocol.version=CURRENT_KAFKA_VERSION (例如 0.8.2、0.9.0、0.10.0、0.10.1、0.10.2、0.11.0、1.0)。
    • log.message.format.version=CURRENT_MESSAGE_FORMAT_VERSION (查看潜在的性能影响) 有关此配置的作用的详细信息。
    如果要从 0.11.0.x 或 1.0.x 升级,并且尚未覆盖消息格式,则只需覆盖 Inter-Broker 协议格式。
    • inter.broker.protocol.version=CURRENT_KAFKA_VERSION(0.11.0 或 1.0)。
  2. 一次升级一个代理:关闭代理,更新代码,然后重新启动它。
  3. 升级整个集群后,通过编辑来增加协议版本inter.broker.protocol.version并将其设置为 1.1。
  4. 逐个重启 broker,新协议版本才能生效。
  5. 如果您已按照上述说明覆盖了消息格式版本,则需要再执行一次滚动重启,以 将其升级到最新版本。所有(或大多数)消费者都升级到 0.11.0 或更高版本后, 将 log.message.format.version 修改为 1.1,然后逐个重启。请注意,较旧的 Scala 使用者 不支持 0.11 中引入的新消息格式,因此为了避免下转换(或 利用 Exactly Once 语义),则必须使用较新的 Java 使用者。

其他升级说明:

  1. 如果您愿意接受停机,您可以简单地关闭所有代理,更新代码并重新启动它们。他们将开始 默认使用新协议。
  2. 升级 broker 后,可以随时更新协议版本并重新启动。它不必紧随其后。 消息格式版本也是如此。
  3. 如果您在 Kafka Streams 代码中使用 Java8 方法引用,则可能需要更新代码以解决方法歧义。 仅热交换 jar 文件可能不起作用。
1.1.1 中的显著变化
  • 新的 Kafka Streams 配置参数upgrade.from添加了允许从版本 0.10.0.x 进行滚动弹跳升级的功能
  • 请参阅 Kafka Streams 升级指南 有关此新配置的详细信息。
1.1.0 中的显著变化
  • Maven 中的 kafka 工件不再依赖于 log4j 或 slf4j-log4j12。与 kafka-clients 工件类似,用户 现在,可以通过包含适当的 SLF4j 模块(SLF4J-Log4J12、LOGBack 等)来选择日志记录后端。发布 tarball 仍然包括 log4j 和 slf4j-log4j12。
  • KIP-225 更改了指标“records.lag”,以使用主题和分区的标签。名称格式为“{topic}-{partition}.records-lag”的原始版本已弃用,并将在 2.0.0 中删除。
  • Kafka Streams 在防止代理通信错误方面更健壮。而不是停止 Kafka Streams 客户端并显示致命异常, Kafka Streams 会尝试自我修复并重新连接到集群。使用新的AdminClient您可以更好地控制频率 Kafka Streams 重试,并且可以配置精细超时(而不是旧版本中的硬编码重试)。
  • Kafka Streams 再平衡时间进一步缩短,使 Kafka Streams 的响应速度更快。
  • Kafka Connect 现在支持 Sink 和 Source Connector 中的消息标头,并通过简单的消息转换对其进行作。必须更改连接器才能显式使用它们。新的HeaderConverter用于控制 Headers 的 (反) 序列化方式,并且默认使用新的 “SimpleHeaderConverter” 来使用值的字符串表示形式。
  • 如果启用了 print-data-log,kafka.tools.DumpLogSegments 现在会自动设置 deep-iteration 选项 显式或隐式地由于任何其他选项(如 decoder)而显式或隐式地使用。
新协议版本
  • KIP-226 引入了 DescribeConfigs 请求/响应 v1。
  • KIP-227 引入了 Fetch Request/Response v7。
升级 1.0 Kafka Streams 应用程序
  • 将 Streams 应用程序从 1.0 升级到 1.1 不需要升级代理。 Kafka Streams 1.1 应用程序可以连接到 1.0、0.11.0、0.10.2 和 0.10.1 代理(但无法连接到 0.10.0 代理)。
  • 有关更多详细信息,请参阅 1.1.0 中的 Streams API 更改

从 0.8.x、0.9.x、0.10.0.x、0.10.1.x、0.10.2.x 或 0.11.0.x 升级到 1.0.0

Kafka 1.0.0 引入了有线协议更改。通过遵循下面推荐的滚动升级计划, 您保证在升级期间不会出现停机时间。但是,请在升级之前查看 1.0.0 中的显著更改

对于滚动升级:

  1. 更新所有代理上的 server.properties 并添加以下属性。CURRENT_KAFKA_VERSION 是指您 正在升级。CURRENT_MESSAGE_FORMAT_VERSION 是指当前正在使用的消息格式版本。如果您之前有 覆盖了 Message Format version,则应保留其当前值。或者,如果您要从之前的版本升级 设置为 0.11.0.x,则CURRENT_MESSAGE_FORMAT_VERSION应设置为 MATCH CURRENT_KAFKA_VERSION。
    • inter.broker.protocol.version=CURRENT_KAFKA_VERSION (例如 0.8.2、0.9.0、0.10.0、0.10.1、0.10.2、0.11.0)。
    • log.message.format.version=CURRENT_MESSAGE_FORMAT_VERSION (查看潜在的性能影响) 有关此配置的作用的详细信息。
    如果要从 0.11.0.x 升级,并且尚未覆盖消息格式,则必须将 消息格式版本和 Inter-Broker 协议版本都设置为 0.11.0。
    • inter.broker.protocol.version=0.11.0
    • log.message.format.version=0.11.0
  2. 一次升级一个代理:关闭代理,更新代码,然后重新启动它。
  3. 升级整个集群后,通过编辑来增加协议版本inter.broker.protocol.version并将其设置为 1.0。
  4. 逐个重启 broker,新协议版本才能生效。
  5. 如果您已按照上述说明覆盖了消息格式版本,则需要再执行一次滚动重启,以 将其升级到最新版本。所有(或大多数)消费者都升级到 0.11.0 或更高版本后, 将每个 broker 上的 log.message.format.version 更改为 1.0,然后逐个重新启动它们。如果要从 0.11.0 且 log.message.format.version 设置为 0.11.0,则可以更新配置并跳过滚动重启。 请注意,较旧的 Scala consumer 不支持 0.11 中引入的新消息格式,因此为了避免 下转换的性能成本(或利用 Exactly Once 语义), 必须使用较新的 Java 使用者。

其他升级说明:

  1. 如果您愿意接受停机,您可以简单地关闭所有代理,更新代码并重新启动它们。他们将开始 默认使用新协议。
  2. 升级 broker 后,可以随时更新协议版本并重新启动。它不必紧随其后。 消息格式版本也是如此。
1.0.2 中的显著变化
  • 新的 Kafka Streams 配置参数upgrade.from添加了允许从版本 0.10.0.x 进行滚动弹跳升级的功能
  • 请参阅 Kafka Streams 升级指南 有关此新配置的详细信息。
1.0.1 中的显著变化
  • 恢复了 AdminClient 的 Options 类(例如 CreateTopicsOptions、DeleteTopicsOptions 等)与 0.11.0.x 的二进制(但不是源)兼容性在 1.0.0 中被无意中破坏了。
1.0.0 中的显著更改
  • 主题删除现在默认启用,因为该功能现在很稳定。希望 要保留之前的行为,应将 broker configdelete.topic.enablefalse.请记住,主题删除会删除数据,并且该作是不可逆的(即没有“取消删除”作)
  • 对于支持时间戳搜索的主题,如果找不到分区的偏移量,则该分区现在包含在搜索结果中,并带有 null 偏移值。以前,分区不包括在 map 中。 进行此更改是为了使搜索行为与不支持时间戳搜索的主题的情况一致。
  • 如果inter.broker.protocol.version是 1.0 或更高版本,代理现在将保持联机以提供副本 在实时日志目录上,即使存在离线日志目录。日志目录可能会因 IOException 而脱机 由硬件故障引起。用户需要监控每个代理的指标offlineLogDirectoryCount检查 是否有离线日志目录。
  • 添加了 KafkaStorageException,这是一个可重试的异常。KafkaStorageException 将在响应中转换为 NotLeaderForPartitionException 如果客户端的 FetchRequest 或 ProducerRequest 版本不支持 KafkaStorageException。
  • 在默认 JVM 设置中,-XX:+DisableExplicitGC 已替换为 -XX:+ExplicitGCInvokesConcurrent。这有助于 在某些情况下,避免在直接缓冲区分配本机内存期间出现内存不足异常。
  • 被覆盖的handleError方法实现已从 这kafka.api包:FetchRequest,GroupCoordinatorRequest,OffsetCommitRequest,OffsetFetchRequest,OffsetRequest,ProducerRequestTopicMetadataRequest. 这仅用于代理,但已不再使用,并且尚未维护实现。 为了二进制兼容性,保留了存根实现。
  • Java 客户端和工具现在接受任何字符串作为 client-id。
  • 已弃用的工具kafka-consumer-offset-checker.sh已被删除。用kafka-consumer-groups.sh以获取 Consumer Group 详细信息。
  • 现在,默认情况下,SimpleAclAuthorizer 会将访问拒绝记录到授权方日志中。
  • 身份验证失败现在作为 的子类之一报告给客户端AuthenticationException. 如果客户端连接身份验证失败,则不会执行重试。
  • 习惯SaslServerimplementations 可能会抛出SaslAuthenticationException提供错误 消息返回给客户端,指示身份验证失败的原因。实现者应注意不要包含 异常消息中不应泄露给未经身份验证的客户端的任何安全关键信息。
  • app-info向 JMX 注册以提供版本和提交 ID 的 mbean 将被弃用并替换为 提供这些属性的指标。
  • Kafka 指标现在可能包含非数字值。org.apache.kafka.common.Metric#value()已被弃用,并且 将返回0.0在这种情况下,为了最大限度地降低打破读取每个客户端值的用户的可能性 度量(通过MetricsReporter实现或通过调用metrics()方法)。org.apache.kafka.common.Metric#metricValue()可用于检索数字和非数字度量值。
  • 现在,每个 Kafka 速率指标都有一个相应的累积计数指标,其后缀为-total简化下游处理。例如records-consumed-rate具有相应的 名为records-consumed-total.
  • Mx4j 仅在 system 属性kafka_mx4jenable设置为true.由于逻辑 inversion 错误,它之前默认启用,如果kafka_mx4jenable设置为true.
  • 包装org.apache.kafka.common.security.auth在 clients 中,jar 已公开并添加到 JavaDocs 中。 以前位于此包中的 Internal 类已移至其他位置。
  • 当使用 Authorizer 并且用户对主题没有所需的权限时,代理 将TOPIC_AUTHORIZATION_FAILED错误返回给请求,而不管 broker 上是否存在主题。 如果用户具有所需的权限,但主题不存在,则 UNKNOWN_TOPIC_OR_PARTITION 将返回错误代码。
  • config/consumer.properties 文件已更新为使用新的 Consumer Config 属性。
新协议版本
  • KIP-112:LeaderAndIsrRequest v1 引入了分区级别is_new田。
  • KIP-112:UpdateMetadataRequest v4 引入了分区级别offline_replicas田。
  • KIP-112:MetadataResponse v5 引入了分区级offline_replicas田。
  • KIP-112:ProduceResponse v4 引入了 KafkaStorageException 的错误代码。
  • KIP-112:FetchResponse v6 引入了 KafkaStorageException 的错误代码。
  • KIP-152: 添加了 SaslAuthenticate 请求,以启用身份验证失败的报告。此请求将 如果 SaslHandshake 请求版本大于 0,则使用。
升级 0.11.0 Kafka Streams 应用程序
  • 将 Streams 应用程序从 0.11.0 升级到 1.0 不需要代理升级。 Kafka Streams 1.0 应用程序可以连接到 0.11.0、0.10.2 和 0.10.1 代理(但无法连接到 0.10.0 代理)。 但是,Kafka Streams 1.0 需要 0.10 或更新的消息格式,并且不适用于较旧的消息格式。
  • 如果您正在监控流指标,则需要对报告和监控代码中的指标名称进行一些更改,因为指标传感器层次结构已更改。
  • 有一些公共 API,包括ProcessorContext#schedule(),Processor#punctuate()KStreamBuilder,TopologyBuilder正在被新的 API 弃用。 我们建议您在升级时进行相应的代码更改,这些更改应该非常小,因为新 API 看起来非常相似。
  • 有关更多详细信息,请参阅 1.0.0 中的 Streams API 更改
升级 0.10.2 Kafka Streams 应用程序
  • 将 Streams 应用程序从 0.10.2 升级到 1.0 不需要升级代理。 Kafka Streams 1.0 应用程序可以连接到 1.0、0.11.0、0.10.2 和 0.10.1 代理(但无法连接到 0.10.0 代理)。
  • 如果您正在监控流指标,则需要对报告和监控代码中的指标名称进行一些更改,因为指标传感器层次结构已更改。
  • 有一些公共 API,包括ProcessorContext#schedule(),Processor#punctuate()KStreamBuilder,TopologyBuilder正在被新的 API 弃用。 我们建议您在升级时进行相应的代码更改,这些更改应该非常小,因为新 API 看起来非常相似。
  • 如果指定 customizedkey.serde,value.serdetimestamp.extractor在 Config 中,建议使用其替换的 configure 参数,因为这些配置已被弃用。
  • 有关更多详细信息,请参阅 0.11.0 中的 Streams API 更改
升级 0.10.1 Kafka Streams 应用程序
  • 将 Streams 应用程序从 0.10.1 升级到 1.0 不需要代理升级。 Kafka Streams 1.0 应用程序可以连接到 1.0、0.11.0、0.10.2 和 0.10.1 代理(但无法连接到 0.10.0 代理)。
  • 您需要重新编译代码。仅交换 Kafka Streams 库 jar 文件将不起作用,并且会破坏您的应用程序。
  • 如果您正在监控流指标,则需要对报告和监控代码中的指标名称进行一些更改,因为指标传感器层次结构已更改。
  • 有一些公共 API,包括ProcessorContext#schedule(),Processor#punctuate()KStreamBuilder,TopologyBuilder正在被新的 API 弃用。 我们建议您在升级时进行相应的代码更改,这些更改应该非常小,因为新 API 看起来非常相似。
  • 如果指定 customizedkey.serde,value.serdetimestamp.extractor在 Config 中,建议使用其替换的 configure 参数,因为这些配置已被弃用。
  • 如果您使用自定义(即用户实现的)时间戳提取器,则需要更新此代码,因为TimestampExtractor界面已更改。
  • 如果您注册自定义指标,则需要更新此代码,因为StreamsMetric界面已更改。
  • 有关更多详细信息,请参阅 1.0.0 中的 Streams API 更改0.11.0 中的 Streams API 更改0.10.2 中的 Streams API 更改
升级 0.10.0 Kafka Streams 应用程序
  • 将 Streams 应用程序从 0.10.0 升级到 1.0 确实需要升级代理,因为 Kafka Streams 1.0 应用程序只能连接到 0.1、0.11.0、0.10.2 或 0.10.1 代理。
  • 有一些 API 更改不向后兼容(有关更多详细信息,请参阅 1.0.0 中的 Streams API 更改0.11.0 中的 Streams API 更改0.10.2 中的 Streams API 更改0.10.1 中的 Streams API 更改)。 因此,您需要更新并重新编译您的代码。仅交换 Kafka Streams 库 jar 文件将不起作用,并且会破坏您的应用程序。
  • 从 0.10.0.x 升级到 1.0.2 需要使用 config 进行两次滚动退回upgrade.from="0.10.0"设置为第一个升级阶段 (参见 KIP-268)。 作为替代方案,也可以进行离线升级。
    • 为滚动退回准备应用程序实例,并确保 configupgrade.from设置为"0.10.0"新版本 0.11.0.3
    • 退回应用程序的每个实例一次
    • 为新部署的 1.0.2 应用程序实例准备第二轮滚动退回;确保删除 config 的值upgrade.from
    • 再次退回应用程序的每个实例以完成升级
  • 从 0.10.0.x 升级到 1.0.0 或 1.0.1 需要离线升级(不支持滚动弹跳升级)
    • 停止所有旧的 (0.10.0.x) 应用程序实例
    • 更新您的代码,并将旧代码和 JAR 文件替换为新代码和新 JAR 文件
    • 重新启动所有新的(1.0.0 或 1.0.1)应用程序实例

从 0.8.x、0.9.x、0.10.0.x、0.10.1.x 或 0.10.2.x 升级到 0.11.0.0

Kafka 0.11.0.0 引入了新的消息格式版本以及有线协议更改。通过遵循下面推荐的滚动升级计划, 您保证在升级期间不会出现停机时间。但是,请在升级之前查看 0.11.0.0 中的显著更改

从版本 0.10.2 开始,Java 客户端(生产者和使用者)已获得与旧代理通信的能力。版本 0.11.0 客户端可以与 0.10.0 或更高版本的代理通信。但是,如果您的代理版本低于 0.10.0,则必须升级 Kafka 集群。版本 0.11.0 代理支持 0.8.x 和更新的客户端。

对于滚动升级:

  1. 更新所有代理上的 server.properties 并添加以下属性。CURRENT_KAFKA_VERSION 是指您 正在升级。CURRENT_MESSAGE_FORMAT_VERSION 是指当前正在使用的消息格式版本。如果你有 之前未覆盖消息格式,则应将 CURRENT_MESSAGE_FORMAT_VERSION 设置为 MATCH CURRENT_KAFKA_VERSION。
    • inter.broker.protocol.version=CURRENT_KAFKA_VERSION (例如 0.8.2、0.9.0、0.10.0、0.10.1 或 0.10.2)。
    • log.message.format.version=CURRENT_MESSAGE_FORMAT_VERSION (查看潜在的性能影响) 有关此配置的作用的详细信息。
  2. 一次升级一个代理:关闭代理,更新代码,然后重新启动它。
  3. 升级整个集群后,通过编辑来增加协议版本inter.broker.protocol.version并将其设置为 0.11.0,但 不更改log.message.format.version还。
  4. 逐个重启 broker,新协议版本才能生效。
  5. 将所有(或大多数)使用者升级到 0.11.0 或更高版本后,将每个使用者的 log.message.format.version 更改为 0.11.0 broker 并逐个重新启动它们。请注意,较旧的 Scala 使用者不支持新的 message 格式,因此要避免 下转换的性能成本(或利用 Exactly once 语义), 必须使用新的 Java 使用者。

其他升级说明:

  1. 如果您愿意接受停机,您可以简单地关闭所有代理,更新代码并重新启动它们。他们将开始 默认使用新协议。
  2. 升级 broker 后,可以随时更新协议版本并重新启动。它不必紧随其后。 消息格式版本也是如此。
  3. 也可以使用主题管理工具 (bin/kafka-topics.sh) 更新全局设置之前log.message.format.version.
  4. 如果您从 0.10.0 之前的版本升级,则无需先将消息格式更新为 0.10.0 在切换到 0.11.0 之前。
升级 0.10.2 Kafka Streams 应用程序
  • 将 Streams 应用程序从 0.10.2 升级到 0.11.0 不需要升级代理。 Kafka Streams 0.11.0 应用程序可以连接到 0.11.0、0.10.2 和 0.10.1 代理(但无法连接到 0.10.0 代理)。
  • 如果指定 customizedkey.serde,value.serdetimestamp.extractor在 Config 中,建议使用其替换的 configure 参数,因为这些配置已被弃用。
  • 有关更多详细信息,请参阅 0.11.0 中的 Streams API 更改
升级 0.10.1 Kafka Streams 应用程序
  • 将 Streams 应用程序从 0.10.1 升级到 0.11.0 不需要代理升级。 Kafka Streams 0.11.0 应用程序可以连接到 0.11.0、0.10.2 和 0.10.1 代理(但无法连接到 0.10.0 代理)。
  • 您需要重新编译代码。仅交换 Kafka Streams 库 jar 文件将不起作用,并且会破坏您的应用程序。
  • 如果指定 customizedkey.serde,value.serdetimestamp.extractor在 Config 中,建议使用其替换的 configure 参数,因为这些配置已被弃用。
  • 如果您使用自定义(即用户实现的)时间戳提取器,则需要更新此代码,因为TimestampExtractor界面已更改。
  • 如果您注册自定义指标,则需要更新此代码,因为StreamsMetric界面已更改。
  • 有关更多详细信息,请参阅 0.11.0 中的 Streams API 更改0.10.2 中的 Streams API 更改
升级 0.10.0 Kafka Streams 应用程序
  • 将 Streams 应用程序从 0.10.0 升级到 0.11.0 确实需要升级代理,因为 Kafka Streams 0.11.0 应用程序只能连接到 0.11.0、0.10.2 或 0.10.1 代理。
  • 有几个 API 更改不向后兼容(有关详细信息,请参阅 0.11.0 中的 Streams API 更改0.10.2 中的 Streams API 更改0.10.1 中的 Streams API 更改)。 因此,您需要更新并重新编译您的代码。仅交换 Kafka Streams 库 jar 文件将不起作用,并且会破坏您的应用程序。
  • 从 0.10.0.x 升级到 0.11.0.3 需要使用 config 进行两次滚动退回upgrade.from="0.10.0"设置为第一个升级阶段 (参见 KIP-268)。 作为替代方案,也可以进行离线升级。
    • 为滚动退回准备应用程序实例,并确保 configupgrade.from设置为"0.10.0"新版本 0.11.0.3
    • 退回应用程序的每个实例一次
    • 为新部署的 0.11.0.3 应用程序实例准备第二轮滚动退回;确保删除 config 的值upgrade.from
    • 再次退回应用程序的每个实例以完成升级
  • 从 0.10.0.x 升级到 0.11.0.0、0.11.0.1 或 0.11.0.2 需要离线升级(不支持滚动退回升级)
    • 停止所有旧的 (0.10.0.x) 应用程序实例
    • 更新您的代码,并将旧代码和 JAR 文件替换为新代码和新 JAR 文件
    • 重新启动所有新的(0.11.0.0、0.11.0.1 或 0.11.0.2)应用程序实例
0.11.0.3 中的显著变化
  • 新的 Kafka Streams 配置参数upgrade.from添加了允许从版本 0.10.0.x 进行滚动弹跳升级的功能
  • 请参阅 Kafka Streams 升级指南 有关此新配置的详细信息。
0.11.0.0 中的显著变化
  • Unclean leader 选举现在默认处于禁用状态。新的默认值更倾向于持久性而不是可用性。希望 要保留之前的行为,应将 broker configunclean.leader.election.enabletrue.
  • 生产者配置block.on.buffer.full,metadata.fetch.timeout.mstimeout.ms一直 删除。它们最初在 Kafka 0.9.0.0 中被弃用。
  • offsets.topic.replication.factor现在,在自动创建主题时强制执行 Broker Config。内部 自动主题创建将失败并显示 GROUP_COORDINATOR_NOT_AVAILABLE 错误,直到集群大小满足此错误 复制因子要求。
  • 使用 snappy 压缩数据时,创建者和代理将使用压缩方案的默认块大小 (2 x 32 KB) 而不是 1 KB,以提高压缩率。有报道称,使用较小的 块大小比使用较大块大小压缩时大 50%。对于快速的情况,具有 5000 个 分区将需要额外的 315 MB JVM 堆。
  • 同样,当使用 gzip 压缩数据时,创建者和代理将使用 8 KB 而不是 1 KB 作为缓冲区大小。默认的 因为 gzip 过低(512 字节)。
  • 代理配置max.message.bytes现在适用于一批消息的总大小。 以前,该设置应用于批量压缩消息,或单独应用于非压缩消息。 消息批次可能仅包含一条消息,因此在大多数情况下, 单个消息仅因批处理格式的开销而减少。然而,也有一些微妙的含义 对于消息格式转换(有关更多详细信息,请参阅下文)。另请注意 虽然以前 broker 会确保每个 fetch 请求中至少返回一条消息(无论 total 和分区级 fetch 大小),相同的行为现在适用于一个消息批次。
  • GC 日志轮换默认开启,详见 KAFKA-3754。
  • 已删除 RecordMetadata、MetricName 和 Cluster 类的已弃用构造函数。
  • 通过新的 Headers 界面添加了用户标头支持,从而提供用户标头读取和写入访问权限。
  • ProducerRecord 和 ConsumerRecord 通过Headers headers()方法调用。
  • 引入了 ExtendedSerializer 和 ExtendedDeserializer 接口以支持 Headers 的序列化和反序列化。如果配置的 serializer 和 deserializer 不是上述 class,则 Headers 将被忽略。
  • 新配置group.initial.rebalance.delay.ms。 此配置指定GroupCoordinator将延迟初始 Consumer 再平衡。 再平衡将进一步延迟group.initial.rebalance.delay.ms当新成员加入群组时,最多可添加max.poll.interval.ms. 默认值为 3 秒。 在开发和测试期间,可能需要将此设置为 0,以免延迟测试执行时间。
  • org.apache.kafka.common.Cluster#partitionsForTopic,partitionsForNodeavailablePartitionsForTopic方法 将返回一个空列表,而不是null(这被认为是一种不好的做法),以防所需主题的元数据不存在。
  • Streams API 配置参数timestamp.extractor,key.serdevalue.serde已弃用,并且 替换为default.timestamp.extractor,default.key.serdedefault.value.serde分别。
  • 对于 Java 使用者的commitAsyncAPI,我们不再暴露底层 cause 当RetriableCommitFailedException传递给提交回调。有关更多详细信息,请参阅 KAFKA-5052
新协议版本
  • KIP-107:FetchRequest v5 引入了分区级log_start_offset田。
  • KIP-107:FetchResponse v5 引入了分区级别log_start_offset田。
  • KIP-82:ProduceRequest v3 引入了一个header在 Message Protocol 中,包含keyfield 和value田。
  • KIP-82:FetchResponse v5 引入了一个header在 Message Protocol 中,包含keyfield 和value田。
关于 Exactly Once 语义的说明

Kafka 0.11.0 包括对创建者中的幂等和事务功能的支持。幂等交付 确保在单个创建者的生命周期内,消息只传送到特定主题分区一次。 事务性传输允许创建者将数据发送到多个分区,以便所有消息都成功 已交付,或者都没有。这些功能共同在 Kafka 中实现了“恰好一次语义”。有关这些的更多详细信息 用户指南中提供了这些功能,但下面我们添加了一些关于在升级后的集群中启用这些功能的具体说明。 请注意,启用 EoS 不是必需的,如果未使用,则不会对代理的行为产生影响。

  1. 只有新的 Java 生产者和使用者支持 Exactly once 语义。
  2. 这些功能主要依赖于 0.11.0 消息格式。尝试使用它们 使用较旧的格式将导致不支持的版本错误。
  3. 交易状态存储在新的内部主题__transaction_state.此主题在 第一次尝试使用事务请求 API。与使用者偏移量主题类似,有几个设置 以控制主题的配置。例如transaction.state.log.min.isr控制 本主题。有关选项的完整列表,请参阅用户指南中的配置部分。
  4. 对于安全集群,事务性 API 需要新的 ACL,可以使用bin/kafka-acls.sh. 工具。
  5. Kafka 中的 EoS 引入了新的请求 API 并修改了几个现有的 API。有关详细信息,请参阅 KIP-98
关于 0.11.0 中新消息格式的说明

0.11.0 消息格式包括几项主要增强功能,以便为创建者提供更好的传递语义 (见 KIP-98) 和改进的复制容错能力 (参见 KIP-101)。 尽管新格式包含更多信息以使这些改进成为可能,但我们对批处理格式进行了大幅度的改进 更高效。只要每批的消息数大于 2,就可以降低总体开销。对于较小的 但是,可能会对性能产生较小的影响。请在此处查看我们的结果 新消息格式的初始性能分析。您还可以在 KIP-98 提案中找到有关消息格式的更多详细信息。

新消息格式的一个显著区别是,即使是未压缩的消息也作为单个批处理一起存储。 这对代理配置有一些影响max.message.bytes,这会限制单个批次的大小。第一 如果较旧的客户端使用旧格式向主题分区生成消息,并且消息单独小于max.message.bytes,在上转换过程中将它们合并为单个批次后,代理可能仍会拒绝它们。 通常,当单个消息的聚合大小大于max.message.bytes.有类似的 对从新格式向下转换的读取消息的老年使用者的影响:如果 fetch 大小未设置为至少与max.message.bytes,即使单个未压缩的消息较小,使用者也可能无法取得进展 比配置的 fetch 大小。此行为不会影响 0.10.1.0 及更高版本的 Java 客户端,因为它使用更新的 fetch 协议 这可确保至少可以返回一条消息,即使它超过了 fetch 大小。要解决这些问题,您应该确保 1) 生产者的批量大小未设置为大于max.message.bytes,以及 2) 消费者的 fetch size 设置为 最小max.message.bytes.

关于升级到 0.10.0 消息格式对性能影响的大多数讨论仍然与 0.11.0 升级相关。这主要影响自 “零拷贝” 传输以来未使用 TLS 保护的集群 在这种情况下已经不可能了。为了避免下转换的成本,您应该确保 Consumer 应用程序 已升级到最新的 0.11.0 客户端。值得注意的是,由于旧的 consumer 在 0.11.0.0 中已被弃用,因此它不支持 新的消息格式。您必须升级才能使用新使用者才能使用新的消息格式,而无需进行向下转换。 请注意,0.11.0 消费者支持向后兼容 0.10.0 代理及更高版本,因此可以升级 客户先到经纪人。

从 0.8.x、0.9.x、0.10.0.x 或 0.10.1.x 升级到 0.10.2.0

0.10.2.0 的有线协议发生了变化。通过遵循下面建议的滚动升级计划,您可以保证升级期间不会出现停机时间。 但是,请在升级之前查看 0.10.2.0 中的显著变化

从版本 0.10.2 开始,Java 客户端(生产者和使用者)已获得与旧代理通信的能力。版本 0.10.2 客户端可以与 0.10.0 或更高版本的代理通信。但是,如果您的代理版本低于 0.10.0,则必须升级 Kafka 集群。版本 0.10.2 代理支持 0.8.x 和更新的客户端。

对于滚动升级:

  1. 更新所有代理上的 server.properties 文件并添加以下属性:
    • inter.broker.protocol.version=CURRENT_KAFKA_VERSION (例如 0.8.2、0.9.0、0.10.0 或 0.10.1)。
    • log.message.format.version=CURRENT_KAFKA_VERSION (有关此配置的作用的详细信息,请参阅升级后的潜在性能影响
  2. 一次升级一个代理:关闭代理,更新代码,然后重新启动它。
  3. 升级整个集群后,通过编辑 inter.broker.protocol.version 并将其设置为 0.10.2 来增加协议版本。
  4. 如果您以前的消息格式为 0.10.0,请将 log.message.format.version 更改为 0.10.2(这是一个无作,因为 0.10.0、0.10.1 和 0.10.2 的消息格式相同)。 如果您以前的消息格式版本低于 0.10.0,请不要更改 log.message.format.version - 只有在所有使用者都升级到 0.10.0.0 或更高版本后,此参数才应更改。
  5. 逐个重启 broker,新协议版本才能生效。
  6. 如果此时 log.message.format.version 仍然低于 0.10.0,请等待所有消费者都升级到 0.10.0 或更高版本, 然后将每个代理上的 log.message.format.version 更改为 0.10.2,并逐个重新启动它们。

注意:如果您愿意接受停机,您可以简单地关闭所有代理,更新代码并启动所有代理。默认情况下,他们将从新协议开始。

注意:升级 broker 后,可以随时更新协议版本并重新启动。它不必紧随其后。

升级 0.10.1 Kafka Streams 应用程序
  • 将 Streams 应用程序从 0.10.1 升级到 0.10.2 不需要升级代理。 Kafka Streams 0.10.2 应用程序可以连接到 0.10.2 和 0.10.1 代理(但无法连接到 0.10.0 代理)。
  • 您需要重新编译代码。仅交换 Kafka Streams 库 jar 文件将不起作用,并且会破坏您的应用程序。
  • 如果您使用自定义(即用户实现的)时间戳提取器,则需要更新此代码,因为TimestampExtractor界面已更改。
  • 如果您注册自定义指标,则需要更新此代码,因为StreamsMetric界面已更改。
  • 有关更多详细信息,请参阅 0.10.2 中的 Streams API 更改
升级 0.10.0 Kafka Streams 应用程序
  • 将 Streams 应用程序从 0.10.0 升级到 0.10.2 确实需要升级代理,因为 Kafka Streams 0.10.2 应用程序只能连接到 0.10.2 或 0.10.1 代理。
  • 有一些 API 更改,不向后兼容(有关更多详细信息,请参阅 0.10.2 中的 Streams API 更改)。 因此,您需要更新并重新编译您的代码。仅交换 Kafka Streams 库 jar 文件将不起作用,并且会破坏您的应用程序。
  • 从 0.10.0.x 升级到 0.10.2.2 需要两次带有 config 的滚动退回upgrade.from="0.10.0"设置为第一个升级阶段 (参见 KIP-268)。 作为替代方案,也可以进行离线升级。
    • 为滚动退回准备应用程序实例,并确保 configupgrade.from设置为"0.10.0"新版本 0.10.2.2
    • 退回应用程序的每个实例一次
    • 为新部署的 0.10.2.2 应用程序实例准备第二轮滚动退回;确保删除 config 的值upgrade.from
    • 再次退回应用程序的每个实例以完成升级
  • 从 0.10.0.x 升级到 0.10.2.0 或 0.10.2.1 需要离线升级(不支持滚动退回升级)
    • 停止所有旧的 (0.10.0.x) 应用程序实例
    • 更新您的代码,并将旧代码和 JAR 文件替换为新代码和新 JAR 文件
    • 重新启动所有新的(0.10.2.0 或 0.10.2.1)应用程序实例
0.10.2.2 中的显著变化
  • 新的配置参数upgrade.from添加了允许从版本 0.10.0.x 进行滚动弹跳升级的功能
0.10.2.1 中的显著变化
  • 更改了 StreamsConfig 类的两个配置的默认值,以提高 Kafka Streams 应用程序的弹性。内部 Kafka Streams 创建者retries默认值已从 0 更改为 10。内部 Kafka Streams 使用者max.poll.interval.ms默认值已从 300000 更改为Integer.MAX_VALUE.
0.10.2.0 中的显著变化
  • Java 客户端(生产者和使用者)已经获得了与旧代理通信的能力。版本 0.10.2 客户端 可以与版本 0.10.0 或更高版本的代理通信。请注意,某些功能在较旧的经纪人时不可用或受到限制 使用。
  • Java 使用者上的几个方法现在可能会抛出InterruptException如果调用线程被中断。 请参阅KafkaConsumerJavadoc 中提供了有关此更改的更深入说明。
  • Java 使用者现在可以正常关闭。默认情况下,使用者最多等待 30 秒才能完成待处理请求。 已向KafkaConsumer以控制最长等待时间。
  • 可以通过 --whitelist 选项将多个以逗号分隔的正则表达式传递给具有新 Java 使用者的 MirrorMaker。这 使行为与使用旧 Scala 使用者时的 MirrorMaker 一致。
  • 将 Streams 应用程序从 0.10.1 升级到 0.10.2 不需要升级代理。 Kafka Streams 0.10.2 应用程序可以连接到 0.10.2 和 0.10.1 代理(但无法连接到 0.10.0 代理)。
  • Zookeeper 依赖项已从 Streams API 中删除。Streams API 现在使用 Kafka 协议来管理内部主题,而不是 直接修改 Zookeeper。这消除了直接访问 Zookeeper 和“StreamsConfig.ZOOKEEPER_CONFIG”的权限 不应再在 Streams 应用程序中设置。如果 Kafka 集群是安全的,则 Streams 应用程序必须具有创建新主题所需的安全权限。
  • 添加了几个新字段,包括 “security.protocol”、“connections.max.idle.ms”、“retry.backoff.ms”、“reconnect.backoff.ms” 和 “request.timeout.ms” StreamsConfig 类。用户应注意默认值,并根据需要进行设置。更多细节请参考 3.5 Kafka Streams 配置
新协议版本
  • KIP-88:如果topicsarray 设置为null.
  • KIP-88:OffsetFetchResponse v2 引入了顶级error_code田。
  • KIP-103:UpdateMetadataRequest v3 引入了listener_namefield 添加到end_points数组。
  • KIP-108:CreateTopicsRequest v1 引入了validate_only田。
  • KIP-108:CreateTopicsResponse v1 引入了error_messagefield 添加到topic_errors数组。

从 0.8.x、0.9.x 或 0.10.0.X 升级到 0.10.1.0

0.10.1.0 有有线协议更改。通过遵循下面建议的滚动升级计划,您可以保证升级期间不会出现停机时间。 但是,请在升级前注意 0.10.1.0 中的潜在重大更改
注意:由于引入了新协议,因此在升级客户端(即 0.10.1.x 客户端)之前升级 Kafka 集群非常重要 仅支持 0.10.1.x 或更高版本的 broker,而 0.10.1.x 的 broker 也支持较旧的客户端)。

对于滚动升级:

  1. 更新所有代理上的 server.properties 文件并添加以下属性:
    • inter.broker.protocol.version=CURRENT_KAFKA_VERSION (例如 0.8.2.0、0.9.0.0 或 0.10.0.0)。
    • log.message.format.version=CURRENT_KAFKA_VERSION (有关此配置的作用的详细信息,请参阅升级后的潜在性能影响
  2. 一次升级一个代理:关闭代理,更新代码,然后重新启动它。
  3. 升级整个集群后,通过编辑 inter.broker.protocol.version 并将其设置为 0.10.1.0 来增加协议版本。
  4. 如果您以前的消息格式是 0.10.0,请将 log.message.format.version 更改为 0.10.1(这是一个无作,因为 0.10.0 和 0.10.1 的消息格式相同)。 如果您以前的消息格式版本低于 0.10.0,请不要更改 log.message.format.version - 只有在所有使用者都升级到 0.10.0.0 或更高版本后,此参数才应更改。
  5. 逐个重启 broker,新协议版本才能生效。
  6. 如果此时 log.message.format.version 仍然低于 0.10.0,请等待所有消费者都升级到 0.10.0 或更高版本, 然后将每个代理上的 log.message.format.version 更改为 0.10.1,并逐个重新启动它们。

注意:如果您愿意接受停机,您可以简单地关闭所有代理,更新代码并启动所有代理。默认情况下,他们将从新协议开始。

注意:升级 broker 后,可以随时更新协议版本并重新启动。它不必紧随其后。

0.10.1.2 中的显著变化
  • 新的配置参数upgrade.from添加了允许从版本 0.10.0.x 进行滚动弹跳升级的功能
0.10.1.0 中的潜在重大变化
  • 日志保留时间不再基于日志分段的上次修改时间。相反,它将基于日志分段中消息的最大时间戳。
  • 日志滚动时间不再取决于日志分段创建时间。相反,它现在基于消息中的时间戳。更具体地说。如果分段中第一条消息的时间戳为 T,则当新消息的时间戳大于或等于 T + log.roll.ms 时,将转出日志
  • 由于为每个分段添加了时间索引文件,0.10.0 的打开文件处理程序将增加 ~33%。
  • time index 和 offset index 共享相同的索引大小配置。由于每个 time 索引条目的大小是偏移索引条目大小的 1.5 倍。用户可能需要增加 log.index.size.max.bytes 以避免潜在的频繁日志滚动。
  • 由于索引文件数量的增加,在一些日志段量较大的 broker 上(例如 >15K),broker 启动期间的日志加载过程可能会更长。根据我们的实验,将 num.recovery.threads.per.data.dir 设置为 1 可能会减少日志加载时间。
升级 0.10.0 Kafka Streams 应用程序
  • 将 Streams 应用程序从 0.10.0 升级到 0.10.1 确实需要升级代理,因为 Kafka Streams 0.10.1 应用程序只能连接到 0.10.1 代理。
  • 有一些 API 更改,不向后兼容(有关更多详细信息,请参阅 0.10.1 中的 Streams API 更改)。 因此,您需要更新并重新编译您的代码。仅交换 Kafka Streams 库 jar 文件将不起作用,并且会破坏您的应用程序。
  • 从 0.10.0.x 升级到 0.10.1.2 需要使用 config 进行两次滚动退回upgrade.from="0.10.0"设置为第一个升级阶段 (参见 KIP-268)。 作为替代方案,也可以进行离线升级。
    • 为滚动退回准备应用程序实例,并确保 configupgrade.from设置为"0.10.0"新版本 0.10.1.2
    • 退回应用程序的每个实例一次
    • 为新部署的 0.10.1.2 应用程序实例准备第二轮滚动退回;确保删除 config 的值upgrade.from
    • 再次退回应用程序的每个实例以完成升级
  • 从 0.10.0.x 升级到 0.10.1.0 或 0.10.1.1 需要离线升级(不支持滚动退回升级)
    • 停止所有旧的 (0.10.0.x) 应用程序实例
    • 更新您的代码,并将旧代码和 JAR 文件替换为新代码和新 JAR 文件
    • 重新启动所有新的(0.10.1.0 或 0.10.1.1)应用程序实例
0.10.1.0 中的显著变化
  • 新的 Java 使用者不再处于 beta 阶段,我们建议将其用于所有新的开发。旧的 Scala 使用者仍然受支持,但它们将在下一个版本中被弃用 ,并将在未来的主要版本中删除。
  • --new-consumer/--new.consumerswitch 不再需要将 MirrorMaker 和 Console Consumer 等工具与新使用者一起使用;一个简单 需要传递一个 Kafka 代理来连接,而不是 ZooKeeper ensemble。此外,已弃用 Console Consumer 与旧 Consumer 的使用,它将 在将来的主要版本中删除。
  • Kafka 集群现在可以通过集群 ID 进行唯一标识。当 broker 升级到 0.10.1.0 时,将自动生成它。集群 ID 可通过 kafka.server:type=KafkaServer,name=ClusterId 指标获得,它是元数据响应的一部分。序列化器、客户端拦截器和指标报告器可以通过实现 ClusterResourceListener 接口来接收集群 ID。
  • 已删除 BrokerState “RunningAsController” (值 4)。由于错误,代理在转换出此状态之前只会短暂地处于此状态,因此删除的影响应该很小。检测给定代理是否为控制器的推荐方法是通过 kafka.controller:type=KafkaController,name=ActiveControllerCount 指标。
  • 新的 Java Consumer 现在允许用户按时间戳搜索分区上的偏移量。
  • 新的 Java Consumer 现在支持从后台线程进行检测信号。有一个新的配置max.poll.interval.ms它控制使用者之前轮询调用之间的最长时间 将主动离开组(默认为 5 分钟)。配置的值request.timeout.ms(默认为 30 秒)必须始终小于max.poll.interval.ms(默认为 5 分钟)、 因为这是 JoinGroup 请求在使用者再平衡时可以在服务器上阻止的最长时间。 最后,默认值session.timeout.ms已下调至 10 秒,默认值max.poll.records已更改为 500。
  • 当使用 Authorizer 并且用户没有对主题的 Describe 授权时,代理将不会 longer 将 TOPIC_AUTHORIZATION_FAILED 错误返回给请求,因为这会泄露主题名称。相反,UNKNOWN_TOPIC_OR_PARTITION 将返回错误代码。这可能会导致在使用 producer 和 consumer 时出现意外的超时或延迟,因为 Kafka 客户端通常会在出现未知主题错误时自动重试。如果您 怀疑这可能正在发生。
  • 默认情况下,Fetch 响应具有大小限制(使用者为 50 MB,复制为 10 MB)。现有的每个分区限制也适用(使用者为 1 MB) 和复制)。请注意,这些限制都不是绝对最大值,如下一点所述。
  • 如果找到大于响应/分区大小限制的消息,使用者和副本可以继续前进。更具体地说,如果 FETCH 的第一个非空 partition 大于其中一个或两个限制,则仍将返回该消息。
  • 重载构造函数已添加到kafka.api.FetchRequestkafka.javaapi.FetchRequest以允许调用方指定 分区的顺序(因为 V3 中的顺序很重要)。以前存在的构造函数已被弃用,分区之前被随机排序 发送请求以避免匮乏问题。
新协议版本
  • ListOffsetRequest v1 支持基于时间戳的精确偏移搜索。
  • MetadataResponse v2 引入了一个新字段:“cluster_id”。
  • FetchRequest v3 支持限制响应大小(除了现有的每个分区限制之外),它会返回消息 大于限制(如果需要)才能取得进展,并且请求中的分区顺序现在很重要。
  • JoinGroup v1 引入了一个新字段:“rebalance_timeout”。

从 0.8.x 或 0.9.x 升级到 0.10.0.0

0.10.0.0 具有潜在的重大更改(请在升级前查看)以及升级后可能的性能影响。通过遵循下面建议的滚动升级计划,您可以保证在升级期间和之后不会出现停机时间,也不会对性能产生影响。
注意:由于引入了新协议,因此在升级客户端之前升级 Kafka 集群非常重要。

版本 0.9.0.0 的客户端说明: 由于 0.9.0.0 中引入的一个错误, 依赖于 ZooKeeper(旧的 Scala 高级 Consumer 和 MirrorMaker,如果与旧的 Consumer 一起使用)的客户端将不会 使用 0.10.0.x 代理。因此,在将 broker 升级到 0.9.0.1 之前,应将 0.9.0.0 客户端升级到 0.9.0.1 0.10.0.x 的对于 0.8.X 或 0.9.0.1 客户端,此步骤不是必需的。

对于滚动升级:

  1. 更新所有代理上的 server.properties 文件并添加以下属性:
    • inter.broker.protocol.version=CURRENT_KAFKA_VERSION (例如 0.8.2 或 0.9.0.0)。
    • log.message.format.version=CURRENT_KAFKA_VERSION (有关此配置的作用的详细信息,请参阅升级后的潜在性能影响
  2. 升级代理。这可以一次完成一个 broker作,只需将其关闭、更新代码并重新启动即可。
  3. 升级整个集群后,通过编辑 inter.broker.protocol.version 并将其设置为 0.10.0.0 来增加协议版本。注意:您暂时不应该接触 log.message.format.version - 只有在所有消费者都升级到 0.10.0.0 后,此参数才应该更改
  4. 逐个重启 broker,新协议版本才能生效。
  5. 将所有 Consumer 升级到 0.10.0 后,将每个 Broker 的 log.message.format.version 更改为 0.10.0,然后逐个重启。

注意:如果您愿意接受停机,您可以简单地关闭所有代理,更新代码并启动所有代理。默认情况下,他们将从新协议开始。

注意:升级 broker 后,可以随时更新协议版本并重新启动。它不必紧随其后。

升级到 0.10.0.0 后的潜在性能影响

0.10.0 中的消息格式包括一个新的 timestamp 字段,并对压缩的消息使用相对偏移量。 可以通过 server.properties 文件中的 log.message.format.version 配置磁盘消息格式。 默认的磁盘消息格式为 0.10.0。如果 Consumer 客户端使用的是 0.10.0.0 之前的版本,则它只能理解 0.10.0 之前的 message 格式。在这种情况下,代理能够将消息从 0.10.0 格式转换为早期格式 在将响应发送给旧版本上的使用者之前。但是,在这种情况下,代理不能使用零副本传输。 来自 Kafka 社区的有关性能影响的报告显示,CPU 利用率从升级前的 20% 上升到升级后的 100%,这迫使所有客户端立即升级以使性能恢复正常。 为避免在消费者升级到 0.10.0.0 之前进行此类消息转换,可以在将 broker 升级到 0.10.0.0 时将 log.message.format.version 设置为 0.8.2 或 0.9.0。这样,代理仍然可以使用 Zero Copy Transfer 将数据发送给老消费者。升级使用者后,可以在代理上将消息格式更改为 0.10.0,并享受包含新时间戳和改进压缩的新消息格式。 支持转换以确保兼容性,并且可用于支持一些尚未更新到较新客户端的应用程序,但即使在过度预置的集群上支持所有使用者流量也是不切实际的。因此,当代理已升级但大多数客户端尚未升级时,尽可能避免消息转换至关重要。

对于升级到 0.10.0.0 的客户端,性能不会受到影响。

注意:通过设置消息格式版本,可以证明所有现有消息都位于或低于该版本。 消息格式版本。否则,0.10.0.0 之前的使用者可能会中断。特别是,在消息格式 设置为 0.10.0,则不应将其改回以前的格式,因为它可能会破坏 0.10.0.0 之前版本的使用者。

注意:由于每条消息中引入了额外的时间戳,发送短消息的创建者可能会看到 由于开销增加,消息吞吐量下降。 同样,复制现在每条消息额外传输 8 个字节。 如果您的运行接近集群的网络容量,则可能会使网卡不堪重负 并查看由于过载而导致的故障和性能问题。

注意:如果您在 producer 上启用了压缩,您可能会注意到 producer 吞吐量降低和/或 在某些情况下,代理上的压缩率较低。接收压缩消息时,0.10.0 代理避免重新压缩消息,这通常可以减少延迟并提高吞吐量。在 但是,在某些情况下,这可能会减小生产者上的批处理大小,从而导致吞吐量变差。如果此 发生时,用户可以调整 producer 的 linger.ms 和 batch.size 以获得更好的吞吐量。此外,producer 缓冲区 用于使用 snappy 压缩消息的 值 小于 broker 使用的 值,后者可能具有负数 对磁盘上消息的压缩率的影响。我们打算在未来的 Kafka 中实现可配置 释放。

0.10.0.0 中的潜在重大更改
  • 从 Kafka 0.10.0.0 开始,Kafka 中的消息格式版本表示为 Kafka 版本。例如,消息格式 0.9.0 是指 Kafka 0.9.0 支持的最高消息版本。
  • 引入了消息格式 0.10.0,并默认使用。它在消息中包括一个时间戳字段,相对偏移量用于压缩的消息。
  • 引入了 ProduceRequest/Response v2,默认情况下使用它来支持消息格式 0.10.0
  • 引入了 FetchRequest/Response v2,默认情况下使用它来支持消息格式 0.10.0
  • MessageFormatter 接口已从def writeTo(key: Array[Byte], value: Array[Byte], output: PrintStream)def writeTo(consumerRecord: ConsumerRecord[Array[Byte], Array[Byte]], output: PrintStream)
  • MessageReader 接口已从def readMessage(): KeyedMessage[Array[Byte], Array[Byte]]def readMessage(): ProducerRecord[Array[Byte], Array[Byte]]
  • MessageFormatter 的包已从kafka.toolskafka.common
  • MessageReader 的包已从kafka.toolskafka.common
  • MirrorMakerMessageHandler 不再公开handle(record: MessageAndMetadata[Array[Byte], Array[Byte]])方法,因为它从未被调用过。
  • 0.7 KafkaMigrationTool 不再与 Kafka 打包在一起。如果您需要从 0.7 迁移到 0.10.0,请先迁移到 0.8,然后按照记录的升级过程从 0.8 升级到 0.10.0。
  • 新使用者已将其 API 标准化以接受java.util.Collection作为方法参数的序列类型。可能需要更新现有代码才能使用 0.10.0 客户端库。
  • LZ4 压缩的消息处理已更改为使用可互作的成帧规范 (LZ4f v1.5.1)。 为了保持与旧客户端的兼容性,此更改仅适用于 Message 格式 0.10.0 及更高版本。 使用 v0/v1(消息格式 0.9.0)生成/获取 LZ4 压缩消息的客户端应继续 使用 0.9.0 成帧实现。使用 Produce/Fetch 协议 v2 或更高版本的客户端 应使用可互作的 LZ4f 帧。可互作的 LZ4 库的列表可在 https://www.lz4.org/
0.10.0.0 中的显著变化
  • 从 Kafka 0.10.0.0 开始,名为 Kafka Streams 的新客户端库可用于对存储在 Kafka 主题中的数据进行流处理。由于上述消息格式更改,这个新的客户端库仅适用于 0.10.x 及更高版本的代理。有关更多信息,请阅读 Streams 文档
  • 配置参数的默认值receive.buffer.bytes现在对于新使用者来说是 64K。
  • 新的使用者现在公开了 configuration 参数exclude.internal.topics限制内部主题(例如 Consumer Offsets 主题)意外包含在正则表达式订阅中。默认情况下,它是启用的。
  • 旧的 Scala 生产者已被弃用。用户应尽快将其代码迁移到 kafka-clients JAR 中包含的 Java 生产者。
  • 新的使用者 API 已标记为稳定。

从 0.8.0、0.8.1.X 或 0.8.2.X 升级到 0.9.0.0

0.9.0.0 与以前的版本相比,存在潜在的重大更改(请在升级前查看)和代理间协议更改。这意味着升级后的经纪商和客户端可能与旧版本不兼容。在升级客户端之前,请务必先升级 Kafka 集群。如果您使用的是 MirrorMaker,则还应首先升级下游集群。

对于滚动升级:

  1. 更新所有代理上的 server.properties 文件并添加以下属性:inter.broker.protocol.version=0.8.2.X
  2. 升级代理。这可以一次完成一个 broker作,只需将其关闭、更新代码并重新启动即可。
  3. 升级整个集群后,通过编辑 inter.broker.protocol.version 并将其设置为 0.9.0.0 来增加协议版本。
  4. 逐个重启 broker 以使新协议版本生效

注意:如果您愿意接受停机,您可以简单地关闭所有代理,更新代码并启动所有代理。默认情况下,他们将从新协议开始。

注意:升级 broker 后,可以随时更新协议版本并重新启动。它不必紧随其后。

0.9.0.0 中的潜在重大更改
  • Java 1.6 不再受支持。
  • 不再支持 Scala 2.9。
  • 现在,默认情况下,超过 1000 的代理 ID 将保留给自动分配的代理 ID。如果您的集群的现有代理 ID 高于该阈值,请确保相应地增加 reserved.broker.max.id 代理配置属性。
  • 删除了配置参数 replica.lag.max.messages。分区领导在决定哪些副本同步时将不再考虑滞后消息的数量。
  • 配置参数 replica.lag.time.max.ms 现在不仅指自上次从副本获取请求以来经过的时间,还指自上次副本赶上以来的时间。仍在从领导处获取消息但未赶上 replica.lag.time.max.ms 中最新消息的副本将被视为不同步。
  • 压缩的主题不再接受没有键的消息,如果尝试这样做,创建者将引发异常。在 0.8.x 中,没有 key 的消息会导致日志压缩线程随后抱怨并退出(并停止压缩所有压缩的主题)。
  • MirrorMaker 不再支持多个目标集群。因此,它只接受一个 --consumer.config 参数。要镜像多个源集群,每个源集群至少需要一个 MirrorMaker 实例,每个实例都有自己的使用者配置。
  • org.apache.kafka.clients.tools.* 下打包的工具已移至 org.apache.kafka.tools.*。所有包含的脚本仍将照常运行,只有直接导入这些类的自定义代码会受到影响。
  • 默认的 Kafka JVM 性能选项 (KAFKA_JVM_PERFORMANCE_OPTS) 已在 kafka-run-class.sh 中更改。
  • 现在,kafka-topics.sh 脚本 (kafka.admin.TopicCommand) 在失败时退出时,退出代码为非零。
  • 现在,kafka-topics.sh 脚本 (kafka.admin.TopicCommand) 将在主题名称中打印警告,因为在主题名称中使用了 '.' 或 '_' 而存在指标冲突风险,并且在实际冲突的情况下会出现错误。
  • kafka-console-producer.sh 脚本 (kafka.tools.ConsoleProducer) 将使用 Java 生产者,而不是默认使用的旧 Scala 生产者,用户必须指定 'old-producer' 才能使用旧的生产者。
  • 默认情况下,所有命令行工具都会将所有日志记录消息打印到 stderr 而不是 stdout。
0.9.0.1 中的显著变化
  • 可以通过将 broker.id.generation.enable 设置为 false 来禁用新的代理 ID 生成功能。
  • 配置参数 log.cleaner.enable 现在默认为 true。这意味着现在将默认压缩具有 cleanup.policy=compact 的主题,并且将通过 log.cleaner.dedupe.buffer.size 将 128 MB 的堆分配给清理进程。您可能希望根据您对压缩主题的使用情况查看 log.cleaner.dedupe.buffer.size 和其他 log.cleaner 配置值。
  • 默认情况下,新使用者的配置参数 fetch.min.bytes 的默认值现在为 1。
0.9.0.0 中的废弃
  • 已弃用从 kafka-topics.sh 脚本 (kafka.admin.TopicCommand) 更改主题配置的功能。今后,请使用 kafka-configs.sh 脚本 (kafka.admin.ConfigCommand) 来实现此功能。
  • kafka-consumer-offset-checker.sh (kafka.tools.ConsumerOffsetChecker) 已弃用。今后,请使用 kafka-consumer-groups.sh (kafka.admin.ConsumerGroupCommand) 来实现此功能。
  • kafka.tools.ProducerPerformance 类已弃用。今后,请使用 org.apache.kafka.tools.ProducerPerformance 来实现此功能(kafka-producer-perf-test.sh 也将更改为使用新类)。
  • 生产者配置 block.on.buffer.full 已被弃用,并将在未来版本中删除。目前,其默认值已更改为 false。KafkaProducer 将不再抛出 BufferExhaustedException,而是使用 max.block.ms 值进行 block,之后它将抛出 TimeoutException。如果 block.on.buffer.full 属性显式设置为 true,它会将 max.block.ms 设置为 Long.MAX_VALUE,并且不会遵循 metadata.fetch.timeout.ms

从 0.8.1 升级到 0.8.2

0.8.2 与 0.8.1 完全兼容。升级可以一次完成一个代理,只需将其关闭、更新代码并重新启动即可。

从 0.8.0 升级到 0.8.1

0.8.1 与 0.8 完全兼容。升级可以一次完成一个代理,只需将其关闭、更新代码并重新启动即可。

从 0.7 升级

版本 0.7 与较新版本不兼容。对 API、ZooKeeper 数据结构和协议以及配置进行了重大更改,以添加复制(在 0.7 中缺少)。从 0.7 升级到更高版本需要一个特殊的迁移工具。此迁移可以在不停机的情况下完成。

2. API 接口

Kafka includes five core apis:
  1. The Producer API allows applications to send streams of data to topics in the Kafka cluster.
  2. The Consumer API allows applications to read streams of data from topics in the Kafka cluster.
  3. The Streams API allows transforming streams of data from input topics to output topics.
  4. The Connect API allows implementing connectors that continually pull from some source system or application into Kafka or push from Kafka into some sink system or application.
  5. The Admin API allows managing and inspecting topics, brokers, and other Kafka objects.
Kafka exposes all its functionality over a language independent protocol which has clients available in many programming languages. However only the Java clients are maintained as part of the main Kafka project, the others are available as independent open source projects. A list of non-Java clients is available here.

2.1 Producer API

The Producer API allows applications to send streams of data to topics in the Kafka cluster.

Examples showing how to use the producer are given in the javadocs.

To use the producer, you can use the following maven dependency:

<dependency>
	<groupId>org.apache.kafka</groupId>
	<artifactId>kafka-clients</artifactId>
	<version>3.5.2</version>
</dependency>

2.2 Consumer API

The Consumer API allows applications to read streams of data from topics in the Kafka cluster.

Examples showing how to use the consumer are given in the javadocs.

To use the consumer, you can use the following maven dependency:

<dependency>
	<groupId>org.apache.kafka</groupId>
	<artifactId>kafka-clients</artifactId>
	<version>3.5.2</version>
</dependency>

2.3 Streams API

The Streams API allows transforming streams of data from input topics to output topics.

Examples showing how to use this library are given in the javadocs

Additional documentation on using the Streams API is available here.

To use Kafka Streams you can use the following maven dependency:

<dependency>
	<groupId>org.apache.kafka</groupId>
	<artifactId>kafka-streams</artifactId>
	<version>3.5.2</version>
</dependency>

When using Scala you may optionally include the library. Additional documentation on using the Kafka Streams DSL for Scala is available in the developer guide. kafka-streams-scala

To use Kafka Streams DSL for Scala for Scala 2.13 you can use the following maven dependency:

<dependency>
	<groupId>org.apache.kafka</groupId>
	<artifactId>kafka-streams-scala_2.13</artifactId>
	<version>3.5.2</version>
</dependency>

2.4 Connect API

The Connect API allows implementing connectors that continually pull from some source data system into Kafka or push from Kafka into some sink data system.

Many users of Connect won't need to use this API directly, though, they can use pre-built connectors without needing to write any code. Additional information on using Connect is available here.

Those who want to implement custom connectors can see the javadoc.

2.5 Admin API

The Admin API supports managing and inspecting topics, brokers, acls, and other Kafka objects.

To use the Admin API, add the following Maven dependency:

<dependency>
	<groupId>org.apache.kafka</groupId>
	<artifactId>kafka-clients</artifactId>
	<version>3.5.2</version>
</dependency>
For more information about the Admin APIs, see the javadoc.

3. 配置

Kafka uses key-value pairs in the property file format for configuration. These values can be supplied either from a file or programmatically.

3.1 Broker Configs

The essential configurations are the following:
  • broker.id
  • log.dirs
  • zookeeper.connect
Topic-level configurations and defaults are discussed in more detail below.
  • advertised.listeners

    Listeners to publish to ZooKeeper for clients to use, if different than the config property. In IaaS environments, this may need to be different from the interface to which the broker binds. If this is not set, the value for will be used. Unlike , it is not valid to advertise the 0.0.0.0 meta-address.
    Also unlike , there can be duplicated ports in this property, so that one listener can be configured to advertise another listener's address. This can be useful in some cases where external load balancers are used.
    listenerslistenerslistenerslisteners

    Type:string
    Default:null
    Valid Values:
    Importance:high
    Update Mode:per-broker
  • auto.create.topics.enable

    Enable auto creation of topic on the server

    Type:boolean
    Default:true
    Valid Values:
    Importance:high
    Update Mode:read-only
  • auto.leader.rebalance.enable

    Enables auto leader balancing. A background thread checks the distribution of partition leaders at regular intervals, configurable by `leader.imbalance.check.interval.seconds`. If the leader imbalance exceeds `leader.imbalance.per.broker.percentage`, leader rebalance to the preferred leader for partitions is triggered.

    Type:boolean
    Default:true
    Valid Values:
    Importance:high
    Update Mode:read-only
  • background.threads

    The number of threads to use for various background processing tasks

    Type:int
    Default:10
    Valid Values:[1,...]
    Importance:high
    Update Mode:cluster-wide
  • broker.id

    The broker id for this server. If unset, a unique broker id will be generated.To avoid conflicts between zookeeper generated broker id's and user configured broker id's, generated broker ids start from reserved.broker.max.id + 1.

    Type:int
    Default:-1
    Valid Values:
    Importance:high
    Update Mode:read-only
  • compression.type

    Specify the final compression type for a given topic. This configuration accepts the standard compression codecs ('gzip', 'snappy', 'lz4', 'zstd'). It additionally accepts 'uncompressed' which is equivalent to no compression; and 'producer' which means retain the original compression codec set by the producer.

    Type:string
    Default:producer
    Valid Values:[uncompressed, zstd, lz4, snappy, gzip, producer]
    Importance:high
    Update Mode:cluster-wide
  • control.plane.listener.name

    Name of listener used for communication between controller and brokers. Broker will use the control.plane.listener.name to locate the endpoint in listeners list, to listen for connections from the controller. For example, if a broker's config is :
    listeners = INTERNAL://192.1.1.8:9092, EXTERNAL://10.1.1.5:9093, CONTROLLER://192.1.1.8:9094
    listener.security.protocol.map = INTERNAL:PLAINTEXT, EXTERNAL:SSL, CONTROLLER:SSL
    control.plane.listener.name = CONTROLLER
    On startup, the broker will start listening on "192.1.1.8:9094" with security protocol "SSL".
    On controller side, when it discovers a broker's published endpoints through zookeeper, it will use the control.plane.listener.name to find the endpoint, which it will use to establish connection to the broker.
    For example, if the broker's published endpoints on zookeeper are :
    "endpoints" : ["INTERNAL://broker1.example.com:9092","EXTERNAL://broker1.example.com:9093","CONTROLLER://broker1.example.com:9094"]
    and the controller's config is :
    listener.security.protocol.map = INTERNAL:PLAINTEXT, EXTERNAL:SSL, CONTROLLER:SSL
    control.plane.listener.name = CONTROLLER
    then controller will use "broker1.example.com:9094" with security protocol "SSL" to connect to the broker.
    If not explicitly configured, the default value will be null and there will be no dedicated endpoints for controller connections.
    If explicitly configured, the value cannot be the same as the value of .
    inter.broker.listener.name

    Type:string
    Default:null
    Valid Values:
    Importance:high
    Update Mode:read-only
  • controller.listener.names

    A comma-separated list of the names of the listeners used by the controller. This is required if running in KRaft mode. When communicating with the controller quorum, the broker will always use the first listener in this list.
    Note: The ZK-based controller should not set this configuration.

    Type:string
    Default:null
    Valid Values:
    Importance:high
    Update Mode:read-only
  • controller.quorum.election.backoff.max.ms

    Maximum time in milliseconds before starting new elections. This is used in the binary exponential backoff mechanism that helps prevent gridlocked elections

    Type:int
    Default:1000 (1 second)
    Valid Values:
    Importance:high
    Update Mode:read-only
  • controller.quorum.election.timeout.ms

    Maximum time in milliseconds to wait without being able to fetch from the leader before triggering a new election

    Type:int
    Default:1000 (1 second)
    Valid Values:
    Importance:high
    Update Mode:read-only
  • controller.quorum.fetch.timeout.ms

    Maximum time without a successful fetch from the current leader before becoming a candidate and triggering an election for voters; Maximum time without receiving fetch from a majority of the quorum before asking around to see if there's a new epoch for leader

    Type:int
    Default:2000 (2 seconds)
    Valid Values:
    Importance:high
    Update Mode:read-only
  • controller.quorum.voters

    Map of id/endpoint information for the set of voters in a comma-separated list of `{id}@{host}:{port}` entries. For example: `1@localhost:9092,2@localhost:9093,3@localhost:9094`

    Type:list
    Default:""
    Valid Values:non-empty list
    Importance:high
    Update Mode:read-only
  • delete.topic.enable

    Enables delete topic. Delete topic through the admin tool will have no effect if this config is turned off

    Type:boolean
    Default:true
    Valid Values:
    Importance:high
    Update Mode:read-only
  • early.start.listeners

    A comma-separated list of listener names which may be started before the authorizer has finished initialization. This is useful when the authorizer is dependent on the cluster itself for bootstrapping, as is the case for the StandardAuthorizer (which stores ACLs in the metadata log.) By default, all listeners included in controller.listener.names will also be early start listeners. A listener should not appear in this list if it accepts external traffic.

    Type:string
    Default:null
    Valid Values:
    Importance:high
    Update Mode:read-only
  • leader.imbalance.check.interval.seconds

    The frequency with which the partition rebalance check is triggered by the controller

    Type:long
    Default:300
    Valid Values:[1,...]
    Importance:high
    Update Mode:read-only
  • leader.imbalance.per.broker.percentage

    The ratio of leader imbalance allowed per broker. The controller would trigger a leader balance if it goes above this value per broker. The value is specified in percentage.

    Type:int
    Default:10
    Valid Values:
    Importance:high
    Update Mode:read-only
  • listeners

    Listener List - Comma-separated list of URIs we will listen on and the listener names. If the listener name is not a security protocol, must also be set.
    Listener names and port numbers must be unique.
    Specify hostname as 0.0.0.0 to bind to all interfaces.
    Leave hostname empty to bind to default interface.
    Examples of legal listener lists:
    PLAINTEXT://myhost:9092,SSL://:9091
    CLIENT://0.0.0.0:9092,REPLICATION://localhost:9093
    listener.security.protocol.map

    Type:string
    Default:PLAINTEXT://:9092
    Valid Values:
    Importance:high
    Update Mode:per-broker
  • log.dir

    The directory in which the log data is kept (supplemental for log.dirs property)

    Type:string
    Default:/tmp/kafka-logs
    Valid Values:
    Importance:high
    Update Mode:read-only
  • log.dirs

    A comma-separated list of the directories where the log data is stored. If not set, the value in log.dir is used.

    Type:string
    Default:null
    Valid Values:
    Importance:high
    Update Mode:read-only
  • log.flush.interval.messages

    The number of messages accumulated on a log partition before messages are flushed to disk

    Type:long
    Default:9223372036854775807
    Valid Values:[1,...]
    Importance:high
    Update Mode:cluster-wide
  • log.flush.interval.ms

    The maximum time in ms that a message in any topic is kept in memory before flushed to disk. If not set, the value in log.flush.scheduler.interval.ms is used

    Type:long
    Default:null
    Valid Values:
    Importance:high
    Update Mode:cluster-wide
  • log.flush.offset.checkpoint.interval.ms

    The frequency with which we update the persistent record of the last flush which acts as the log recovery point

    Type:int
    Default:60000 (1 minute)
    Valid Values:[0,...]
    Importance:high
    Update Mode:read-only
  • log.flush.scheduler.interval.ms

    The frequency in ms that the log flusher checks whether any log needs to be flushed to disk

    Type:long
    Default:9223372036854775807
    Valid Values:
    Importance:high
    Update Mode:read-only
  • log.flush.start.offset.checkpoint.interval.ms

    The frequency with which we update the persistent record of log start offset

    Type:int
    Default:60000 (1 minute)
    Valid Values:[0,...]
    Importance:high
    Update Mode:read-only
  • log.retention.bytes

    The maximum size of the log before deleting it

    Type:long
    Default:-1
    Valid Values:
    Importance:high
    Update Mode:cluster-wide
  • log.retention.hours

    The number of hours to keep a log file before deleting it (in hours), tertiary to log.retention.ms property

    Type:int
    Default:168
    Valid Values:
    Importance:high
    Update Mode:read-only
  • log.retention.minutes

    The number of minutes to keep a log file before deleting it (in minutes), secondary to log.retention.ms property. If not set, the value in log.retention.hours is used

    Type:int
    Default:null
    Valid Values:
    Importance:high
    Update Mode:read-only
  • log.retention.ms

    The number of milliseconds to keep a log file before deleting it (in milliseconds), If not set, the value in log.retention.minutes is used. If set to -1, no time limit is applied.

    Type:long
    Default:null
    Valid Values:
    Importance:high
    Update Mode:cluster-wide
  • log.roll.hours

    The maximum time before a new log segment is rolled out (in hours), secondary to log.roll.ms property

    Type:int
    Default:168
    Valid Values:[1,...]
    Importance:high
    Update Mode:read-only
  • log.roll.jitter.hours

    The maximum jitter to subtract from logRollTimeMillis (in hours), secondary to log.roll.jitter.ms property

    Type:int
    Default:0
    Valid Values:[0,...]
    Importance:high
    Update Mode:read-only
  • log.roll.jitter.ms

    The maximum jitter to subtract from logRollTimeMillis (in milliseconds). If not set, the value in log.roll.jitter.hours is used

    Type:long
    Default:null
    Valid Values:
    Importance:high
    Update Mode:cluster-wide
  • log.roll.ms

    The maximum time before a new log segment is rolled out (in milliseconds). If not set, the value in log.roll.hours is used

    Type:long
    Default:null
    Valid Values:
    Importance:high
    Update Mode:cluster-wide
  • log.segment.bytes

    The maximum size of a single log file

    Type:int
    Default:1073741824 (1 gibibyte)
    Valid Values:[14,...]
    Importance:high
    Update Mode:cluster-wide
  • log.segment.delete.delay.ms

    The amount of time to wait before deleting a file from the filesystem

    Type:long
    Default:60000 (1 minute)
    Valid Values:[0,...]
    Importance:high
    Update Mode:cluster-wide
  • message.max.bytes

    The largest record batch size allowed by Kafka (after compression if compression is enabled). If this is increased and there are consumers older than 0.10.2, the consumers' fetch size must also be increased so that they can fetch record batches this large. In the latest message format version, records are always grouped into batches for efficiency. In previous message format versions, uncompressed records are not grouped into batches and this limit only applies to a single record in that case.This can be set per topic with the topic level config.max.message.bytes

    Type:int
    Default:1048588
    Valid Values:[0,...]
    Importance:high
    Update Mode:cluster-wide
  • metadata.log.dir

    This configuration determines where we put the metadata log for clusters in KRaft mode. If it is not set, the metadata log is placed in the first log directory from log.dirs.

    Type:string
    Default:null
    Valid Values:
    Importance:high
    Update Mode:read-only
  • metadata.log.max.record.bytes.between.snapshots

    This is the maximum number of bytes in the log between the latest snapshot and the high-watermark needed before generating a new snapshot. The default value is 20971520. To generate snapshots based on the time elapsed, see the configuration. The Kafka node will generate a snapshot when either the maximum time interval is reached or the maximum bytes limit is reached.metadata.log.max.snapshot.interval.ms

    Type:long
    Default:20971520
    Valid Values:[1,...]
    Importance:high
    Update Mode:read-only
  • metadata.log.max.snapshot.interval.ms

    This is the maximum number of milliseconds to wait to generate a snapshot if there are committed records in the log that are not included in the latest snapshot. A value of zero disables time based snapshot generation. The default value is 3600000. To generate snapshots based on the number of metadata bytes, see the configuration. The Kafka node will generate a snapshot when either the maximum time interval is reached or the maximum bytes limit is reached.metadata.log.max.record.bytes.between.snapshots

    Type:long
    Default:3600000 (1 hour)
    Valid Values:[0,...]
    Importance:high
    Update Mode:read-only
  • metadata.log.segment.bytes

    The maximum size of a single metadata log file.

    Type:int
    Default:1073741824 (1 gibibyte)
    Valid Values:[12,...]
    Importance:high
    Update Mode:read-only
  • metadata.log.segment.ms

    The maximum time before a new metadata log file is rolled out (in milliseconds).

    Type:long
    Default:604800000 (7 days)
    Valid Values:
    Importance:high
    Update Mode:read-only
  • metadata.max.retention.bytes

    The maximum combined size of the metadata log and snapshots before deleting old snapshots and log files. Since at least one snapshot must exist before any logs can be deleted, this is a soft limit.

    Type:long
    Default:104857600 (100 mebibytes)
    Valid Values:
    Importance:high
    Update Mode:read-only
  • metadata.max.retention.ms

    The number of milliseconds to keep a metadata log file or snapshot before deleting it. Since at least one snapshot must exist before any logs can be deleted, this is a soft limit.

    Type:long
    Default:604800000 (7 days)
    Valid Values:
    Importance:high
    Update Mode:read-only
  • min.insync.replicas

    When a producer sets acks to "all" (or "-1"), min.insync.replicas specifies the minimum number of replicas that must acknowledge a write for the write to be considered successful. If this minimum cannot be met, then the producer will raise an exception (either NotEnoughReplicas or NotEnoughReplicasAfterAppend).
    When used together, min.insync.replicas and acks allow you to enforce greater durability guarantees. A typical scenario would be to create a topic with a replication factor of 3, set min.insync.replicas to 2, and produce with acks of "all". This will ensure that the producer raises an exception if a majority of replicas do not receive a write.

    Type:int
    Default:1
    Valid Values:[1,...]
    Importance:high
    Update Mode:cluster-wide
  • node.id

    The node ID associated with the roles this process is playing when `process.roles` is non-empty. This is required configuration when running in KRaft mode.

    Type:int
    Default:-1
    Valid Values:
    Importance:high
    Update Mode:read-only
  • num.io.threads

    The number of threads that the server uses for processing requests, which may include disk I/O

    Type:int
    Default:8
    Valid Values:[1,...]
    Importance:high
    Update Mode:cluster-wide
  • num.network.threads

    The number of threads that the server uses for receiving requests from the network and sending responses to the network. Noted: each listener (except for controller listener) creates its own thread pool.

    Type:int
    Default:3
    Valid Values:[1,...]
    Importance:high
    Update Mode:cluster-wide
  • num.recovery.threads.per.data.dir

    The number of threads per data directory to be used for log recovery at startup and flushing at shutdown

    Type:int
    Default:1
    Valid Values:[1,...]
    Importance:high
    Update Mode:cluster-wide
  • num.replica.alter.log.dirs.threads

    The number of threads that can move replicas between log directories, which may include disk I/O

    Type:int
    Default:null
    Valid Values:
    Importance:high
    Update Mode:read-only
  • num.replica.fetchers

    Number of fetcher threads used to replicate records from each source broker. The total number of fetchers on each broker is bound by multiplied by the number of brokers in the cluster.Increasing this value can increase the degree of I/O parallelism in the follower and leader broker at the cost of higher CPU and memory utilization.num.replica.fetchers

    Type:int
    Default:1
    Valid Values:
    Importance:high
    Update Mode:cluster-wide
  • offset.metadata.max.bytes

    The maximum size for a metadata entry associated with an offset commit

    Type:int
    Default:4096 (4 kibibytes)
    Valid Values:
    Importance:high
    Update Mode:read-only
  • offsets.commit.required.acks

    The required acks before the commit can be accepted. In general, the default (-1) should not be overridden

    Type:short
    Default:-1
    Valid Values:
    Importance:high
    Update Mode:read-only
  • offsets.commit.timeout.ms

    Offset commit will be delayed until all replicas for the offsets topic receive the commit or this timeout is reached. This is similar to the producer request timeout.

    Type:int
    Default:5000 (5 seconds)
    Valid Values:[1,...]
    Importance:high
    Update Mode:read-only
  • offsets.load.buffer.size

    Batch size for reading from the offsets segments when loading offsets into the cache (soft-limit, overridden if records are too large).

    Type:int
    Default:5242880
    Valid Values:[1,...]
    Importance:high
    Update Mode:read-only
  • offsets.retention.check.interval.ms

    Frequency at which to check for stale offsets

    Type:long
    Default:600000 (10 minutes)
    Valid Values:[1,...]
    Importance:high
    Update Mode:read-only
  • offsets.retention.minutes

    For subscribed consumers, committed offset of a specific partition will be expired and discarded when 1) this retention period has elapsed after the consumer group loses all its consumers (i.e. becomes empty); 2) this retention period has elapsed since the last time an offset is committed for the partition and the group is no longer subscribed to the corresponding topic. For standalone consumers (using manual assignment), offsets will be expired after this retention period has elapsed since the time of last commit. Note that when a group is deleted via the delete-group request, its committed offsets will also be deleted without extra retention period; also when a topic is deleted via the delete-topic request, upon propagated metadata update any group's committed offsets for that topic will also be deleted without extra retention period.

    Type:int
    Default:10080
    Valid Values:[1,...]
    Importance:high
    Update Mode:read-only
  • offsets.topic.compression.codec

    Compression codec for the offsets topic - compression may be used to achieve "atomic" commits

    Type:int
    Default:0
    Valid Values:
    Importance:high
    Update Mode:read-only
  • offsets.topic.num.partitions

    The number of partitions for the offset commit topic (should not change after deployment)

    Type:int
    Default:50
    Valid Values:[1,...]
    Importance:high
    Update Mode:read-only
  • offsets.topic.replication.factor

    The replication factor for the offsets topic (set higher to ensure availability). Internal topic creation will fail until the cluster size meets this replication factor requirement.

    Type:short
    Default:3
    Valid Values:[1,...]
    Importance:high
    Update Mode:read-only
  • offsets.topic.segment.bytes

    The offsets topic segment bytes should be kept relatively small in order to facilitate faster log compaction and cache loads

    Type:int
    Default:104857600 (100 mebibytes)
    Valid Values:[1,...]
    Importance:high
    Update Mode:read-only
  • process.roles

    The roles that this process plays: 'broker', 'controller', or 'broker,controller' if it is both. This configuration is only applicable for clusters in KRaft (Kafka Raft) mode (instead of ZooKeeper). Leave this config undefined or empty for Zookeeper clusters.

    Type:list
    Default:""
    Valid Values:[broker, controller]
    Importance:high
    Update Mode:read-only
  • queued.max.requests

    The number of queued requests allowed for data-plane, before blocking the network threads

    Type:int
    Default:500
    Valid Values:[1,...]
    Importance:high
    Update Mode:read-only
  • replica.fetch.min.bytes

    Minimum bytes expected for each fetch response. If not enough bytes, wait up to (broker config).replica.fetch.wait.max.ms

    Type:int
    Default:1
    Valid Values:
    Importance:high
    Update Mode:read-only
  • replica.fetch.wait.max.ms

    The maximum wait time for each fetcher request issued by follower replicas. This value should always be less than the replica.lag.time.max.ms at all times to prevent frequent shrinking of ISR for low throughput topics

    Type:int
    Default:500
    Valid Values:
    Importance:high
    Update Mode:read-only
  • replica.high.watermark.checkpoint.interval.ms

    The frequency with which the high watermark is saved out to disk

    Type:long
    Default:5000 (5 seconds)
    Valid Values:
    Importance:high
    Update Mode:read-only
  • replica.lag.time.max.ms

    If a follower hasn't sent any fetch requests or hasn't consumed up to the leaders log end offset for at least this time, the leader will remove the follower from isr

    Type:long
    Default:30000 (30 seconds)
    Valid Values:
    Importance:high
    Update Mode:read-only
  • replica.socket.receive.buffer.bytes

    The socket receive buffer for network requests to the leader for replicating data

    Type:int
    Default:65536 (64 kibibytes)
    Valid Values:
    Importance:high
    Update Mode:read-only
  • replica.socket.timeout.ms

    The socket timeout for network requests. Its value should be at least replica.fetch.wait.max.ms

    Type:int
    Default:30000 (30 seconds)
    Valid Values:
    Importance:high
    Update Mode:read-only
  • request.timeout.ms

    The configuration controls the maximum amount of time the client will wait for the response of a request. If the response is not received before the timeout elapses the client will resend the request if necessary or fail the request if retries are exhausted.

    Type:int
    Default:30000 (30 seconds)
    Valid Values:
    Importance:high
    Update Mode:read-only
  • sasl.mechanism.controller.protocol

    SASL mechanism used for communication with controllers. Default is GSSAPI.

    Type:string
    Default:GSSAPI
    Valid Values:
    Importance:high
    Update Mode:read-only
  • socket.receive.buffer.bytes

    The SO_RCVBUF buffer of the socket server sockets. If the value is -1, the OS default will be used.

    Type:int
    Default:102400 (100 kibibytes)
    Valid Values:
    Importance:high
    Update Mode:read-only
  • socket.request.max.bytes

    The maximum number of bytes in a socket request

    Type:int
    Default:104857600 (100 mebibytes)
    Valid Values:[1,...]
    Importance:high
    Update Mode:read-only
  • socket.send.buffer.bytes

    The SO_SNDBUF buffer of the socket server sockets. If the value is -1, the OS default will be used.

    Type:int
    Default:102400 (100 kibibytes)
    Valid Values:
    Importance:high
    Update Mode:read-only
  • transaction.max.timeout.ms

    The maximum allowed timeout for transactions. If a client’s requested transaction time exceed this, then the broker will return an error in InitProducerIdRequest. This prevents a client from too large of a timeout, which can stall consumers reading from topics included in the transaction.

    Type:int
    Default:900000 (15 minutes)
    Valid Values:[1,...]
    Importance:high
    Update Mode:read-only
  • transaction.state.log.load.buffer.size

    Batch size for reading from the transaction log segments when loading producer ids and transactions into the cache (soft-limit, overridden if records are too large).

    Type:int
    Default:5242880
    Valid Values:[1,...]
    Importance:high
    Update Mode:read-only
  • transaction.state.log.min.isr

    Overridden min.insync.replicas config for the transaction topic.

    Type:int
    Default:2
    Valid Values:[1,...]
    Importance:high
    Update Mode:read-only
  • transaction.state.log.num.partitions

    The number of partitions for the transaction topic (should not change after deployment).

    Type:int
    Default:50
    Valid Values:[1,...]
    Importance:high
    Update Mode:read-only
  • transaction.state.log.replication.factor

    The replication factor for the transaction topic (set higher to ensure availability). Internal topic creation will fail until the cluster size meets this replication factor requirement.

    Type:short
    Default:3
    Valid Values:[1,...]
    Importance:high
    Update Mode:read-only
  • transaction.state.log.segment.bytes

    The transaction topic segment bytes should be kept relatively small in order to facilitate faster log compaction and cache loads

    Type:int
    Default:104857600 (100 mebibytes)
    Valid Values:[1,...]
    Importance:high
    Update Mode:read-only
  • transactional.id.expiration.ms

    The time in ms that the transaction coordinator will wait without receiving any transaction status updates for the current transaction before expiring its transactional id. Transactional IDs will not expire while a the transaction is still ongoing.

    Type:int
    Default:604800000 (7 days)
    Valid Values:[1,...]
    Importance:high
    Update Mode:read-only
  • unclean.leader.election.enable

    Indicates whether to enable replicas not in the ISR set to be elected as leader as a last resort, even though doing so may result in data loss

    Type:boolean
    Default:false
    Valid Values:
    Importance:high
    Update Mode:cluster-wide
  • zookeeper.connect

    Specifies the ZooKeeper connection string in the form where host and port are the host and port of a ZooKeeper server. To allow connecting through other ZooKeeper nodes when that ZooKeeper machine is down you can also specify multiple hosts in the form .
    The server can also have a ZooKeeper chroot path as part of its ZooKeeper connection string which puts its data under some path in the global ZooKeeper namespace. For example to give a chroot path of you would give the connection string as .
    hostname:porthostname1:port1,hostname2:port2,hostname3:port3/chroot/pathhostname1:port1,hostname2:port2,hostname3:port3/chroot/path

    Type:string
    Default:null
    Valid Values:
    Importance:high
    Update Mode:read-only
  • zookeeper.connection.timeout.ms

    The max time that the client waits to establish a connection to zookeeper. If not set, the value in zookeeper.session.timeout.ms is used

    Type:int
    Default:null
    Valid Values:
    Importance:high
    Update Mode:read-only
  • zookeeper.max.in.flight.requests

    The maximum number of unacknowledged requests the client will send to Zookeeper before blocking.

    Type:int
    Default:10
    Valid Values:[1,...]
    Importance:high
    Update Mode:read-only
  • zookeeper.metadata.migration.enable

    Enable ZK to KRaft migration

    Type:boolean
    Default:false
    Valid Values:
    Importance:high
    Update Mode:read-only
  • zookeeper.session.timeout.ms

    Zookeeper session timeout

    Type:int
    Default:18000 (18 seconds)
    Valid Values:
    Importance:high
    Update Mode:read-only
  • zookeeper.set.acl

    Set client to use secure ACLs

    Type:boolean
    Default:false
    Valid Values:
    Importance:high
    Update Mode:read-only
  • broker.heartbeat.interval.ms

    The length of time in milliseconds between broker heartbeats. Used when running in KRaft mode.

    Type:int
    Default:2000 (2 seconds)
    Valid Values:
    Importance:medium
    Update Mode:read-only
  • broker.id.generation.enable

    Enable automatic broker id generation on the server. When enabled the value configured for reserved.broker.max.id should be reviewed.

    Type:boolean
    Default:true
    Valid Values:
    Importance:medium
    Update Mode:read-only
  • broker.rack

    Rack of the broker. This will be used in rack aware replication assignment for fault tolerance. Examples: `RACK1`, `us-east-1d`

    Type:string
    Default:null
    Valid Values:
    Importance:medium
    Update Mode:read-only
  • broker.session.timeout.ms

    The length of time in milliseconds that a broker lease lasts if no heartbeats are made. Used when running in KRaft mode.

    Type:int
    Default:9000 (9 seconds)
    Valid Values:
    Importance:medium
    Update Mode:read-only
  • connections.max.idle.ms

    Idle connections timeout: the server socket processor threads close the connections that idle more than this

    Type:long
    Default:600000 (10 minutes)
    Valid Values:
    Importance:medium
    Update Mode:read-only
  • connections.max.reauth.ms

    When explicitly set to a positive number (the default is 0, not a positive number), a session lifetime that will not exceed the configured value will be communicated to v2.2.0 or later clients when they authenticate. The broker will disconnect any such connection that is not re-authenticated within the session lifetime and that is then subsequently used for any purpose other than re-authentication. Configuration names can optionally be prefixed with listener prefix and SASL mechanism name in lower-case. For example, listener.name.sasl_ssl.oauthbearer.connections.max.reauth.ms=3600000

    Type:long
    Default:0
    Valid Values:
    Importance:medium
    Update Mode:read-only
  • controlled.shutdown.enable

    Enable controlled shutdown of the server

    Type:boolean
    Default:true
    Valid Values:
    Importance:medium
    Update Mode:read-only
  • controlled.shutdown.max.retries

    Controlled shutdown can fail for multiple reasons. This determines the number of retries when such failure happens

    Type:int
    Default:3
    Valid Values:
    Importance:medium
    Update Mode:read-only
  • controlled.shutdown.retry.backoff.ms

    Before each retry, the system needs time to recover from the state that caused the previous failure (Controller fail over, replica lag etc). This config determines the amount of time to wait before retrying.

    Type:long
    Default:5000 (5 seconds)
    Valid Values:
    Importance:medium
    Update Mode:read-only
  • controller.quorum.append.linger.ms

    The duration in milliseconds that the leader will wait for writes to accumulate before flushing them to disk.

    Type:int
    Default:25
    Valid Values:
    Importance:medium
    Update Mode:read-only
  • controller.quorum.request.timeout.ms

    The configuration controls the maximum amount of time the client will wait for the response of a request. If the response is not received before the timeout elapses the client will resend the request if necessary or fail the request if retries are exhausted.

    Type:int
    Default:2000 (2 seconds)
    Valid Values:
    Importance:medium
    Update Mode:read-only
  • controller.socket.timeout.ms

    The socket timeout for controller-to-broker channels

    Type:int
    Default:30000 (30 seconds)
    Valid Values:
    Importance:medium
    Update Mode:read-only
  • default.replication.factor

    The default replication factors for automatically created topics

    Type:int
    Default:1
    Valid Values:
    Importance:medium
    Update Mode:read-only
  • delegation.token.expiry.time.ms

    The token validity time in miliseconds before the token needs to be renewed. Default value 1 day.

    Type:long
    Default:86400000 (1 day)
    Valid Values:[1,...]
    Importance:medium
    Update Mode:read-only
  • delegation.token.master.key

    DEPRECATED: An alias for delegation.token.secret.key, which should be used instead of this config.

    Type:password
    Default:null
    Valid Values:
    Importance:medium
    Update Mode:read-only
  • delegation.token.max.lifetime.ms

    The token has a maximum lifetime beyond which it cannot be renewed anymore. Default value 7 days.

    Type:long
    Default:604800000 (7 days)
    Valid Values:[1,...]
    Importance:medium
    Update Mode:read-only
  • delegation.token.secret.key

    Secret key to generate and verify delegation tokens. The same key must be configured across all the brokers. If the key is not set or set to empty string, brokers will disable the delegation token support.

    Type:password
    Default:null
    Valid Values:
    Importance:medium
    Update Mode:read-only
  • delete.records.purgatory.purge.interval.requests

    The purge interval (in number of requests) of the delete records request purgatory

    Type:int
    Default:1
    Valid Values:
    Importance:medium
    Update Mode:read-only
  • fetch.max.bytes

    The maximum number of bytes we will return for a fetch request. Must be at least 1024.

    Type:int
    Default:57671680 (55 mebibytes)
    Valid Values:[1024,...]
    Importance:medium
    Update Mode:read-only
  • fetch.purgatory.purge.interval.requests

    The purge interval (in number of requests) of the fetch request purgatory

    Type:int
    Default:1000
    Valid Values:
    Importance:medium
    Update Mode:read-only
  • group.initial.rebalance.delay.ms

    The amount of time the group coordinator will wait for more consumers to join a new group before performing the first rebalance. A longer delay means potentially fewer rebalances, but increases the time until processing begins.

    Type:int
    Default:3000 (3 seconds)
    Valid Values:
    Importance:medium
    Update Mode:read-only
  • group.max.session.timeout.ms

    The maximum allowed session timeout for registered consumers. Longer timeouts give consumers more time to process messages in between heartbeats at the cost of a longer time to detect failures.

    Type:int
    Default:1800000 (30 minutes)
    Valid Values:
    Importance:medium
    Update Mode:read-only
  • group.max.size

    The maximum number of consumers that a single consumer group can accommodate.

    Type:int
    Default:2147483647
    Valid Values:[1,...]
    Importance:medium
    Update Mode:read-only
  • group.min.session.timeout.ms

    The minimum allowed session timeout for registered consumers. Shorter timeouts result in quicker failure detection at the cost of more frequent consumer heartbeating, which can overwhelm broker resources.

    Type:int
    Default:6000 (6 seconds)
    Valid Values:
    Importance:medium
    Update Mode:read-only
  • initial.broker.registration.timeout.ms

    When initially registering with the controller quorum, the number of milliseconds to wait before declaring failure and exiting the broker process.

    Type:int
    Default:60000 (1 minute)
    Valid Values:
    Importance:medium
    Update Mode:read-only
  • inter.broker.listener.name

    Name of listener used for communication between brokers. If this is unset, the listener name is defined by security.inter.broker.protocol. It is an error to set this and security.inter.broker.protocol properties at the same time.

    Type:string
    Default:null
    Valid Values:
    Importance:medium
    Update Mode:read-only
  • inter.broker.protocol.version

    Specify which version of the inter-broker protocol will be used.
    This is typically bumped after all brokers were upgraded to a new version.
    Example of some valid values are: 0.8.0, 0.8.1, 0.8.1.1, 0.8.2, 0.8.2.0, 0.8.2.1, 0.9.0.0, 0.9.0.1 Check MetadataVersion for the full list.
    This configuration is only applicable in Zookeeper mode.

    Type:string
    Default:3.5-IV2
    Valid Values:[0.8.0, 0.8.1, 0.8.2, 0.9.0, 0.10.0-IV0, 0.10.0-IV1, 0.10.1-IV0, 0.10.1-IV1, 0.10.1-IV2, 0.10.2-IV0, 0.11.0-IV0, 0.11.0-IV1, 0.11.0-IV2, 1.0-IV0, 1.1-IV0, 2.0-IV0, 2.0-IV1, 2.1-IV0, 2.1-IV1, 2.1-IV2, 2.2-IV0, 2.2-IV1, 2.3-IV0, 2.3-IV1, 2.4-IV0, 2.4-IV1, 2.5-IV0, 2.6-IV0, 2.7-IV0, 2.7-IV1, 2.7-IV2, 2.8-IV0, 2.8-IV1, 3.0-IV0, 3.0-IV1, 3.1-IV0, 3.2-IV0, 3.3-IV0, 3.3-IV1, 3.3-IV2, 3.3-IV3, 3.4-IV0, 3.5-IV0, 3.5-IV1, 3.5-IV2]
    Importance:medium
    Update Mode:read-only
  • log.cleaner.backoff.ms

    The amount of time to sleep when there are no logs to clean

    Type:long
    Default:15000 (15 seconds)
    Valid Values:[0,...]
    Importance:medium
    Update Mode:cluster-wide
  • log.cleaner.dedupe.buffer.size

    The total memory used for log deduplication across all cleaner threads

    Type:long
    Default:134217728
    Valid Values:
    Importance:medium
    Update Mode:cluster-wide
  • log.cleaner.delete.retention.ms

    The amount of time to retain delete tombstone markers for log compacted topics. This setting also gives a bound on the time in which a consumer must complete a read if they begin from offset 0 to ensure that they get a valid snapshot of the final stage (otherwise delete tombstones may be collected before they complete their scan).

    Type:long
    Default:86400000 (1 day)
    Valid Values:[0,...]
    Importance:medium
    Update Mode:cluster-wide
  • log.cleaner.enable

    Enable the log cleaner process to run on the server. Should be enabled if using any topics with a cleanup.policy=compact including the internal offsets topic. If disabled those topics will not be compacted and continually grow in size.

    Type:boolean
    Default:true
    Valid Values:
    Importance:medium
    Update Mode:read-only
  • log.cleaner.io.buffer.load.factor

    Log cleaner dedupe buffer load factor. The percentage full the dedupe buffer can become. A higher value will allow more log to be cleaned at once but will lead to more hash collisions

    Type:double
    Default:0.9
    Valid Values:
    Importance:medium
    Update Mode:cluster-wide
  • log.cleaner.io.buffer.size

    The total memory used for log cleaner I/O buffers across all cleaner threads

    Type:int
    Default:524288
    Valid Values:[0,...]
    Importance:medium
    Update Mode:cluster-wide
  • log.cleaner.io.max.bytes.per.second

    The log cleaner will be throttled so that the sum of its read and write i/o will be less than this value on average

    Type:double
    Default:1.7976931348623157E308
    Valid Values:
    Importance:medium
    Update Mode:cluster-wide
  • log.cleaner.max.compaction.lag.ms

    The maximum time a message will remain ineligible for compaction in the log. Only applicable for logs that are being compacted.

    Type:long
    Default:9223372036854775807
    Valid Values:[1,...]
    Importance:medium
    Update Mode:cluster-wide
  • log.cleaner.min.cleanable.ratio

    The minimum ratio of dirty log to total log for a log to eligible for cleaning. If the log.cleaner.max.compaction.lag.ms or the log.cleaner.min.compaction.lag.ms configurations are also specified, then the log compactor considers the log eligible for compaction as soon as either: (i) the dirty ratio threshold has been met and the log has had dirty (uncompacted) records for at least the log.cleaner.min.compaction.lag.ms duration, or (ii) if the log has had dirty (uncompacted) records for at most the log.cleaner.max.compaction.lag.ms period.

    Type:double
    Default:0.5
    Valid Values:[0,...,1]
    Importance:medium
    Update Mode:cluster-wide
  • log.cleaner.min.compaction.lag.ms

    The minimum time a message will remain uncompacted in the log. Only applicable for logs that are being compacted.

    Type:long
    Default:0
    Valid Values:[0,...]
    Importance:medium
    Update Mode:cluster-wide
  • log.cleaner.threads

    The number of background threads to use for log cleaning

    Type:int
    Default:1
    Valid Values:[0,...]
    Importance:medium
    Update Mode:cluster-wide
  • log.cleanup.policy

    The default cleanup policy for segments beyond the retention window. A comma separated list of valid policies. Valid policies are: "delete" and "compact"

    Type:list
    Default:delete
    Valid Values:[compact, delete]
    Importance:medium
    Update Mode:cluster-wide
  • log.index.interval.bytes

    The interval with which we add an entry to the offset index

    Type:int
    Default:4096 (4 kibibytes)
    Valid Values:[0,...]
    Importance:medium
    Update Mode:cluster-wide
  • log.index.size.max.bytes

    The maximum size in bytes of the offset index

    Type:int
    Default:10485760 (10 mebibytes)
    Valid Values:[4,...]
    Importance:medium
    Update Mode:cluster-wide
  • log.message.format.version

    Specify the message format version the broker will use to append messages to the logs. The value should be a valid MetadataVersion. Some examples are: 0.8.2, 0.9.0.0, 0.10.0, check MetadataVersion for more details. By setting a particular message format version, the user is certifying that all the existing messages on disk are smaller or equal than the specified version. Setting this value incorrectly will cause consumers with older versions to break as they will receive messages with a format that they don't understand.

    Type:string
    Default:3.0-IV1
    Valid Values:[0.8.0, 0.8.1, 0.8.2, 0.9.0, 0.10.0-IV0, 0.10.0-IV1, 0.10.1-IV0, 0.10.1-IV1, 0.10.1-IV2, 0.10.2-IV0, 0.11.0-IV0, 0.11.0-IV1, 0.11.0-IV2, 1.0-IV0, 1.1-IV0, 2.0-IV0, 2.0-IV1, 2.1-IV0, 2.1-IV1, 2.1-IV2, 2.2-IV0, 2.2-IV1, 2.3-IV0, 2.3-IV1, 2.4-IV0, 2.4-IV1, 2.5-IV0, 2.6-IV0, 2.7-IV0, 2.7-IV1, 2.7-IV2, 2.8-IV0, 2.8-IV1, 3.0-IV0, 3.0-IV1, 3.1-IV0, 3.2-IV0, 3.3-IV0, 3.3-IV1, 3.3-IV2, 3.3-IV3, 3.4-IV0, 3.5-IV0, 3.5-IV1, 3.5-IV2]
    Importance:medium
    Update Mode:read-only
  • log.message.timestamp.difference.max.ms

    The maximum difference allowed between the timestamp when a broker receives a message and the timestamp specified in the message. If log.message.timestamp.type=CreateTime, a message will be rejected if the difference in timestamp exceeds this threshold. This configuration is ignored if log.message.timestamp.type=LogAppendTime.The maximum timestamp difference allowed should be no greater than log.retention.ms to avoid unnecessarily frequent log rolling.

    Type:long
    Default:9223372036854775807
    Valid Values:[0,...]
    Importance:medium
    Update Mode:cluster-wide
  • log.message.timestamp.type

    Define whether the timestamp in the message is message create time or log append time. The value should be either `CreateTime` or `LogAppendTime`

    Type:string
    Default:CreateTime
    Valid Values:[CreateTime, LogAppendTime]
    Importance:medium
    Update Mode:cluster-wide
  • log.preallocate

    Should pre allocate file when create new segment? If you are using Kafka on Windows, you probably need to set it to true.

    Type:boolean
    Default:false
    Valid Values:
    Importance:medium
    Update Mode:cluster-wide
  • log.retention.check.interval.ms

    The frequency in milliseconds that the log cleaner checks whether any log is eligible for deletion

    Type:long
    Default:300000 (5 minutes)
    Valid Values:[1,...]
    Importance:medium
    Update Mode:read-only
  • max.connection.creation.rate

    The maximum connection creation rate we allow in the broker at any time. Listener-level limits may also be configured by prefixing the config name with the listener prefix, for example, .Broker-wide connection rate limit should be configured based on broker capacity while listener limits should be configured based on application requirements. New connections will be throttled if either the listener or the broker limit is reached, with the exception of inter-broker listener. Connections on the inter-broker listener will be throttled only when the listener-level rate limit is reached.listener.name.internal.max.connection.creation.rate

    Type:int
    Default:2147483647
    Valid Values:[0,...]
    Importance:medium
    Update Mode:cluster-wide
  • max.connections

    The maximum number of connections we allow in the broker at any time. This limit is applied in addition to any per-ip limits configured using max.connections.per.ip. Listener-level limits may also be configured by prefixing the config name with the listener prefix, for example, . Broker-wide limit should be configured based on broker capacity while listener limits should be configured based on application requirements. New connections are blocked if either the listener or broker limit is reached. Connections on the inter-broker listener are permitted even if broker-wide limit is reached. The least recently used connection on another listener will be closed in this case.listener.name.internal.max.connections

    Type:int
    Default:2147483647
    Valid Values:[0,...]
    Importance:medium
    Update Mode:cluster-wide
  • max.connections.per.ip

    The maximum number of connections we allow from each ip address. This can be set to 0 if there are overrides configured using max.connections.per.ip.overrides property. New connections from the ip address are dropped if the limit is reached.

    Type:int
    Default:2147483647
    Valid Values:[0,...]
    Importance:medium
    Update Mode:cluster-wide
  • max.connections.per.ip.overrides

    A comma-separated list of per-ip or hostname overrides to the default maximum number of connections. An example value is "hostName:100,127.0.0.1:200"

    Type:string
    Default:""
    Valid Values:
    Importance:medium
    Update Mode:cluster-wide
  • max.incremental.fetch.session.cache.slots

    The maximum number of incremental fetch sessions that we will maintain.

    Type:int
    Default:1000
    Valid Values:[0,...]
    Importance:medium
    Update Mode:read-only
  • num.partitions

    The default number of log partitions per topic

    Type:int
    Default:1
    Valid Values:[1,...]
    Importance:medium
    Update Mode:read-only
  • password.encoder.old.secret

    The old secret that was used for encoding dynamically configured passwords. This is required only when the secret is updated. If specified, all dynamically encoded passwords are decoded using this old secret and re-encoded using password.encoder.secret when broker starts up.

    Type:password
    Default:null
    Valid Values:
    Importance:medium
    Update Mode:read-only
  • password.encoder.secret

    The secret used for encoding dynamically configured passwords for this broker.

    Type:password
    Default:null
    Valid Values:
    Importance:medium
    Update Mode:read-only
  • principal.builder.class

    The fully qualified name of a class that implements the KafkaPrincipalBuilder interface, which is used to build the KafkaPrincipal object used during authorization. If no principal builder is defined, the default behavior depends on the security protocol in use. For SSL authentication, the principal will be derived using the rules defined by applied on the distinguished name from the client certificate if one is provided; otherwise, if client authentication is not required, the principal name will be ANONYMOUS. For SASL authentication, the principal will be derived using the rules defined by if GSSAPI is in use, and the SASL authentication ID for other mechanisms. For PLAINTEXT, the principal will be ANONYMOUS.ssl.principal.mapping.rulessasl.kerberos.principal.to.local.rules

    Type:class
    Default:org.apache.kafka.common.security.authenticator.DefaultKafkaPrincipalBuilder
    Valid Values:
    Importance:medium
    Update Mode:per-broker
  • producer.purgatory.purge.interval.requests

    The purge interval (in number of requests) of the producer request purgatory

    Type:int
    Default:1000
    Valid Values:
    Importance:medium
    Update Mode:read-only
  • queued.max.request.bytes

    The number of queued bytes allowed before no more requests are read

    Type:long
    Default:-1
    Valid Values:
    Importance:medium
    Update Mode:read-only
  • replica.fetch.backoff.ms

    The amount of time to sleep when fetch partition error occurs.

    Type:int
    Default:1000 (1 second)
    Valid Values:[0,...]
    Importance:medium
    Update Mode:read-only
  • replica.fetch.max.bytes

    The number of bytes of messages to attempt to fetch for each partition. This is not an absolute maximum, if the first record batch in the first non-empty partition of the fetch is larger than this value, the record batch will still be returned to ensure that progress can be made. The maximum record batch size accepted by the broker is defined via (broker config) or (topic config).message.max.bytesmax.message.bytes

    Type:int
    Default:1048576 (1 mebibyte)
    Valid Values:[0,...]
    Importance:medium
    Update Mode:read-only
  • replica.fetch.response.max.bytes

    Maximum bytes expected for the entire fetch response. Records are fetched in batches, and if the first record batch in the first non-empty partition of the fetch is larger than this value, the record batch will still be returned to ensure that progress can be made. As such, this is not an absolute maximum. The maximum record batch size accepted by the broker is defined via (broker config) or (topic config).message.max.bytesmax.message.bytes

    Type:int
    Default:10485760 (10 mebibytes)
    Valid Values:[0,...]
    Importance:medium
    Update Mode:read-only
  • replica.selector.class

    The fully qualified class name that implements ReplicaSelector. This is used by the broker to find the preferred read replica. By default, we use an implementation that returns the leader.

    Type:string
    Default:null
    Valid Values:
    Importance:medium
    Update Mode:read-only
  • reserved.broker.max.id

    Max number that can be used for a broker.id

    Type:int
    Default:1000
    Valid Values:[0,...]
    Importance:medium
    Update Mode:read-only
  • sasl.client.callback.handler.class

    The fully qualified name of a SASL client callback handler class that implements the AuthenticateCallbackHandler interface.

    Type:class
    Default:null
    Valid Values:
    Importance:medium
    Update Mode:read-only
  • sasl.enabled.mechanisms

    The list of SASL mechanisms enabled in the Kafka server. The list may contain any mechanism for which a security provider is available. Only GSSAPI is enabled by default.

    Type:list
    Default:GSSAPI
    Valid Values:
    Importance:medium
    Update Mode:per-broker
  • sasl.jaas.config

    JAAS login context parameters for SASL connections in the format used by JAAS configuration files. JAAS configuration file format is described here. The format for the value is: . For brokers, the config must be prefixed with listener prefix and SASL mechanism name in lower-case. For example, listener.name.sasl_ssl.scram-sha-256.sasl.jaas.config=com.example.ScramLoginModule required;loginModuleClass controlFlag (optionName=optionValue)*;

    Type:password
    Default:null
    Valid Values:
    Importance:medium
    Update Mode:per-broker
  • sasl.kerberos.kinit.cmd

    Kerberos kinit command path.

    Type:string
    Default:/usr/bin/kinit
    Valid Values:
    Importance:medium
    Update Mode:per-broker
  • sasl.kerberos.min.time.before.relogin

    Login thread sleep time between refresh attempts.

    Type:long
    Default:60000
    Valid Values:
    Importance:medium
    Update Mode:per-broker
  • sasl.kerberos.principal.to.local.rules

    A list of rules for mapping from principal names to short names (typically operating system usernames). The rules are evaluated in order and the first rule that matches a principal name is used to map it to a short name. Any later rules in the list are ignored. By default, principal names of the form are mapped to . For more details on the format please see security authorization and acls. Note that this configuration is ignored if an extension of is provided by the configuration.{username}/{hostname}@{REALM}{username}KafkaPrincipalBuilderprincipal.builder.class

    Type:list
    Default:DEFAULT
    Valid Values:
    Importance:medium
    Update Mode:per-broker
  • sasl.kerberos.service.name

    The Kerberos principal name that Kafka runs as. This can be defined either in Kafka's JAAS config or in Kafka's config.

    Type:string
    Default:null
    Valid Values:
    Importance:medium
    Update Mode:per-broker
  • sasl.kerberos.ticket.renew.jitter

    Percentage of random jitter added to the renewal time.

    Type:double
    Default:0.05
    Valid Values:
    Importance:medium
    Update Mode:per-broker
  • sasl.kerberos.ticket.renew.window.factor

    Login thread will sleep until the specified window factor of time from last refresh to ticket's expiry has been reached, at which time it will try to renew the ticket.

    Type:double
    Default:0.8
    Valid Values:
    Importance:medium
    Update Mode:per-broker
  • sasl.login.callback.handler.class

    The fully qualified name of a SASL login callback handler class that implements the AuthenticateCallbackHandler interface. For brokers, login callback handler config must be prefixed with listener prefix and SASL mechanism name in lower-case. For example, listener.name.sasl_ssl.scram-sha-256.sasl.login.callback.handler.class=com.example.CustomScramLoginCallbackHandler

    Type:class
    Default:null
    Valid Values:
    Importance:medium
    Update Mode:read-only
  • sasl.login.class

    The fully qualified name of a class that implements the Login interface. For brokers, login config must be prefixed with listener prefix and SASL mechanism name in lower-case. For example, listener.name.sasl_ssl.scram-sha-256.sasl.login.class=com.example.CustomScramLogin

    Type:class
    Default:null
    Valid Values:
    Importance:medium
    Update Mode:read-only
  • sasl.login.refresh.buffer.seconds

    The amount of buffer time before credential expiration to maintain when refreshing a credential, in seconds. If a refresh would otherwise occur closer to expiration than the number of buffer seconds then the refresh will be moved up to maintain as much of the buffer time as possible. Legal values are between 0 and 3600 (1 hour); a default value of 300 (5 minutes) is used if no value is specified. This value and sasl.login.refresh.min.period.seconds are both ignored if their sum exceeds the remaining lifetime of a credential. Currently applies only to OAUTHBEARER.

    Type:short
    Default:300
    Valid Values:
    Importance:medium
    Update Mode:per-broker
  • sasl.login.refresh.min.period.seconds

    The desired minimum time for the login refresh thread to wait before refreshing a credential, in seconds. Legal values are between 0 and 900 (15 minutes); a default value of 60 (1 minute) is used if no value is specified. This value and sasl.login.refresh.buffer.seconds are both ignored if their sum exceeds the remaining lifetime of a credential. Currently applies only to OAUTHBEARER.

    Type:short
    Default:60
    Valid Values:
    Importance:medium
    Update Mode:per-broker
  • sasl.login.refresh.window.factor

    Login refresh thread will sleep until the specified window factor relative to the credential's lifetime has been reached, at which time it will try to refresh the credential. Legal values are between 0.5 (50%) and 1.0 (100%) inclusive; a default value of 0.8 (80%) is used if no value is specified. Currently applies only to OAUTHBEARER.

    Type:double
    Default:0.8
    Valid Values:
    Importance:medium
    Update Mode:per-broker
  • sasl.login.refresh.window.jitter

    The maximum amount of random jitter relative to the credential's lifetime that is added to the login refresh thread's sleep time. Legal values are between 0 and 0.25 (25%) inclusive; a default value of 0.05 (5%) is used if no value is specified. Currently applies only to OAUTHBEARER.

    Type:double
    Default:0.05
    Valid Values:
    Importance:medium
    Update Mode:per-broker
  • sasl.mechanism.inter.broker.protocol

    SASL mechanism used for inter-broker communication. Default is GSSAPI.

    Type:string
    Default:GSSAPI
    Valid Values:
    Importance:medium
    Update Mode:per-broker
  • sasl.oauthbearer.jwks.endpoint.url

    The OAuth/OIDC provider URL from which the provider's JWKS (JSON Web Key Set) can be retrieved. The URL can be HTTP(S)-based or file-based. If the URL is HTTP(S)-based, the JWKS data will be retrieved from the OAuth/OIDC provider via the configured URL on broker startup. All then-current keys will be cached on the broker for incoming requests. If an authentication request is received for a JWT that includes a "kid" header claim value that isn't yet in the cache, the JWKS endpoint will be queried again on demand. However, the broker polls the URL every sasl.oauthbearer.jwks.endpoint.refresh.ms milliseconds to refresh the cache with any forthcoming keys before any JWT requests that include them are received. If the URL is file-based, the broker will load the JWKS file from a configured location on startup. In the event that the JWT includes a "kid" header value that isn't in the JWKS file, the broker will reject the JWT and authentication will fail.

    Type:string
    Default:null
    Valid Values:
    Importance:medium
    Update Mode:read-only
  • sasl.oauthbearer.token.endpoint.url

    The URL for the OAuth/OIDC identity provider. If the URL is HTTP(S)-based, it is the issuer's token endpoint URL to which requests will be made to login based on the configuration in sasl.jaas.config. If the URL is file-based, it specifies a file containing an access token (in JWT serialized form) issued by the OAuth/OIDC identity provider to use for authorization.

    Type:string
    Default:null
    Valid Values:
    Importance:medium
    Update Mode:read-only
  • sasl.server.callback.handler.class

    The fully qualified name of a SASL server callback handler class that implements the AuthenticateCallbackHandler interface. Server callback handlers must be prefixed with listener prefix and SASL mechanism name in lower-case. For example, listener.name.sasl_ssl.plain.sasl.server.callback.handler.class=com.example.CustomPlainCallbackHandler.

    Type:class
    Default:null
    Valid Values:
    Importance:medium
    Update Mode:read-only
  • sasl.server.max.receive.size

    The maximum receive size allowed before and during initial SASL authentication. Default receive size is 512KB. GSSAPI limits requests to 64K, but we allow upto 512KB by default for custom SASL mechanisms. In practice, PLAIN, SCRAM and OAUTH mechanisms can use much smaller limits.

    Type:int
    Default:524288
    Valid Values:
    Importance:medium
    Update Mode:read-only
  • security.inter.broker.protocol

    Security protocol used to communicate between brokers. Valid values are: PLAINTEXT, SSL, SASL_PLAINTEXT, SASL_SSL. It is an error to set this and inter.broker.listener.name properties at the same time.

    Type:string
    Default:PLAINTEXT
    Valid Values:[PLAINTEXT, SSL, SASL_PLAINTEXT, SASL_SSL]
    Importance:medium
    Update Mode:read-only
  • socket.connection.setup.timeout.max.ms

    The maximum amount of time the client will wait for the socket connection to be established. The connection setup timeout will increase exponentially for each consecutive connection failure up to this maximum. To avoid connection storms, a randomization factor of 0.2 will be applied to the timeout resulting in a random range between 20% below and 20% above the computed value.

    Type:long
    Default:30000 (30 seconds)
    Valid Values:
    Importance:medium
    Update Mode:read-only
  • socket.connection.setup.timeout.ms

    The amount of time the client will wait for the socket connection to be established. If the connection is not built before the timeout elapses, clients will close the socket channel.

    Type:long
    Default:10000 (10 seconds)
    Valid Values:
    Importance:medium
    Update Mode:read-only
  • socket.listen.backlog.size

    The maximum number of pending connections on the socket. In Linux, you may also need to configure `somaxconn` and `tcp_max_syn_backlog` kernel parameters accordingly to make the configuration takes effect.

    Type:int
    Default:50
    Valid Values:[1,...]
    Importance:medium
    Update Mode:read-only
  • ssl.cipher.suites

    A list of cipher suites. This is a named combination of authentication, encryption, MAC and key exchange algorithm used to negotiate the security settings for a network connection using TLS or SSL network protocol. By default all the available cipher suites are supported.

    Type:list
    Default:""
    Valid Values:
    Importance:medium
    Update Mode:per-broker
  • ssl.client.auth

    Configures kafka broker to request client authentication. The following settings are common:

    • ssl.client.auth=required If set to required client authentication is required.
    • ssl.client.auth=requested This means client authentication is optional. unlike required, if this option is set client can choose not to provide authentication information about itself
    • ssl.client.auth=none This means client authentication is not needed.

    Type:string
    Default:none
    Valid Values:[required, requested, none]
    Importance:medium
    Update Mode:per-broker
  • ssl.enabled.protocols

    The list of protocols enabled for SSL connections. The default is 'TLSv1.2,TLSv1.3' when running with Java 11 or newer, 'TLSv1.2' otherwise. With the default value for Java 11, clients and servers will prefer TLSv1.3 if both support it and fallback to TLSv1.2 otherwise (assuming both support at least TLSv1.2). This default should be fine for most cases. Also see the config documentation for `ssl.protocol`.

    Type:list
    Default:TLSv1.2,TLSv1.3
    Valid Values:
    Importance:medium
    Update Mode:per-broker
  • ssl.key.password

    The password of the private key in the key store file or the PEM key specified in 'ssl.keystore.key'.

    Type:password
    Default:null
    Valid Values:
    Importance:medium
    Update Mode:per-broker
  • ssl.keymanager.algorithm

    The algorithm used by key manager factory for SSL connections. Default value is the key manager factory algorithm configured for the Java Virtual Machine.

    Type:string
    Default:SunX509
    Valid Values:
    Importance:medium
    Update Mode:per-broker
  • ssl.keystore.certificate.chain

    Certificate chain in the format specified by 'ssl.keystore.type'. Default SSL engine factory supports only PEM format with a list of X.509 certificates

    Type:password
    Default:null
    Valid Values:
    Importance:medium
    Update Mode:per-broker
  • ssl.keystore.key

    Private key in the format specified by 'ssl.keystore.type'. Default SSL engine factory supports only PEM format with PKCS#8 keys. If the key is encrypted, key password must be specified using 'ssl.key.password'

    Type:password
    Default:null
    Valid Values:
    Importance:medium
    Update Mode:per-broker
  • ssl.keystore.location

    The location of the key store file. This is optional for client and can be used for two-way authentication for client.

    Type:string
    Default:null
    Valid Values:
    Importance:medium
    Update Mode:per-broker
  • ssl.keystore.password

    The store password for the key store file. This is optional for client and only needed if 'ssl.keystore.location' is configured. Key store password is not supported for PEM format.

    Type:password
    Default:null
    Valid Values:
    Importance:medium
    Update Mode:per-broker
  • ssl.keystore.type

    The file format of the key store file. This is optional for client. The values currently supported by the default `ssl.engine.factory.class` are [JKS, PKCS12, PEM].

    Type:string
    Default:JKS
    Valid Values:
    Importance:medium
    Update Mode:per-broker
  • ssl.protocol

    The SSL protocol used to generate the SSLContext. The default is 'TLSv1.3' when running with Java 11 or newer, 'TLSv1.2' otherwise. This value should be fine for most use cases. Allowed values in recent JVMs are 'TLSv1.2' and 'TLSv1.3'. 'TLS', 'TLSv1.1', 'SSL', 'SSLv2' and 'SSLv3' may be supported in older JVMs, but their usage is discouraged due to known security vulnerabilities. With the default value for this config and 'ssl.enabled.protocols', clients will downgrade to 'TLSv1.2' if the server does not support 'TLSv1.3'. If this config is set to 'TLSv1.2', clients will not use 'TLSv1.3' even if it is one of the values in ssl.enabled.protocols and the server only supports 'TLSv1.3'.

    Type:string
    Default:TLSv1.3
    Valid Values:
    Importance:medium
    Update Mode:per-broker
  • ssl.provider

    The name of the security provider used for SSL connections. Default value is the default security provider of the JVM.

    Type:string
    Default:null
    Valid Values:
    Importance:medium
    Update Mode:per-broker
  • ssl.trustmanager.algorithm

    The algorithm used by trust manager factory for SSL connections. Default value is the trust manager factory algorithm configured for the Java Virtual Machine.

    Type:string
    Default:PKIX
    Valid Values:
    Importance:medium
    Update Mode:per-broker
  • ssl.truststore.certificates

    Trusted certificates in the format specified by 'ssl.truststore.type'. Default SSL engine factory supports only PEM format with X.509 certificates.

    Type:password
    Default:null
    Valid Values:
    Importance:medium
    Update Mode:per-broker
  • ssl.truststore.location

    The location of the trust store file.

    Type:string
    Default:null
    Valid Values:
    Importance:medium
    Update Mode:per-broker
  • ssl.truststore.password

    The password for the trust store file. If a password is not set, trust store file configured will still be used, but integrity checking is disabled. Trust store password is not supported for PEM format.

    Type:password
    Default:null
    Valid Values:
    Importance:medium
    Update Mode:per-broker
  • ssl.truststore.type

    The file format of the trust store file. The values currently supported by the default `ssl.engine.factory.class` are [JKS, PKCS12, PEM].

    Type:string
    Default:JKS
    Valid Values:
    Importance:medium
    Update Mode:per-broker
  • zookeeper.clientCnxnSocket

    Typically set to when using TLS connectivity to ZooKeeper. Overrides any explicit value set via the same-named system property.org.apache.zookeeper.ClientCnxnSocketNettyzookeeper.clientCnxnSocket

    Type:string
    Default:null
    Valid Values:
    Importance:medium
    Update Mode:read-only
  • zookeeper.ssl.client.enable

    Set client to use TLS when connecting to ZooKeeper. An explicit value overrides any value set via the system property (note the different name). Defaults to false if neither is set; when true, must be set (typically to ); other values to set may include , , , , , , , , , , , zookeeper.client.securezookeeper.clientCnxnSocketorg.apache.zookeeper.ClientCnxnSocketNettyzookeeper.ssl.cipher.suiteszookeeper.ssl.crl.enablezookeeper.ssl.enabled.protocolszookeeper.ssl.endpoint.identification.algorithmzookeeper.ssl.keystore.locationzookeeper.ssl.keystore.passwordzookeeper.ssl.keystore.typezookeeper.ssl.ocsp.enablezookeeper.ssl.protocolzookeeper.ssl.truststore.locationzookeeper.ssl.truststore.passwordzookeeper.ssl.truststore.type

    Type:boolean
    Default:false
    Valid Values:
    Importance:medium
    Update Mode:read-only
  • zookeeper.ssl.keystore.location

    Keystore location when using a client-side certificate with TLS connectivity to ZooKeeper. Overrides any explicit value set via the system property (note the camelCase).zookeeper.ssl.keyStore.location

    Type:string
    Default:null
    Valid Values:
    Importance:medium
    Update Mode:read-only
  • zookeeper.ssl.keystore.password

    Keystore password when using a client-side certificate with TLS connectivity to ZooKeeper. Overrides any explicit value set via the system property (note the camelCase). Note that ZooKeeper does not support a key password different from the keystore password, so be sure to set the key password in the keystore to be identical to the keystore password; otherwise the connection attempt to Zookeeper will fail.zookeeper.ssl.keyStore.password

    Type:password
    Default:null
    Valid Values:
    Importance:medium
    Update Mode:read-only
  • zookeeper.ssl.keystore.type

    Keystore type when using a client-side certificate with TLS connectivity to ZooKeeper. Overrides any explicit value set via the system property (note the camelCase). The default value of means the type will be auto-detected based on the filename extension of the keystore.zookeeper.ssl.keyStore.typenull

    Type:string
    Default:null
    Valid Values:
    Importance:medium
    Update Mode:read-only
  • zookeeper.ssl.truststore.location

    Truststore location when using TLS connectivity to ZooKeeper. Overrides any explicit value set via the system property (note the camelCase).zookeeper.ssl.trustStore.location

    Type:string
    Default:null
    Valid Values:
    Importance:medium
    Update Mode:read-only
  • zookeeper.ssl.truststore.password

    Truststore password when using TLS connectivity to ZooKeeper. Overrides any explicit value set via the system property (note the camelCase).zookeeper.ssl.trustStore.password

    Type:password
    Default:null
    Valid Values:
    Importance:medium
    Update Mode:read-only
  • zookeeper.ssl.truststore.type

    Truststore type when using TLS connectivity to ZooKeeper. Overrides any explicit value set via the system property (note the camelCase). The default value of means the type will be auto-detected based on the filename extension of the truststore.zookeeper.ssl.trustStore.typenull

    Type:string
    Default:null
    Valid Values:
    Importance:medium
    Update Mode:read-only
  • alter.config.policy.class.name

    The alter configs policy class that should be used for validation. The class should implement the interface.org.apache.kafka.server.policy.AlterConfigPolicy

    Type:class
    Default:null
    Valid Values:
    Importance:low
    Update Mode:read-only
  • alter.log.dirs.replication.quota.window.num

    The number of samples to retain in memory for alter log dirs replication quotas

    Type:int
    Default:11
    Valid Values:[1,...]
    Importance:low
    Update Mode:read-only
  • alter.log.dirs.replication.quota.window.size.seconds

    The time span of each sample for alter log dirs replication quotas

    Type:int
    Default:1
    Valid Values:[1,...]
    Importance:low
    Update Mode:read-only
  • authorizer.class.name

    The fully qualified name of a class that implements interface, which is used by the broker for authorization.org.apache.kafka.server.authorizer.Authorizer

    Type:string
    Default:""
    Valid Values:non-null string
    Importance:low
    Update Mode:read-only
  • auto.include.jmx.reporter

    Deprecated. Whether to automatically include JmxReporter even if it's not listed in . This configuration will be removed in Kafka 4.0, users should instead include in in order to enable the JmxReporter.metric.reportersorg.apache.kafka.common.metrics.JmxReportermetric.reporters

    Type:boolean
    Default:true
    Valid Values:
    Importance:low
    Update Mode:read-only
  • client.quota.callback.class

    The fully qualified name of a class that implements the ClientQuotaCallback interface, which is used to determine quota limits applied to client requests. By default, the <user> and <client-id> quotas that are stored in ZooKeeper are applied. For any given request, the most specific quota that matches the user principal of the session and the client-id of the request is applied.

    Type:class
    Default:null
    Valid Values:
    Importance:low
    Update Mode:read-only
  • connection.failed.authentication.delay.ms

    Connection close delay on failed authentication: this is the time (in milliseconds) by which connection close will be delayed on authentication failure. This must be configured to be less than connections.max.idle.ms to prevent connection timeout.

    Type:int
    Default:100
    Valid Values:[0,...]
    Importance:low
    Update Mode:read-only
  • controller.quorum.retry.backoff.ms

    The amount of time to wait before attempting to retry a failed request to a given topic partition. This avoids repeatedly sending requests in a tight loop under some failure scenarios.

    Type:int
    Default:20
    Valid Values:
    Importance:low
    Update Mode:read-only
  • controller.quota.window.num

    The number of samples to retain in memory for controller mutation quotas

    Type:int
    Default:11
    Valid Values:[1,...]
    Importance:low
    Update Mode:read-only
  • controller.quota.window.size.seconds

    The time span of each sample for controller mutations quotas

    Type:int
    Default:1
    Valid Values:[1,...]
    Importance:low
    Update Mode:read-only
  • create.topic.policy.class.name

    The create topic policy class that should be used for validation. The class should implement the interface.org.apache.kafka.server.policy.CreateTopicPolicy

    Type:class
    Default:null
    Valid Values:
    Importance:low
    Update Mode:read-only
  • delegation.token.expiry.check.interval.ms

    Scan interval to remove expired delegation tokens.

    Type:long
    Default:3600000 (1 hour)
    Valid Values:[1,...]
    Importance:low
    Update Mode:read-only
  • kafka.metrics.polling.interval.secs

    The metrics polling interval (in seconds) which can be used in kafka.metrics.reporters implementations.

    Type:int
    Default:10
    Valid Values:[1,...]
    Importance:low
    Update Mode:read-only
  • kafka.metrics.reporters

    A list of classes to use as Yammer metrics custom reporters. The reporters should implement trait. If a client wants to expose JMX operations on a custom reporter, the custom reporter needs to additionally implement an MBean trait that extends trait so that the registered MBean is compliant with the standard MBean convention.kafka.metrics.KafkaMetricsReporterkafka.metrics.KafkaMetricsReporterMBean

    Type:list
    Default:""
    Valid Values:
    Importance:low
    Update Mode:read-only
  • listener.security.protocol.map

    Map between listener names and security protocols. This must be defined for the same security protocol to be usable in more than one port or IP. For example, internal and external traffic can be separated even if SSL is required for both. Concretely, the user could define listeners with names INTERNAL and EXTERNAL and this property as: `INTERNAL:SSL,EXTERNAL:SSL`. As shown, key and value are separated by a colon and map entries are separated by commas. Each listener name should only appear once in the map. Different security (SSL and SASL) settings can be configured for each listener by adding a normalised prefix (the listener name is lowercased) to the config name. For example, to set a different keystore for the INTERNAL listener, a config with name would be set. If the config for the listener name is not set, the config will fallback to the generic config (i.e. ). Note that in KRaft a default mapping from the listener names defined by to PLAINTEXT is assumed if no explicit mapping is provided and no other security protocol is in use.listener.name.internal.ssl.keystore.locationssl.keystore.locationcontroller.listener.names

    Type:string
    Default:PLAINTEXT:PLAINTEXT,SSL:SSL,SASL_PLAINTEXT:SASL_PLAINTEXT,SASL_SSL:SASL_SSL
    Valid Values:
    Importance:low
    Update Mode:per-broker
  • log.message.downconversion.enable

    This configuration controls whether down-conversion of message formats is enabled to satisfy consume requests. When set to , broker will not perform down-conversion for consumers expecting an older message format. The broker responds with error for consume requests from such older clients. This configurationdoes not apply to any message format conversion that might be required for replication to followers.falseUNSUPPORTED_VERSION

    Type:boolean
    Default:true
    Valid Values:
    Importance:low
    Update Mode:cluster-wide
  • metadata.max.idle.interval.ms

    This configuration controls how often the active controller should write no-op records to the metadata partition. If the value is 0, no-op records are not appended to the metadata partition. The default value is 500

    Type:int
    Default:500
    Valid Values:[0,...]
    Importance:low
    Update Mode:read-only
  • metric.reporters

    A list of classes to use as metrics reporters. Implementing the interface allows plugging in classes that will be notified of new metric creation. The JmxReporter is always included to register JMX statistics.org.apache.kafka.common.metrics.MetricsReporter

    Type:list
    Default:""
    Valid Values:
    Importance:low
    Update Mode:cluster-wide
  • metrics.num.samples

    The number of samples maintained to compute metrics.

    Type:int
    Default:2
    Valid Values:[1,...]
    Importance:low
    Update Mode:read-only
  • metrics.recording.level

    The highest recording level for metrics.

    Type:string
    Default:INFO
    Valid Values:
    Importance:low
    Update Mode:read-only
  • metrics.sample.window.ms

    The window of time a metrics sample is computed over.

    Type:long
    Default:30000 (30 seconds)
    Valid Values:[1,...]
    Importance:low
    Update Mode:read-only
  • password.encoder.cipher.algorithm

    The Cipher algorithm used for encoding dynamically configured passwords.

    Type:string
    Default:AES/CBC/PKCS5Padding
    Valid Values:
    Importance:low
    Update Mode:read-only
  • password.encoder.iterations

    The iteration count used for encoding dynamically configured passwords.

    Type:int
    Default:4096
    Valid Values:[1024,...]
    Importance:low
    Update Mode:read-only
  • password.encoder.key.length

    The key length used for encoding dynamically configured passwords.

    Type:int
    Default:128
    Valid Values:[8,...]
    Importance:low
    Update Mode:read-only
  • password.encoder.keyfactory.algorithm

    The SecretKeyFactory algorithm used for encoding dynamically configured passwords. Default is PBKDF2WithHmacSHA512 if available and PBKDF2WithHmacSHA1 otherwise.

    Type:string
    Default:null
    Valid Values:
    Importance:low
    Update Mode:read-only
  • producer.id.expiration.ms

    The time in ms that a topic partition leader will wait before expiring producer IDs. Producer IDs will not expire while a transaction associated to them is still ongoing. Note that producer IDs may expire sooner if the last write from the producer ID is deleted due to the topic's retention settings. Setting this value the same or higher than can help prevent expiration during retries and protect against message duplication, but the default should be reasonable for most use cases.delivery.timeout.ms

    Type:int
    Default:86400000 (1 day)
    Valid Values:[1,...]
    Importance:low
    Update Mode:cluster-wide
  • quota.window.num

    The number of samples to retain in memory for client quotas

    Type:int
    Default:11
    Valid Values:[1,...]
    Importance:low
    Update Mode:read-only
  • quota.window.size.seconds

    The time span of each sample for client quotas

    Type:int
    Default:1
    Valid Values:[1,...]
    Importance:low
    Update Mode:read-only
  • replication.quota.window.num

    The number of samples to retain in memory for replication quotas

    Type:int
    Default:11
    Valid Values:[1,...]
    Importance:low
    Update Mode:read-only
  • replication.quota.window.size.seconds

    The time span of each sample for replication quotas

    Type:int
    Default:1
    Valid Values:[1,...]
    Importance:low
    Update Mode:read-only
  • sasl.login.connect.timeout.ms

    The (optional) value in milliseconds for the external authentication provider connection timeout. Currently applies only to OAUTHBEARER.

    Type:int
    Default:null
    Valid Values:
    Importance:low
    Update Mode:read-only
  • sasl.login.read.timeout.ms

    The (optional) value in milliseconds for the external authentication provider read timeout. Currently applies only to OAUTHBEARER.

    Type:int
    Default:null
    Valid Values:
    Importance:low
    Update Mode:read-only
  • sasl.login.retry.backoff.max.ms

    The (optional) value in milliseconds for the maximum wait between login attempts to the external authentication provider. Login uses an exponential backoff algorithm with an initial wait based on the sasl.login.retry.backoff.ms setting and will double in wait length between attempts up to a maximum wait length specified by the sasl.login.retry.backoff.max.ms setting. Currently applies only to OAUTHBEARER.

    Type:long
    Default:10000 (10 seconds)
    Valid Values:
    Importance:low
    Update Mode:read-only
  • sasl.login.retry.backoff.ms

    The (optional) value in milliseconds for the initial wait between login attempts to the external authentication provider. Login uses an exponential backoff algorithm with an initial wait based on the sasl.login.retry.backoff.ms setting and will double in wait length between attempts up to a maximum wait length specified by the sasl.login.retry.backoff.max.ms setting. Currently applies only to OAUTHBEARER.

    Type:long
    Default:100
    Valid Values:
    Importance:low
    Update Mode:read-only
  • sasl.oauthbearer.clock.skew.seconds

    The (optional) value in seconds to allow for differences between the time of the OAuth/OIDC identity provider and the broker.

    Type:int
    Default:30
    Valid Values:
    Importance:low
    Update Mode:read-only
  • sasl.oauthbearer.expected.audience

    The (optional) comma-delimited setting for the broker to use to verify that the JWT was issued for one of the expected audiences. The JWT will be inspected for the standard OAuth "aud" claim and if this value is set, the broker will match the value from JWT's "aud" claim to see if there is an exact match. If there is no match, the broker will reject the JWT and authentication will fail.

    Type:list
    Default:null
    Valid Values:
    Importance:low
    Update Mode:read-only
  • sasl.oauthbearer.expected.issuer

    The (optional) setting for the broker to use to verify that the JWT was created by the expected issuer. The JWT will be inspected for the standard OAuth "iss" claim and if this value is set, the broker will match it exactly against what is in the JWT's "iss" claim. If there is no match, the broker will reject the JWT and authentication will fail.

    Type:string
    Default:null
    Valid Values:
    Importance:low
    Update Mode:read-only
  • sasl.oauthbearer.jwks.endpoint.refresh.ms

    The (optional) value in milliseconds for the broker to wait between refreshing its JWKS (JSON Web Key Set) cache that contains the keys to verify the signature of the JWT.

    Type:long
    Default:3600000 (1 hour)
    Valid Values:
    Importance:low
    Update Mode:read-only
  • sasl.oauthbearer.jwks.endpoint.retry.backoff.max.ms

    The (optional) value in milliseconds for the maximum wait between attempts to retrieve the JWKS (JSON Web Key Set) from the external authentication provider. JWKS retrieval uses an exponential backoff algorithm with an initial wait based on the sasl.oauthbearer.jwks.endpoint.retry.backoff.ms setting and will double in wait length between attempts up to a maximum wait length specified by the sasl.oauthbearer.jwks.endpoint.retry.backoff.max.ms setting.

    Type:long
    Default:10000 (10 seconds)
    Valid Values:
    Importance:low
    Update Mode:read-only
  • sasl.oauthbearer.jwks.endpoint.retry.backoff.ms

    The (optional) value in milliseconds for the initial wait between JWKS (JSON Web Key Set) retrieval attempts from the external authentication provider. JWKS retrieval uses an exponential backoff algorithm with an initial wait based on the sasl.oauthbearer.jwks.endpoint.retry.backoff.ms setting and will double in wait length between attempts up to a maximum wait length specified by the sasl.oauthbearer.jwks.endpoint.retry.backoff.max.ms setting.

    Type:long
    Default:100
    Valid Values:
    Importance:low
    Update Mode:read-only
  • sasl.oauthbearer.scope.claim.name

    The OAuth claim for the scope is often named "scope", but this (optional) setting can provide a different name to use for the scope included in the JWT payload's claims if the OAuth/OIDC provider uses a different name for that claim.

    Type:string
    Default:scope
    Valid Values:
    Importance:low
    Update Mode:read-only
  • sasl.oauthbearer.sub.claim.name

    The OAuth claim for the subject is often named "sub", but this (optional) setting can provide a different name to use for the subject included in the JWT payload's claims if the OAuth/OIDC provider uses a different name for that claim.

    Type:string
    Default:sub
    Valid Values:
    Importance:low
    Update Mode:read-only
  • security.providers

    A list of configurable creator classes each returning a provider implementing security algorithms. These classes should implement the interface.org.apache.kafka.common.security.auth.SecurityProviderCreator

    Type:string
    Default:null
    Valid Values:
    Importance:low
    Update Mode:read-only
  • ssl.endpoint.identification.algorithm

    The endpoint identification algorithm to validate server hostname using server certificate.

    Type:string
    Default:https
    Valid Values:
    Importance:low
    Update Mode:per-broker
  • ssl.engine.factory.class

    The class of type org.apache.kafka.common.security.auth.SslEngineFactory to provide SSLEngine objects. Default value is org.apache.kafka.common.security.ssl.DefaultSslEngineFactory

    Type:class
    Default:null
    Valid Values:
    Importance:low
    Update Mode:per-broker
  • ssl.principal.mapping.rules

    A list of rules for mapping from distinguished name from the client certificate to short name. The rules are evaluated in order and the first rule that matches a principal name is used to map it to a short name. Any later rules in the list are ignored. By default, distinguished name of the X.500 certificate will be the principal. For more details on the format please see security authorization and acls. Note that this configuration is ignored if an extension of KafkaPrincipalBuilder is provided by the configuration.principal.builder.class

    Type:string
    Default:DEFAULT
    Valid Values:
    Importance:low
    Update Mode:read-only
  • ssl.secure.random.implementation

    The SecureRandom PRNG implementation to use for SSL cryptography operations.

    Type:string
    Default:null
    Valid Values:
    Importance:low
    Update Mode:per-broker
  • transaction.abort.timed.out.transaction.cleanup.interval.ms

    The interval at which to rollback transactions that have timed out

    Type:int
    Default:10000 (10 seconds)
    Valid Values:[1,...]
    Importance:low
    Update Mode:read-only
  • transaction.remove.expired.transaction.cleanup.interval.ms

    The interval at which to remove transactions that have expired due to passingtransactional.id.expiration.ms

    Type:int
    Default:3600000 (1 hour)
    Valid Values:[1,...]
    Importance:low
    Update Mode:read-only
  • zookeeper.ssl.cipher.suites

    Specifies the enabled cipher suites to be used in ZooKeeper TLS negotiation (csv). Overrides any explicit value set via the system property (note the single word "ciphersuites"). The default value of means the list of enabled cipher suites is determined by the Java runtime being used.zookeeper.ssl.ciphersuitesnull

    Type:list
    Default:null
    Valid Values:
    Importance:low
    Update Mode:read-only
  • zookeeper.ssl.crl.enable

    Specifies whether to enable Certificate Revocation List in the ZooKeeper TLS protocols. Overrides any explicit value set via the system property (note the shorter name).zookeeper.ssl.crl

    Type:boolean
    Default:false
    Valid Values:
    Importance:low
    Update Mode:read-only
  • zookeeper.ssl.enabled.protocols

    Specifies the enabled protocol(s) in ZooKeeper TLS negotiation (csv). Overrides any explicit value set via the system property (note the camelCase). The default value of means the enabled protocol will be the value of the configuration property.zookeeper.ssl.enabledProtocolsnullzookeeper.ssl.protocol

    Type:list
    Default:null
    Valid Values:
    Importance:low
    Update Mode:read-only
  • zookeeper.ssl.endpoint.identification.algorithm

    Specifies whether to enable hostname verification in the ZooKeeper TLS negotiation process, with (case-insensitively) "https" meaning ZooKeeper hostname verification is enabled and an explicit blank value meaning it is disabled (disabling it is only recommended for testing purposes). An explicit value overrides any "true" or "false" value set via the system property (note the different name and values; true implies https and false implies blank).zookeeper.ssl.hostnameVerification

    Type:string
    Default:HTTPS
    Valid Values:
    Importance:low
    Update Mode:read-only
  • zookeeper.ssl.ocsp.enable

    Specifies whether to enable Online Certificate Status Protocol in the ZooKeeper TLS protocols. Overrides any explicit value set via the system property (note the shorter name).zookeeper.ssl.ocsp

    Type:boolean
    Default:false
    Valid Values:
    Importance:low
    Update Mode:read-only
  • zookeeper.ssl.protocol

    Specifies the protocol to be used in ZooKeeper TLS negotiation. An explicit value overrides any value set via the same-named system property.zookeeper.ssl.protocol

    Type:string
    Default:TLSv1.2
    Valid Values:
    Importance:low
    Update Mode:read-only

More details about broker configuration can be found in the scala class .kafka.server.KafkaConfig

3.1.1 Updating Broker Configs

From Kafka version 1.1 onwards, some of the broker configs can be updated without restarting the broker. See the column in Broker Configs for the update mode of each broker config. Dynamic Update Mode
  • read-only: Requires a broker restart for update
  • per-broker: May be updated dynamically for each broker
  • cluster-wide: May be updated dynamically as a cluster-wide default. May also be updated as a per-broker value for testing.
To alter the current broker configs for broker id 0 (for example, the number of log cleaner threads): To describe the current dynamic broker configs for broker id 0: To delete a config override and revert to the statically configured or default value for broker id 0 (for example, the number of log cleaner threads): Some configs may be configured as a cluster-wide default to maintain consistent values across the whole cluster. All brokers in the cluster will process the cluster default update. For example, to update log cleaner threads on all brokers: To describe the currently configured dynamic cluster-wide default configs: All configs that are configurable at cluster level may also be configured at per-broker level (e.g. for testing). If a config value is defined at different levels, the following order of precedence is used:
> bin/kafka-configs.sh --bootstrap-server localhost:9092 --entity-type brokers --entity-name 0 --alter --add-config log.cleaner.threads=2
> bin/kafka-configs.sh --bootstrap-server localhost:9092 --entity-type brokers --entity-name 0 --describe
> bin/kafka-configs.sh --bootstrap-server localhost:9092 --entity-type brokers --entity-name 0 --alter --delete-config log.cleaner.threads
> bin/kafka-configs.sh --bootstrap-server localhost:9092 --entity-type brokers --entity-default --alter --add-config log.cleaner.threads=2
> bin/kafka-configs.sh --bootstrap-server localhost:9092 --entity-type brokers --entity-default --describe
  • Dynamic per-broker config stored in ZooKeeper
  • Dynamic cluster-wide default config stored in ZooKeeper
  • Static broker config from server.properties
  • Kafka default, see broker configs
Updating Password Configs Dynamically

Password config values that are dynamically updated are encrypted before storing in ZooKeeper. The broker config must be configured in to enable dynamic update of password configs. The secret may be different on different brokers.password.encoder.secretserver.properties

The secret used for password encoding may be rotated with a rolling restart of brokers. The old secret used for encoding passwords currently in ZooKeeper must be provided in the static broker config and the new secret must be provided in . All dynamic password configs stored in ZooKeeper will be re-encoded with the new secret when the broker starts up.password.encoder.old.secretpassword.encoder.secret

In Kafka 1.1.x, all dynamically updated password configs must be provided in every alter request when updating configs using even if the password config is not being altered. This constraint will be removed in a future release.kafka-configs.sh

Updating Password Configs in ZooKeeper Before Starting Brokers
From Kafka 2.0.0 onwards, enables dynamic broker configs to be updated using ZooKeeper before starting brokers for bootstrapping. This enables all password configs to be stored in encrypted form, avoiding the need for clear passwords in . The broker config must also be specified if any password configs are included in the alter command. Additional encryption parameters may also be specified. Password encoder configs will not be persisted in ZooKeeper. For example, to store SSL key password for listener on broker 0: The configuration will be persisted in ZooKeeper in encrypted form using the provided encoder configs. The encoder secret and iterations are not persisted in ZooKeeper. kafka-configs.shserver.propertiespassword.encoder.secretINTERNAL
> bin/kafka-configs.sh --zookeeper localhost:2182 --zk-tls-config-file zk_tls_config.properties --entity-type brokers --entity-name 0 --alter --add-config
    'listener.name.internal.ssl.key.password=key-password,password.encoder.secret=secret,password.encoder.iterations=8192'
listener.name.internal.ssl.key.password
Updating SSL Keystore of an Existing Listener
Brokers may be configured with SSL keystores with short validity periods to reduce the risk of compromised certificates. Keystores may be updated dynamically without restarting the broker. The config name must be prefixed with the listener prefix so that only the keystore config of a specific listener is updated. The following configs may be updated in a single alter request at per-broker level: listener.name.{listenerName}.
  • ssl.keystore.type
  • ssl.keystore.location
  • ssl.keystore.password
  • ssl.key.password
If the listener is the inter-broker listener, the update is allowed only if the new keystore is trusted by the truststore configured for that listener. For other listeners, no trust validation is performed on the keystore by the broker. Certificates must be signed by the same certificate authority that signed the old certificate to avoid any client authentication failures.
Updating SSL Truststore of an Existing Listener
Broker truststores may be updated dynamically without restarting the broker to add or remove certificates. Updated truststore will be used to authenticate new client connections. The config name must be prefixed with the listener prefix so that only the truststore config of a specific listener is updated. The following configs may be updated in a single alter request at per-broker level: listener.name.{listenerName}.
  • ssl.truststore.type
  • ssl.truststore.location
  • ssl.truststore.password
If the listener is the inter-broker listener, the update is allowed only if the existing keystore for that listener is trusted by the new truststore. For other listeners, no trust validation is performed by the broker before the update. Removal of CA certificates used to sign client certificates from the new truststore can lead to client authentication failures.
Updating Default Topic Configuration
Default topic configuration options used by brokers may be updated without broker restart. The configs are applied to topics without a topic config override for the equivalent per-topic config. One or more of these configs may be overridden at cluster-default level used by all brokers.
  • log.segment.bytes
  • log.roll.ms
  • log.roll.hours
  • log.roll.jitter.ms
  • log.roll.jitter.hours
  • log.index.size.max.bytes
  • log.flush.interval.messages
  • log.flush.interval.ms
  • log.retention.bytes
  • log.retention.ms
  • log.retention.minutes
  • log.retention.hours
  • log.index.interval.bytes
  • log.cleaner.delete.retention.ms
  • log.cleaner.min.compaction.lag.ms
  • log.cleaner.max.compaction.lag.ms
  • log.cleaner.min.cleanable.ratio
  • log.cleanup.policy
  • log.segment.delete.delay.ms
  • unclean.leader.election.enable
  • min.insync.replicas
  • max.message.bytes
  • compression.type
  • log.preallocate
  • log.message.timestamp.type
  • log.message.timestamp.difference.max.ms
From Kafka version 2.0.0 onwards, unclean leader election is automatically enabled by the controller when the config is dynamically updated. In Kafka version 1.1.x, changes to take effect only when a new controller is elected. Controller re-election may be forced by running: unclean.leader.election.enableunclean.leader.election.enable
> bin/zookeeper-shell.sh localhost
  rmr /controller
Updating Log Cleaner Configs
Log cleaner configs may be updated dynamically at cluster-default level used by all brokers. The changes take effect on the next iteration of log cleaning. One or more of these configs may be updated:
  • log.cleaner.threads
  • log.cleaner.io.max.bytes.per.second
  • log.cleaner.dedupe.buffer.size
  • log.cleaner.io.buffer.size
  • log.cleaner.io.buffer.load.factor
  • log.cleaner.backoff.ms
Updating Thread Configs
The size of various thread pools used by the broker may be updated dynamically at cluster-default level used by all brokers. Updates are restricted to the range to to ensure that config updates are handled gracefully. currentSize / 2currentSize * 2
  • num.network.threads
  • num.io.threads
  • num.replica.fetchers
  • num.recovery.threads.per.data.dir
  • log.cleaner.threads
  • background.threads
Updating ConnectionQuota Configs
The maximum number of connections allowed for a given IP/host by the broker may be updated dynamically at cluster-default level used by all brokers. The changes will apply for new connection creations and the existing connections count will be taken into account by the new limits.
  • max.connections.per.ip
  • max.connections.per.ip.overrides
Adding and Removing Listeners

Listeners may be added or removed dynamically. When a new listener is added, security configs of the listener must be provided as listener configs with the listener prefix . If the new listener uses SASL, the JAAS configuration of the listener must be provided using the JAAS configuration property with the listener and mechanism prefix. See JAAS configuration for Kafka brokers for details.listener.name.{listenerName}.sasl.jaas.config

In Kafka version 1.1.x, the listener used by the inter-broker listener may not be updated dynamically. To update the inter-broker listener to a new listener, the new listener may be added on all brokers without restarting the broker. A rolling restart is then required to update .inter.broker.listener.name

In addition to all the security configs of new listeners, the following configs may be updated dynamically at per-broker level:
  • listeners
  • advertised.listeners
  • listener.security.protocol.map
Inter-broker listener must be configured using the static broker configuration or . inter.broker.listener.namesecurity.inter.broker.protocol

3.2 Topic-Level Configs

Configurations pertinent to topics have both a server default as well an optional per-topic override. If no per-topic configuration is given the server default is used. The override can be set at topic creation time by giving one or more options. This example creates a topic named my-topic with a custom max message size and flush rate: Overrides can also be changed or set later using the alter configs command. This example updates the max message size for my-topic: To check overrides set on the topic you can do To remove an override you can do The following are the topic-level configurations. The server's default configuration for this property is given under the Server Default Property heading. A given server default config value only applies to a topic if it does not have an explicit topic config override. --config
> bin/kafka-topics.sh --bootstrap-server localhost:9092 --create --topic my-topic --partitions 1 \
  --replication-factor 1 --config max.message.bytes=64000 --config flush.messages=1
> bin/kafka-configs.sh --bootstrap-server localhost:9092 --entity-type topics --entity-name my-topic
  --alter --add-config max.message.bytes=128000
> bin/kafka-configs.sh --bootstrap-server localhost:9092 --entity-type topics --entity-name my-topic --describe
> bin/kafka-configs.sh --bootstrap-server localhost:9092  --entity-type topics --entity-name my-topic
  --alter --delete-config max.message.bytes
  • cleanup.policy

    This config designates the retention policy to use on log segments. The "delete" policy (which is the default) will discard old segments when their retention time or size limit has been reached. The "compact" policy will enable log compaction, which retains the latest value for each key. It is also possible to specify both policies in a comma-separated list (e.g. "delete,compact"). In this case, old segments will be discarded per the retention time and size configuration, while retained segments will be compacted.

    Type:list
    Default:delete
    Valid Values:[compact, delete]
    Server Default Property:log.cleanup.policy
    Importance:medium
  • compression.type

    Specify the final compression type for a given topic. This configuration accepts the standard compression codecs ('gzip', 'snappy', 'lz4', 'zstd'). It additionally accepts 'uncompressed' which is equivalent to no compression; and 'producer' which means retain the original compression codec set by the producer.

    Type:string
    Default:producer
    Valid Values:[uncompressed, zstd, lz4, snappy, gzip, producer]
    Server Default Property:compression.type
    Importance:medium
  • delete.retention.ms

    The amount of time to retain delete tombstone markers for log compacted topics. This setting also gives a bound on the time in which a consumer must complete a read if they begin from offset 0 to ensure that they get a valid snapshot of the final stage (otherwise delete tombstones may be collected before they complete their scan).

    Type:long
    Default:86400000 (1 day)
    Valid Values:[0,...]
    Server Default Property:log.cleaner.delete.retention.ms
    Importance:medium
  • file.delete.delay.ms

    The time to wait before deleting a file from the filesystem

    Type:long
    Default:60000 (1 minute)
    Valid Values:[0,...]
    Server Default Property:log.segment.delete.delay.ms
    Importance:medium
  • flush.messages

    This setting allows specifying an interval at which we will force an fsync of data written to the log. For example if this was set to 1 we would fsync after every message; if it were 5 we would fsync after every five messages. In general we recommend you not set this and use replication for durability and allow the operating system's background flush capabilities as it is more efficient. This setting can be overridden on a per-topic basis (see the per-topic configuration section).

    Type:long
    Default:9223372036854775807
    Valid Values:[1,...]
    Server Default Property:log.flush.interval.messages
    Importance:medium
  • flush.ms

    This setting allows specifying a time interval at which we will force an fsync of data written to the log. For example if this was set to 1000 we would fsync after 1000 ms had passed. In general we recommend you not set this and use replication for durability and allow the operating system's background flush capabilities as it is more efficient.

    Type:long
    Default:9223372036854775807
    Valid Values:[0,...]
    Server Default Property:log.flush.interval.ms
    Importance:medium
  • follower.replication.throttled.replicas

    A list of replicas for which log replication should be throttled on the follower side. The list should describe a set of replicas in the form [PartitionId]:[BrokerId],[PartitionId]:[BrokerId]:... or alternatively the wildcard '*' can be used to throttle all replicas for this topic.

    Type:list
    Default:""
    Valid Values:[partitionId]:[brokerId],[partitionId]:[brokerId],...
    Server Default Property:null
    Importance:medium
  • index.interval.bytes

    This setting controls how frequently Kafka adds an index entry to its offset index. The default setting ensures that we index a message roughly every 4096 bytes. More indexing allows reads to jump closer to the exact position in the log but makes the index larger. You probably don't need to change this.

    Type:int
    Default:4096 (4 kibibytes)
    Valid Values:[0,...]
    Server Default Property:log.index.interval.bytes
    Importance:medium
  • leader.replication.throttled.replicas

    A list of replicas for which log replication should be throttled on the leader side. The list should describe a set of replicas in the form [PartitionId]:[BrokerId],[PartitionId]:[BrokerId]:... or alternatively the wildcard '*' can be used to throttle all replicas for this topic.

    Type:list
    Default:""
    Valid Values:[partitionId]:[brokerId],[partitionId]:[brokerId],...
    Server Default Property:null
    Importance:medium
  • max.compaction.lag.ms

    The maximum time a message will remain ineligible for compaction in the log. Only applicable for logs that are being compacted.

    Type:long
    Default:9223372036854775807
    Valid Values:[1,...]
    Server Default Property:log.cleaner.max.compaction.lag.ms
    Importance:medium
  • max.message.bytes

    The largest record batch size allowed by Kafka (after compression if compression is enabled). If this is increased and there are consumers older than 0.10.2, the consumers' fetch size must also be increased so that they can fetch record batches this large. In the latest message format version, records are always grouped into batches for efficiency. In previous message format versions, uncompressed records are not grouped into batches and this limit only applies to a single record in that case.

    Type:int
    Default:1048588
    Valid Values:[0,...]
    Server Default Property:message.max.bytes
    Importance:medium
  • message.format.version

    [DEPRECATED] Specify the message format version the broker will use to append messages to the logs. The value of this config is always assumed to be `3.0` if `inter.broker.protocol.version` is 3.0 or higher (the actual config value is ignored). Otherwise, the value should be a valid ApiVersion. Some examples are: 0.10.0, 1.1, 2.8, 3.0. By setting a particular message format version, the user is certifying that all the existing messages on disk are smaller or equal than the specified version. Setting this value incorrectly will cause consumers with older versions to break as they will receive messages with a format that they don't understand.

    Type:string
    Default:3.0-IV1
    Valid Values:[0.8.0, 0.8.1, 0.8.2, 0.9.0, 0.10.0-IV0, 0.10.0-IV1, 0.10.1-IV0, 0.10.1-IV1, 0.10.1-IV2, 0.10.2-IV0, 0.11.0-IV0, 0.11.0-IV1, 0.11.0-IV2, 1.0-IV0, 1.1-IV0, 2.0-IV0, 2.0-IV1, 2.1-IV0, 2.1-IV1, 2.1-IV2, 2.2-IV0, 2.2-IV1, 2.3-IV0, 2.3-IV1, 2.4-IV0, 2.4-IV1, 2.5-IV0, 2.6-IV0, 2.7-IV0, 2.7-IV1, 2.7-IV2, 2.8-IV0, 2.8-IV1, 3.0-IV0, 3.0-IV1, 3.1-IV0, 3.2-IV0, 3.3-IV0, 3.3-IV1, 3.3-IV2, 3.3-IV3, 3.4-IV0, 3.5-IV0, 3.5-IV1, 3.5-IV2]
    Server Default Property:log.message.format.version
    Importance:medium
  • message.timestamp.difference.max.ms

    The maximum difference allowed between the timestamp when a broker receives a message and the timestamp specified in the message. If message.timestamp.type=CreateTime, a message will be rejected if the difference in timestamp exceeds this threshold. This configuration is ignored if message.timestamp.type=LogAppendTime.

    Type:long
    Default:9223372036854775807
    Valid Values:[0,...]
    Server Default Property:log.message.timestamp.difference.max.ms
    Importance:medium
  • message.timestamp.type

    Define whether the timestamp in the message is message create time or log append time. The value should be either `CreateTime` or `LogAppendTime`

    Type:string
    Default:CreateTime
    Valid Values:[CreateTime, LogAppendTime]
    Server Default Property:log.message.timestamp.type
    Importance:medium
  • min.cleanable.dirty.ratio

    This configuration controls how frequently the log compactor will attempt to clean the log (assuming log compaction is enabled). By default we will avoid cleaning a log where more than 50% of the log has been compacted. This ratio bounds the maximum space wasted in the log by duplicates (at 50% at most 50% of the log could be duplicates). A higher ratio will mean fewer, more efficient cleanings but will mean more wasted space in the log. If the max.compaction.lag.ms or the min.compaction.lag.ms configurations are also specified, then the log compactor considers the log to be eligible for compaction as soon as either: (i) the dirty ratio threshold has been met and the log has had dirty (uncompacted) records for at least the min.compaction.lag.ms duration, or (ii) if the log has had dirty (uncompacted) records for at most the max.compaction.lag.ms period.

    Type:double
    Default:0.5
    Valid Values:[0,...,1]
    Server Default Property:log.cleaner.min.cleanable.ratio
    Importance:medium
  • min.compaction.lag.ms

    The minimum time a message will remain uncompacted in the log. Only applicable for logs that are being compacted.

    Type:long
    Default:0
    Valid Values:[0,...]
    Server Default Property:log.cleaner.min.compaction.lag.ms
    Importance:medium
  • min.insync.replicas

    When a producer sets acks to "all" (or "-1"), this configuration specifies the minimum number of replicas that must acknowledge a write for the write to be considered successful. If this minimum cannot be met, then the producer will raise an exception (either NotEnoughReplicas or NotEnoughReplicasAfterAppend).
    When used together, and allow you to enforce greater durability guarantees. A typical scenario would be to create a topic with a replication factor of 3, set to 2, and produce with of "all". This will ensure that the producer raises an exception if a majority of replicas do not receive a write.
    min.insync.replicasacksmin.insync.replicasacks

    Type:int
    Default:1
    Valid Values:[1,...]
    Server Default Property:min.insync.replicas
    Importance:medium
  • preallocate

    True if we should preallocate the file on disk when creating a new log segment.

    Type:boolean
    Default:false
    Valid Values:
    Server Default Property:log.preallocate
    Importance:medium
  • retention.bytes

    This configuration controls the maximum size a partition (which consists of log segments) can grow to before we will discard old log segments to free up space if we are using the "delete" retention policy. By default there is no size limit only a time limit. Since this limit is enforced at the partition level, multiply it by the number of partitions to compute the topic retention in bytes.

    Type:long
    Default:-1
    Valid Values:
    Server Default Property:log.retention.bytes
    Importance:medium
  • retention.ms

    This configuration controls the maximum time we will retain a log before we will discard old log segments to free up space if we are using the "delete" retention policy. This represents an SLA on how soon consumers must read their data. If set to -1, no time limit is applied.

    Type:long
    Default:604800000 (7 days)
    Valid Values:[-1,...]
    Server Default Property:log.retention.ms
    Importance:medium
  • segment.bytes

    This configuration controls the segment file size for the log. Retention and cleaning is always done a file at a time so a larger segment size means fewer files but less granular control over retention.

    Type:int
    Default:1073741824 (1 gibibyte)
    Valid Values:[14,...]
    Server Default Property:log.segment.bytes
    Importance:medium
  • segment.index.bytes

    This configuration controls the size of the index that maps offsets to file positions. We preallocate this index file and shrink it only after log rolls. You generally should not need to change this setting.

    Type:int
    Default:10485760 (10 mebibytes)
    Valid Values:[4,...]
    Server Default Property:log.index.size.max.bytes
    Importance:medium
  • segment.jitter.ms

    The maximum random jitter subtracted from the scheduled segment roll time to avoid thundering herds of segment rolling

    Type:long
    Default:0
    Valid Values:[0,...]
    Server Default Property:log.roll.jitter.ms
    Importance:medium
  • segment.ms

    This configuration controls the period of time after which Kafka will force the log to roll even if the segment file isn't full to ensure that retention can delete or compact old data.

    Type:long
    Default:604800000 (7 days)
    Valid Values:[1,...]
    Server Default Property:log.roll.ms
    Importance:medium
  • unclean.leader.election.enable

    Indicates whether to enable replicas not in the ISR set to be elected as leader as a last resort, even though doing so may result in data loss.

    Type:boolean
    Default:false
    Valid Values:
    Server Default Property:unclean.leader.election.enable
    Importance:medium
  • message.downconversion.enable

    This configuration controls whether down-conversion of message formats is enabled to satisfy consume requests. When set to , broker will not perform down-conversion for consumers expecting an older message format. The broker responds with error for consume requests from such older clients. This configurationdoes not apply to any message format conversion that might be required for replication to followers.falseUNSUPPORTED_VERSION

    Type:boolean
    Default:true
    Valid Values:
    Server Default Property:log.message.downconversion.enable
    Importance:low

3.3 Producer Configs

Below is the configuration of the producer:
  • key.serializer

    Serializer class for key that implements the interface.org.apache.kafka.common.serialization.Serializer

    Type:class
    Default:
    Valid Values:
    Importance:high
  • value.serializer

    Serializer class for value that implements the interface.org.apache.kafka.common.serialization.Serializer

    Type:class
    Default:
    Valid Values:
    Importance:high
  • bootstrap.servers

    A list of host/port pairs to use for establishing the initial connection to the Kafka cluster. The client will make use of all servers irrespective of which servers are specified here for bootstrapping—this list only impacts the initial hosts used to discover the full set of servers. This list should be in the form . Since these servers are just used for the initial connection to discover the full cluster membership (which may change dynamically), this list need not contain the full set of servers (you may want more than one, though, in case a server is down).host1:port1,host2:port2,...

    Type:list
    Default:""
    Valid Values:non-null string
    Importance:high
  • buffer.memory

    The total bytes of memory the producer can use to buffer records waiting to be sent to the server. If records are sent faster than they can be delivered to the server the producer will block for after which it will throw an exception.max.block.ms

    This setting should correspond roughly to the total memory the producer will use, but is not a hard bound since not all memory the producer uses is used for buffering. Some additional memory will be used for compression (if compression is enabled) as well as for maintaining in-flight requests.

    Type:long
    Default:33554432
    Valid Values:[0,...]
    Importance:high
  • compression.type

    The compression type for all data generated by the producer. The default is none (i.e. no compression). Valid values are , , , , or . Compression is of full batches of data, so the efficacy of batching will also impact the compression ratio (more batching means better compression).nonegzipsnappylz4zstd

    Type:string
    Default:none
    Valid Values:[none, gzip, snappy, lz4, zstd]
    Importance:high
  • retries

    Setting a value greater than zero will cause the client to resend any record whose send fails with a potentially transient error. Note that this retry is no different than if the client resent the record upon receiving the error. Produce requests will be failed before the number of retries has been exhausted if the timeout configured by expires first before successful acknowledgement. Users should generally prefer to leave this config unset and instead use to control retry behavior.delivery.timeout.msdelivery.timeout.ms

    Enabling idempotence requires this config value to be greater than 0. If conflicting configurations are set and idempotence is not explicitly enabled, idempotence is disabled.

    Allowing retries while setting to and to greater than 1 will potentially change the ordering of records because if two batches are sent to a single partition, and the first fails and is retried but the second succeeds, then the records in the second batch may appear first.enable.idempotencefalsemax.in.flight.requests.per.connection

    Type:int
    Default:2147483647
    Valid Values:[0,...,2147483647]
    Importance:high
  • ssl.key.password

    The password of the private key in the key store file or the PEM key specified in 'ssl.keystore.key'.

    Type:password
    Default:null
    Valid Values:
    Importance:high
  • ssl.keystore.certificate.chain

    Certificate chain in the format specified by 'ssl.keystore.type'. Default SSL engine factory supports only PEM format with a list of X.509 certificates

    Type:password
    Default:null
    Valid Values:
    Importance:high
  • ssl.keystore.key

    Private key in the format specified by 'ssl.keystore.type'. Default SSL engine factory supports only PEM format with PKCS#8 keys. If the key is encrypted, key password must be specified using 'ssl.key.password'

    Type:password
    Default:null
    Valid Values:
    Importance:high
  • ssl.keystore.location

    The location of the key store file. This is optional for client and can be used for two-way authentication for client.

    Type:string
    Default:null
    Valid Values:
    Importance:high
  • ssl.keystore.password

    The store password for the key store file. This is optional for client and only needed if 'ssl.keystore.location' is configured. Key store password is not supported for PEM format.

    Type:password
    Default:null
    Valid Values:
    Importance:high
  • ssl.truststore.certificates

    Trusted certificates in the format specified by 'ssl.truststore.type'. Default SSL engine factory supports only PEM format with X.509 certificates.

    Type:password
    Default:null
    Valid Values:
    Importance:high
  • ssl.truststore.location

    The location of the trust store file.

    Type:string
    Default:null
    Valid Values:
    Importance:high
  • ssl.truststore.password

    The password for the trust store file. If a password is not set, trust store file configured will still be used, but integrity checking is disabled. Trust store password is not supported for PEM format.

    Type:password
    Default:null
    Valid Values:
    Importance:high
  • batch.size

    The producer will attempt to batch records together into fewer requests whenever multiple records are being sent to the same partition. This helps performance on both the client and the server. This configuration controls the default batch size in bytes.

    No attempt will be made to batch records larger than this size.

    Requests sent to brokers will contain multiple batches, one for each partition with data available to be sent.

    A small batch size will make batching less common and may reduce throughput (a batch size of zero will disable batching entirely). A very large batch size may use memory a bit more wastefully as we will always allocate a buffer of the specified batch size in anticipation of additional records.

    Note: This setting gives the upper bound of the batch size to be sent. If we have fewer than this many bytes accumulated for this partition, we will 'linger' for the time waiting for more records to show up. This setting defaults to 0, which means we'll immediately send out a record even the accumulated batch size is under this setting.linger.mslinger.msbatch.size

    Type:int
    Default:16384
    Valid Values:[0,...]
    Importance:medium
  • client.dns.lookup

    Controls how the client uses DNS lookups. If set to , connect to each returned IP address in sequence until a successful connection is established. After a disconnection, the next IP is used. Once all IPs have been used once, the client resolves the IP(s) from the hostname again (both the JVM and the OS cache DNS name lookups, however). If set to , resolve each bootstrap address into a list of canonical names. After the bootstrap phase, this behaves the same as .use_all_dns_ipsresolve_canonical_bootstrap_servers_onlyuse_all_dns_ips

    Type:string
    Default:use_all_dns_ips
    Valid Values:[use_all_dns_ips, resolve_canonical_bootstrap_servers_only]
    Importance:medium
  • client.id

    An id string to pass to the server when making requests. The purpose of this is to be able to track the source of requests beyond just ip/port by allowing a logical application name to be included in server-side request logging.

    Type:string
    Default:""
    Valid Values:
    Importance:medium
  • connections.max.idle.ms

    Close idle connections after the number of milliseconds specified by this config.

    Type:long
    Default:540000 (9 minutes)
    Valid Values:
    Importance:medium
  • delivery.timeout.ms

    An upper bound on the time to report success or failure after a call to returns. This limits the total time that a record will be delayed prior to sending, the time to await acknowledgement from the broker (if expected), and the time allowed for retriable send failures. The producer may report failure to send a record earlier than this config if either an unrecoverable error is encountered, the retries have been exhausted, or the record is added to a batch which reached an earlier delivery expiration deadline. The value of this config should be greater than or equal to the sum of and .send()request.timeout.mslinger.ms

    Type:int
    Default:120000 (2 minutes)
    Valid Values:[0,...]
    Importance:medium
  • linger.ms

    The producer groups together any records that arrive in between request transmissions into a single batched request. Normally this occurs only under load when records arrive faster than they can be sent out. However in some circumstances the client may want to reduce the number of requests even under moderate load. This setting accomplishes this by adding a small amount of artificial delay—that is, rather than immediately sending out a record, the producer will wait for up to the given delay to allow other records to be sent so that the sends can be batched together. This can be thought of as analogous to Nagle's algorithm in TCP. This setting gives the upper bound on the delay for batching: once we get worth of records for a partition it will be sent immediately regardless of this setting, however if we have fewer than this many bytes accumulated for this partition we will 'linger' for the specified time waiting for more records to show up. This setting defaults to 0 (i.e. no delay). Setting , for example, would have the effect of reducing the number of requests sent but would add up to 5ms of latency to records sent in the absence of load.batch.sizelinger.ms=5

    Type:long
    Default:0
    Valid Values:[0,...]
    Importance:medium
  • max.block.ms

    The configuration controls how long the 's , , , , and methods will block. For this timeout bounds the total time waiting for both metadata fetch and buffer allocation (blocking in the user-supplied serializers or partitioner is not counted against this timeout). For this timeout bounds the time spent waiting for metadata if it is unavailable. The transaction-related methods always block, but may timeout if the transaction coordinator could not be discovered or did not respond within the timeout.KafkaProducersend()partitionsFor()initTransactions()sendOffsetsToTransaction()commitTransaction()abortTransaction()send()partitionsFor()

    Type:long
    Default:60000 (1 minute)
    Valid Values:[0,...]
    Importance:medium
  • max.request.size

    The maximum size of a request in bytes. This setting will limit the number of record batches the producer will send in a single request to avoid sending huge requests. This is also effectively a cap on the maximum uncompressed record batch size. Note that the server has its own cap on the record batch size (after compression if compression is enabled) which may be different from this.

    Type:int
    Default:1048576
    Valid Values:[0,...]
    Importance:medium
  • partitioner.class

    A class to use to determine which partition to be send to when produce the records. Available options are:

    • If not set, the default partitioning logic is used. This strategy will try sticking to a partition until at least batch.size bytes is produced to the partition. It works with the strategy:
      • If no partition is specified but a key is present, choose a partition based on a hash of the key
      • If no partition or key is present, choose the sticky partition that changes when at least batch.size bytes are produced to the partition.
    • org.apache.kafka.clients.producer.RoundRobinPartitioner: This partitioning strategy is that each record in a series of consecutive records will be sent to a different partition(no matter if the 'key' is provided or not), until we run out of partitions and start over again. Note: There's a known issue that will cause uneven distribution when new batch is created. Please check KAFKA-9965 for more detail.

    Implementing the interface allows you to plug in a custom partitioner.org.apache.kafka.clients.producer.Partitioner

    Type:class
    Default:null
    Valid Values:
    Importance:medium
  • partitioner.ignore.keys

    When set to 'true' the producer won't use record keys to choose a partition. If 'false', producer would choose a partition based on a hash of the key when a key is present. Note: this setting has no effect if a custom partitioner is used.

    Type:boolean
    Default:false
    Valid Values:
    Importance:medium
  • receive.buffer.bytes

    The size of the TCP receive buffer (SO_RCVBUF) to use when reading data. If the value is -1, the OS default will be used.

    Type:int
    Default:32768 (32 kibibytes)
    Valid Values:[-1,...]
    Importance:medium
  • request.timeout.ms

    The configuration controls the maximum amount of time the client will wait for the response of a request. If the response is not received before the timeout elapses the client will resend the request if necessary or fail the request if retries are exhausted. This should be larger than (a broker configuration) to reduce the possibility of message duplication due to unnecessary producer retries.replica.lag.time.max.ms

    Type:int
    Default:30000 (30 seconds)
    Valid Values:[0,...]
    Importance:medium
  • sasl.client.callback.handler.class

    The fully qualified name of a SASL client callback handler class that implements the AuthenticateCallbackHandler interface.

    Type:class
    Default:null
    Valid Values:
    Importance:medium
  • sasl.jaas.config

    JAAS login context parameters for SASL connections in the format used by JAAS configuration files. JAAS configuration file format is described here. The format for the value is: . For brokers, the config must be prefixed with listener prefix and SASL mechanism name in lower-case. For example, listener.name.sasl_ssl.scram-sha-256.sasl.jaas.config=com.example.ScramLoginModule required;loginModuleClass controlFlag (optionName=optionValue)*;

    Type:password
    Default:null
    Valid Values:
    Importance:medium
  • sasl.kerberos.service.name

    The Kerberos principal name that Kafka runs as. This can be defined either in Kafka's JAAS config or in Kafka's config.

    Type:string
    Default:null
    Valid Values:
    Importance:medium
  • sasl.login.callback.handler.class

    The fully qualified name of a SASL login callback handler class that implements the AuthenticateCallbackHandler interface. For brokers, login callback handler config must be prefixed with listener prefix and SASL mechanism name in lower-case. For example, listener.name.sasl_ssl.scram-sha-256.sasl.login.callback.handler.class=com.example.CustomScramLoginCallbackHandler

    Type:class
    Default:null
    Valid Values:
    Importance:medium
  • sasl.login.class

    The fully qualified name of a class that implements the Login interface. For brokers, login config must be prefixed with listener prefix and SASL mechanism name in lower-case. For example, listener.name.sasl_ssl.scram-sha-256.sasl.login.class=com.example.CustomScramLogin

    Type:class
    Default:null
    Valid Values:
    Importance:medium
  • sasl.mechanism

    SASL mechanism used for client connections. This may be any mechanism for which a security provider is available. GSSAPI is the default mechanism.

    Type:string
    Default:GSSAPI
    Valid Values:
    Importance:medium
  • sasl.oauthbearer.jwks.endpoint.url

    The OAuth/OIDC provider URL from which the provider's JWKS (JSON Web Key Set) can be retrieved. The URL can be HTTP(S)-based or file-based. If the URL is HTTP(S)-based, the JWKS data will be retrieved from the OAuth/OIDC provider via the configured URL on broker startup. All then-current keys will be cached on the broker for incoming requests. If an authentication request is received for a JWT that includes a "kid" header claim value that isn't yet in the cache, the JWKS endpoint will be queried again on demand. However, the broker polls the URL every sasl.oauthbearer.jwks.endpoint.refresh.ms milliseconds to refresh the cache with any forthcoming keys before any JWT requests that include them are received. If the URL is file-based, the broker will load the JWKS file from a configured location on startup. In the event that the JWT includes a "kid" header value that isn't in the JWKS file, the broker will reject the JWT and authentication will fail.

    Type:string
    Default:null
    Valid Values:
    Importance:medium
  • sasl.oauthbearer.token.endpoint.url

    The URL for the OAuth/OIDC identity provider. If the URL is HTTP(S)-based, it is the issuer's token endpoint URL to which requests will be made to login based on the configuration in sasl.jaas.config. If the URL is file-based, it specifies a file containing an access token (in JWT serialized form) issued by the OAuth/OIDC identity provider to use for authorization.

    Type:string
    Default:null
    Valid Values:
    Importance:medium
  • security.protocol

    Protocol used to communicate with brokers. Valid values are: PLAINTEXT, SSL, SASL_PLAINTEXT, SASL_SSL.

    Type:string
    Default:PLAINTEXT
    Valid Values:(case insensitive) [SASL_SSL, PLAINTEXT, SSL, SASL_PLAINTEXT]
    Importance:medium
  • send.buffer.bytes

    The size of the TCP send buffer (SO_SNDBUF) to use when sending data. If the value is -1, the OS default will be used.

    Type:int
    Default:131072 (128 kibibytes)
    Valid Values:[-1,...]
    Importance:medium
  • socket.connection.setup.timeout.max.ms

    The maximum amount of time the client will wait for the socket connection to be established. The connection setup timeout will increase exponentially for each consecutive connection failure up to this maximum. To avoid connection storms, a randomization factor of 0.2 will be applied to the timeout resulting in a random range between 20% below and 20% above the computed value.

    Type:long
    Default:30000 (30 seconds)
    Valid Values:
    Importance:medium
  • socket.connection.setup.timeout.ms

    The amount of time the client will wait for the socket connection to be established. If the connection is not built before the timeout elapses, clients will close the socket channel.

    Type:long
    Default:10000 (10 seconds)
    Valid Values:
    Importance:medium
  • ssl.enabled.protocols

    The list of protocols enabled for SSL connections. The default is 'TLSv1.2,TLSv1.3' when running with Java 11 or newer, 'TLSv1.2' otherwise. With the default value for Java 11, clients and servers will prefer TLSv1.3 if both support it and fallback to TLSv1.2 otherwise (assuming both support at least TLSv1.2). This default should be fine for most cases. Also see the config documentation for `ssl.protocol`.

    Type:list
    Default:TLSv1.2,TLSv1.3
    Valid Values:
    Importance:medium
  • ssl.keystore.type

    The file format of the key store file. This is optional for client. The values currently supported by the default `ssl.engine.factory.class` are [JKS, PKCS12, PEM].

    Type:string
    Default:JKS
    Valid Values:
    Importance:medium
  • ssl.protocol

    The SSL protocol used to generate the SSLContext. The default is 'TLSv1.3' when running with Java 11 or newer, 'TLSv1.2' otherwise. This value should be fine for most use cases. Allowed values in recent JVMs are 'TLSv1.2' and 'TLSv1.3'. 'TLS', 'TLSv1.1', 'SSL', 'SSLv2' and 'SSLv3' may be supported in older JVMs, but their usage is discouraged due to known security vulnerabilities. With the default value for this config and 'ssl.enabled.protocols', clients will downgrade to 'TLSv1.2' if the server does not support 'TLSv1.3'. If this config is set to 'TLSv1.2', clients will not use 'TLSv1.3' even if it is one of the values in ssl.enabled.protocols and the server only supports 'TLSv1.3'.

    Type:string
    Default:TLSv1.3
    Valid Values:
    Importance:medium
  • ssl.provider

    The name of the security provider used for SSL connections. Default value is the default security provider of the JVM.

    Type:string
    Default:null
    Valid Values:
    Importance:medium
  • ssl.truststore.type

    The file format of the trust store file. The values currently supported by the default `ssl.engine.factory.class` are [JKS, PKCS12, PEM].

    Type:string
    Default:JKS
    Valid Values:
    Importance:medium
  • acks

    The number of acknowledgments the producer requires the leader to have received before considering a request complete. This controls the durability of records that are sent. The following settings are allowed:

    • acks=0 If set to zero then the producer will not wait for any acknowledgment from the server at all. The record will be immediately added to the socket buffer and considered sent. No guarantee can be made that the server has received the record in this case, and the configuration will not take effect (as the client won't generally know of any failures). The offset given back for each record will always be set to . retries-1
    • acks=1 This will mean the leader will write the record to its local log but will respond without awaiting full acknowledgement from all followers. In this case should the leader fail immediately after acknowledging the record but before the followers have replicated it then the record will be lost.
    • acks=all This means the leader will wait for the full set of in-sync replicas to acknowledge the record. This guarantees that the record will not be lost as long as at least one in-sync replica remains alive. This is the strongest available guarantee. This is equivalent to the acks=-1 setting.

    Note that enabling idempotence requires this config value to be 'all'. If conflicting configurations are set and idempotence is not explicitly enabled, idempotence is disabled.

    Type:string
    Default:all
    Valid Values:[all, -1, 0, 1]
    Importance:low
  • auto.include.jmx.reporter

    Deprecated. Whether to automatically include JmxReporter even if it's not listed in . This configuration will be removed in Kafka 4.0, users should instead include in in order to enable the JmxReporter.metric.reportersorg.apache.kafka.common.metrics.JmxReportermetric.reporters

    Type:boolean
    Default:true
    Valid Values:
    Importance:low
  • enable.idempotence

    When set to 'true', the producer will ensure that exactly one copy of each message is written in the stream. If 'false', producer retries due to broker failures, etc., may write duplicates of the retried message in the stream. Note that enabling idempotence requires to be less than or equal to 5 (with message ordering preserved for any allowable value), to be greater than 0, and must be 'all'. max.in.flight.requests.per.connectionretriesacks

    Idempotence is enabled by default if no conflicting configurations are set. If conflicting configurations are set and idempotence is not explicitly enabled, idempotence is disabled. If idempotence is explicitly enabled and conflicting configurations are set, a is thrown.ConfigException

    Type:boolean
    Default:true
    Valid Values:
    Importance:low
  • interceptor.classes

    A list of classes to use as interceptors. Implementing the interface allows you to intercept (and possibly mutate) the records received by the producer before they are published to the Kafka cluster. By default, there are no interceptors.org.apache.kafka.clients.producer.ProducerInterceptor

    Type:list
    Default:""
    Valid Values:non-null string
    Importance:low
  • max.in.flight.requests.per.connection

    The maximum number of unacknowledged requests the client will send on a single connection before blocking. Note that if this configuration is set to be greater than 1 and is set to false, there is a risk of message reordering after a failed send due to retries (i.e., if retries are enabled); if retries are disabled or if is set to true, ordering will be preserved. Additionally, enabling idempotence requires the value of this configuration to be less than or equal to 5. If conflicting configurations are set and idempotence is not explicitly enabled, idempotence is disabled. enable.idempotenceenable.idempotence

    Type:int
    Default:5
    Valid Values:[1,...]
    Importance:low
  • metadata.max.age.ms

    The period of time in milliseconds after which we force a refresh of metadata even if we haven't seen any partition leadership changes to proactively discover any new brokers or partitions.

    Type:long
    Default:300000 (5 minutes)
    Valid Values:[0,...]
    Importance:low
  • metadata.max.idle.ms

    Controls how long the producer will cache metadata for a topic that's idle. If the elapsed time since a topic was last produced to exceeds the metadata idle duration, then the topic's metadata is forgotten and the next access to it will force a metadata fetch request.

    Type:long
    Default:300000 (5 minutes)
    Valid Values:[5000,...]
    Importance:low
  • metric.reporters

    A list of classes to use as metrics reporters. Implementing the interface allows plugging in classes that will be notified of new metric creation. The JmxReporter is always included to register JMX statistics.org.apache.kafka.common.metrics.MetricsReporter

    Type:list
    Default:""
    Valid Values:non-null string
    Importance:low
  • metrics.num.samples

    The number of samples maintained to compute metrics.

    Type:int
    Default:2
    Valid Values:[1,...]
    Importance:low
  • metrics.recording.level

    The highest recording level for metrics.

    Type:string
    Default:INFO
    Valid Values:[INFO, DEBUG, TRACE]
    Importance:low
  • metrics.sample.window.ms

    The window of time a metrics sample is computed over.

    Type:long
    Default:30000 (30 seconds)
    Valid Values:[0,...]
    Importance:low
  • partitioner.adaptive.partitioning.enable

    When set to 'true', the producer will try to adapt to broker performance and produce more messages to partitions hosted on faster brokers. If 'false', producer will try to distribute messages uniformly. Note: this setting has no effect if a custom partitioner is used

    Type:boolean
    Default:true
    Valid Values:
    Importance:low
  • partitioner.availability.timeout.ms

    If a broker cannot process produce requests from a partition for time, the partitioner treats that partition as not available. If the value is 0, this logic is disabled. Note: this setting has no effect if a custom partitioner is used or is set to 'false'partitioner.availability.timeout.mspartitioner.adaptive.partitioning.enable

    Type:long
    Default:0
    Valid Values:[0,...]
    Importance:low
  • reconnect.backoff.max.ms

    The maximum amount of time in milliseconds to wait when reconnecting to a broker that has repeatedly failed to connect. If provided, the backoff per host will increase exponentially for each consecutive connection failure, up to this maximum. After calculating the backoff increase, 20% random jitter is added to avoid connection storms.

    Type:long
    Default:1000 (1 second)
    Valid Values:[0,...]
    Importance:low
  • reconnect.backoff.ms

    The base amount of time to wait before attempting to reconnect to a given host. This avoids repeatedly connecting to a host in a tight loop. This backoff applies to all connection attempts by the client to a broker.

    Type:long
    Default:50
    Valid Values:[0,...]
    Importance:low
  • retry.backoff.ms

    The amount of time to wait before attempting to retry a failed request to a given topic partition. This avoids repeatedly sending requests in a tight loop under some failure scenarios.

    Type:long
    Default:100
    Valid Values:[0,...]
    Importance:low
  • sasl.kerberos.kinit.cmd

    Kerberos kinit command path.

    Type:string
    Default:/usr/bin/kinit
    Valid Values:
    Importance:low
  • sasl.kerberos.min.time.before.relogin

    Login thread sleep time between refresh attempts.

    Type:long
    Default:60000
    Valid Values:
    Importance:low
  • sasl.kerberos.ticket.renew.jitter

    Percentage of random jitter added to the renewal time.

    Type:double
    Default:0.05
    Valid Values:
    Importance:low
  • sasl.kerberos.ticket.renew.window.factor

    Login thread will sleep until the specified window factor of time from last refresh to ticket's expiry has been reached, at which time it will try to renew the ticket.

    Type:double
    Default:0.8
    Valid Values:
    Importance:low
  • sasl.login.connect.timeout.ms

    The (optional) value in milliseconds for the external authentication provider connection timeout. Currently applies only to OAUTHBEARER.

    Type:int
    Default:null
    Valid Values:
    Importance:low
  • sasl.login.read.timeout.ms

    The (optional) value in milliseconds for the external authentication provider read timeout. Currently applies only to OAUTHBEARER.

    Type:int
    Default:null
    Valid Values:
    Importance:low
  • sasl.login.refresh.buffer.seconds

    The amount of buffer time before credential expiration to maintain when refreshing a credential, in seconds. If a refresh would otherwise occur closer to expiration than the number of buffer seconds then the refresh will be moved up to maintain as much of the buffer time as possible. Legal values are between 0 and 3600 (1 hour); a default value of 300 (5 minutes) is used if no value is specified. This value and sasl.login.refresh.min.period.seconds are both ignored if their sum exceeds the remaining lifetime of a credential. Currently applies only to OAUTHBEARER.

    Type:short
    Default:300
    Valid Values:[0,...,3600]
    Importance:low
  • sasl.login.refresh.min.period.seconds

    The desired minimum time for the login refresh thread to wait before refreshing a credential, in seconds. Legal values are between 0 and 900 (15 minutes); a default value of 60 (1 minute) is used if no value is specified. This value and sasl.login.refresh.buffer.seconds are both ignored if their sum exceeds the remaining lifetime of a credential. Currently applies only to OAUTHBEARER.

    Type:short
    Default:60
    Valid Values:[0,...,900]
    Importance:low
  • sasl.login.refresh.window.factor

    Login refresh thread will sleep until the specified window factor relative to the credential's lifetime has been reached, at which time it will try to refresh the credential. Legal values are between 0.5 (50%) and 1.0 (100%) inclusive; a default value of 0.8 (80%) is used if no value is specified. Currently applies only to OAUTHBEARER.

    Type:double
    Default:0.8
    Valid Values:[0.5,...,1.0]
    Importance:low
  • sasl.login.refresh.window.jitter

    The maximum amount of random jitter relative to the credential's lifetime that is added to the login refresh thread's sleep time. Legal values are between 0 and 0.25 (25%) inclusive; a default value of 0.05 (5%) is used if no value is specified. Currently applies only to OAUTHBEARER.

    Type:double
    Default:0.05
    Valid Values:[0.0,...,0.25]
    Importance:low
  • sasl.login.retry.backoff.max.ms

    The (optional) value in milliseconds for the maximum wait between login attempts to the external authentication provider. Login uses an exponential backoff algorithm with an initial wait based on the sasl.login.retry.backoff.ms setting and will double in wait length between attempts up to a maximum wait length specified by the sasl.login.retry.backoff.max.ms setting. Currently applies only to OAUTHBEARER.

    Type:long
    Default:10000 (10 seconds)
    Valid Values:
    Importance:low
  • sasl.login.retry.backoff.ms

    The (optional) value in milliseconds for the initial wait between login attempts to the external authentication provider. Login uses an exponential backoff algorithm with an initial wait based on the sasl.login.retry.backoff.ms setting and will double in wait length between attempts up to a maximum wait length specified by the sasl.login.retry.backoff.max.ms setting. Currently applies only to OAUTHBEARER.

    Type:long
    Default:100
    Valid Values:
    Importance:low
  • sasl.oauthbearer.clock.skew.seconds

    The (optional) value in seconds to allow for differences between the time of the OAuth/OIDC identity provider and the broker.

    Type:int
    Default:30
    Valid Values:
    Importance:low
  • sasl.oauthbearer.expected.audience

    The (optional) comma-delimited setting for the broker to use to verify that the JWT was issued for one of the expected audiences. The JWT will be inspected for the standard OAuth "aud" claim and if this value is set, the broker will match the value from JWT's "aud" claim to see if there is an exact match. If there is no match, the broker will reject the JWT and authentication will fail.

    Type:list
    Default:null
    Valid Values:
    Importance:low
  • sasl.oauthbearer.expected.issuer

    The (optional) setting for the broker to use to verify that the JWT was created by the expected issuer. The JWT will be inspected for the standard OAuth "iss" claim and if this value is set, the broker will match it exactly against what is in the JWT's "iss" claim. If there is no match, the broker will reject the JWT and authentication will fail.

    Type:string
    Default:null
    Valid Values:
    Importance:low
  • sasl.oauthbearer.jwks.endpoint.refresh.ms

    The (optional) value in milliseconds for the broker to wait between refreshing its JWKS (JSON Web Key Set) cache that contains the keys to verify the signature of the JWT.

    Type:long
    Default:3600000 (1 hour)
    Valid Values:
    Importance:low
  • sasl.oauthbearer.jwks.endpoint.retry.backoff.max.ms

    The (optional) value in milliseconds for the maximum wait between attempts to retrieve the JWKS (JSON Web Key Set) from the external authentication provider. JWKS retrieval uses an exponential backoff algorithm with an initial wait based on the sasl.oauthbearer.jwks.endpoint.retry.backoff.ms setting and will double in wait length between attempts up to a maximum wait length specified by the sasl.oauthbearer.jwks.endpoint.retry.backoff.max.ms setting.

    Type:long
    Default:10000 (10 seconds)
    Valid Values:
    Importance:low
  • sasl.oauthbearer.jwks.endpoint.retry.backoff.ms

    The (optional) value in milliseconds for the initial wait between JWKS (JSON Web Key Set) retrieval attempts from the external authentication provider. JWKS retrieval uses an exponential backoff algorithm with an initial wait based on the sasl.oauthbearer.jwks.endpoint.retry.backoff.ms setting and will double in wait length between attempts up to a maximum wait length specified by the sasl.oauthbearer.jwks.endpoint.retry.backoff.max.ms setting.

    Type:long
    Default:100
    Valid Values:
    Importance:low
  • sasl.oauthbearer.scope.claim.name

    The OAuth claim for the scope is often named "scope", but this (optional) setting can provide a different name to use for the scope included in the JWT payload's claims if the OAuth/OIDC provider uses a different name for that claim.

    Type:string
    Default:scope
    Valid Values:
    Importance:low
  • sasl.oauthbearer.sub.claim.name

    The OAuth claim for the subject is often named "sub", but this (optional) setting can provide a different name to use for the subject included in the JWT payload's claims if the OAuth/OIDC provider uses a different name for that claim.

    Type:string
    Default:sub
    Valid Values:
    Importance:low
  • security.providers

    A list of configurable creator classes each returning a provider implementing security algorithms. These classes should implement the interface.org.apache.kafka.common.security.auth.SecurityProviderCreator

    Type:string
    Default:null
    Valid Values:
    Importance:low
  • ssl.cipher.suites

    A list of cipher suites. This is a named combination of authentication, encryption, MAC and key exchange algorithm used to negotiate the security settings for a network connection using TLS or SSL network protocol. By default all the available cipher suites are supported.

    Type:list
    Default:null
    Valid Values:
    Importance:low
  • ssl.endpoint.identification.algorithm

    The endpoint identification algorithm to validate server hostname using server certificate.

    Type:string
    Default:https
    Valid Values:
    Importance:low
  • ssl.engine.factory.class

    The class of type org.apache.kafka.common.security.auth.SslEngineFactory to provide SSLEngine objects. Default value is org.apache.kafka.common.security.ssl.DefaultSslEngineFactory

    Type:class
    Default:null
    Valid Values:
    Importance:low
  • ssl.keymanager.algorithm

    The algorithm used by key manager factory for SSL connections. Default value is the key manager factory algorithm configured for the Java Virtual Machine.

    Type:string
    Default:SunX509
    Valid Values:
    Importance:low
  • ssl.secure.random.implementation

    The SecureRandom PRNG implementation to use for SSL cryptography operations.

    Type:string
    Default:null
    Valid Values:
    Importance:low
  • ssl.trustmanager.algorithm

    The algorithm used by trust manager factory for SSL connections. Default value is the trust manager factory algorithm configured for the Java Virtual Machine.

    Type:string
    Default:PKIX
    Valid Values:
    Importance:low
  • transaction.timeout.ms

    The maximum amount of time in milliseconds that a transaction will remain open before the coordinator proactively aborts it. The start of the transaction is set at the time that the first partition is added to it. If this value is larger than the setting in the broker, the request will fail with a error.transaction.max.timeout.msInvalidTxnTimeoutException

    Type:int
    Default:60000 (1 minute)
    Valid Values:
    Importance:low
  • transactional.id

    The TransactionalId to use for transactional delivery. This enables reliability semantics which span multiple producer sessions since it allows the client to guarantee that transactions using the same TransactionalId have been completed prior to starting any new transactions. If no TransactionalId is provided, then the producer is limited to idempotent delivery. If a TransactionalId is configured, is implied. By default the TransactionId is not configured, which means transactions cannot be used. Note that, by default, transactions require a cluster of at least three brokers which is the recommended setting for production; for development you can change this, by adjusting broker setting .enable.idempotencetransaction.state.log.replication.factor

    Type:string
    Default:null
    Valid Values:non-empty string
    Importance:low

3.4 Consumer Configs

Below is the configuration for the consumer:
  • key.deserializer

    Deserializer class for key that implements the interface.org.apache.kafka.common.serialization.Deserializer

    Type:class
    Default:
    Valid Values:
    Importance:high
  • value.deserializer

    Deserializer class for value that implements the interface.org.apache.kafka.common.serialization.Deserializer

    Type:class
    Default:
    Valid Values:
    Importance:high
  • bootstrap.servers

    A list of host/port pairs to use for establishing the initial connection to the Kafka cluster. The client will make use of all servers irrespective of which servers are specified here for bootstrapping—this list only impacts the initial hosts used to discover the full set of servers. This list should be in the form . Since these servers are just used for the initial connection to discover the full cluster membership (which may change dynamically), this list need not contain the full set of servers (you may want more than one, though, in case a server is down).host1:port1,host2:port2,...

    Type:list
    Default:""
    Valid Values:non-null string
    Importance:high
  • fetch.min.bytes

    The minimum amount of data the server should return for a fetch request. If insufficient data is available the request will wait for that much data to accumulate before answering the request. The default setting of 1 byte means that fetch requests are answered as soon as that many byte(s) of data is available or the fetch request times out waiting for data to arrive. Setting this to a larger value will cause the server to wait for larger amounts of data to accumulate which can improve server throughput a bit at the cost of some additional latency.

    Type:int
    Default:1
    Valid Values:[0,...]
    Importance:high
  • group.id

    A unique string that identifies the consumer group this consumer belongs to. This property is required if the consumer uses either the group management functionality by using or the Kafka-based offset management strategy.subscribe(topic)

    Type:string
    Default:null
    Valid Values:
    Importance:high
  • heartbeat.interval.ms

    The expected time between heartbeats to the consumer coordinator when using Kafka's group management facilities. Heartbeats are used to ensure that the consumer's session stays active and to facilitate rebalancing when new consumers join or leave the group. The value must be set lower than , but typically should be set no higher than 1/3 of that value. It can be adjusted even lower to control the expected time for normal rebalances.session.timeout.ms

    Type:int
    Default:3000 (3 seconds)
    Valid Values:
    Importance:high
  • max.partition.fetch.bytes

    The maximum amount of data per-partition the server will return. Records are fetched in batches by the consumer. If the first record batch in the first non-empty partition of the fetch is larger than this limit, the batch will still be returned to ensure that the consumer can make progress. The maximum record batch size accepted by the broker is defined via (broker config) or (topic config). See fetch.max.bytes for limiting the consumer request size.message.max.bytesmax.message.bytes

    Type:int
    Default:1048576 (1 mebibyte)
    Valid Values:[0,...]
    Importance:high
  • session.timeout.ms

    The timeout used to detect client failures when using Kafka's group management facility. The client sends periodic heartbeats to indicate its liveness to the broker. If no heartbeats are received by the broker before the expiration of this session timeout, then the broker will remove this client from the group and initiate a rebalance. Note that the value must be in the allowable range as configured in the broker configuration by and .group.min.session.timeout.msgroup.max.session.timeout.ms

    Type:int
    Default:45000 (45 seconds)
    Valid Values:
    Importance:high
  • ssl.key.password

    The password of the private key in the key store file or the PEM key specified in 'ssl.keystore.key'.

    Type:password
    Default:null
    Valid Values:
    Importance:high
  • ssl.keystore.certificate.chain

    Certificate chain in the format specified by 'ssl.keystore.type'. Default SSL engine factory supports only PEM format with a list of X.509 certificates

    Type:password
    Default:null
    Valid Values:
    Importance:high
  • ssl.keystore.key

    Private key in the format specified by 'ssl.keystore.type'. Default SSL engine factory supports only PEM format with PKCS#8 keys. If the key is encrypted, key password must be specified using 'ssl.key.password'

    Type:password
    Default:null
    Valid Values:
    Importance:high
  • ssl.keystore.location

    The location of the key store file. This is optional for client and can be used for two-way authentication for client.

    Type:string
    Default:null
    Valid Values:
    Importance:high
  • ssl.keystore.password

    The store password for the key store file. This is optional for client and only needed if 'ssl.keystore.location' is configured. Key store password is not supported for PEM format.

    Type:password
    Default:null
    Valid Values:
    Importance:high
  • ssl.truststore.certificates

    Trusted certificates in the format specified by 'ssl.truststore.type'. Default SSL engine factory supports only PEM format with X.509 certificates.

    Type:password
    Default:null
    Valid Values:
    Importance:high
  • ssl.truststore.location

    The location of the trust store file.

    Type:string
    Default:null
    Valid Values:
    Importance:high
  • ssl.truststore.password

    The password for the trust store file. If a password is not set, trust store file configured will still be used, but integrity checking is disabled. Trust store password is not supported for PEM format.

    Type:password
    Default:null
    Valid Values:
    Importance:high
  • allow.auto.create.topics

    Allow automatic topic creation on the broker when subscribing to or assigning a topic. A topic being subscribed to will be automatically created only if the broker allows for it using `auto.create.topics.enable` broker configuration. This configuration must be set to `false` when using brokers older than 0.11.0

    Type:boolean
    Default:true
    Valid Values:
    Importance:medium
  • auto.offset.reset

    What to do when there is no initial offset in Kafka or if the current offset does not exist any more on the server (e.g. because that data has been deleted):

    • earliest: automatically reset the offset to the earliest offset
    • latest: automatically reset the offset to the latest offset
    • none: throw exception to the consumer if no previous offset is found for the consumer's group
    • anything else: throw exception to the consumer.

    Type:string
    Default:latest
    Valid Values:[latest, earliest, none]
    Importance:medium
  • client.dns.lookup

    Controls how the client uses DNS lookups. If set to , connect to each returned IP address in sequence until a successful connection is established. After a disconnection, the next IP is used. Once all IPs have been used once, the client resolves the IP(s) from the hostname again (both the JVM and the OS cache DNS name lookups, however). If set to , resolve each bootstrap address into a list of canonical names. After the bootstrap phase, this behaves the same as .use_all_dns_ipsresolve_canonical_bootstrap_servers_onlyuse_all_dns_ips

    Type:string
    Default:use_all_dns_ips
    Valid Values:[use_all_dns_ips, resolve_canonical_bootstrap_servers_only]
    Importance:medium
  • connections.max.idle.ms

    Close idle connections after the number of milliseconds specified by this config.

    Type:long
    Default:540000 (9 minutes)
    Valid Values:
    Importance:medium
  • default.api.timeout.ms

    Specifies the timeout (in milliseconds) for client APIs. This configuration is used as the default timeout for all client operations that do not specify a parameter.timeout

    Type:int
    Default:60000 (1 minute)
    Valid Values:[0,...]
    Importance:medium
  • enable.auto.commit

    If true the consumer's offset will be periodically committed in the background.

    Type:boolean
    Default:true
    Valid Values:
    Importance:medium
  • exclude.internal.topics

    Whether internal topics matching a subscribed pattern should be excluded from the subscription. It is always possible to explicitly subscribe to an internal topic.

    Type:boolean
    Default:true
    Valid Values:
    Importance:medium
  • fetch.max.bytes

    The maximum amount of data the server should return for a fetch request. Records are fetched in batches by the consumer, and if the first record batch in the first non-empty partition of the fetch is larger than this value, the record batch will still be returned to ensure that the consumer can make progress. As such, this is not a absolute maximum. The maximum record batch size accepted by the broker is defined via (broker config) or (topic config). Note that the consumer performs multiple fetches in parallel.message.max.bytesmax.message.bytes

    Type:int
    Default:52428800 (50 mebibytes)
    Valid Values:[0,...]
    Importance:medium
  • group.instance.id

    A unique identifier of the consumer instance provided by the end user. Only non-empty strings are permitted. If set, the consumer is treated as a static member, which means that only one instance with this ID is allowed in the consumer group at any time. This can be used in combination with a larger session timeout to avoid group rebalances caused by transient unavailability (e.g. process restarts). If not set, the consumer will join the group as a dynamic member, which is the traditional behavior.

    Type:string
    Default:null
    Valid Values:non-empty string
    Importance:medium
  • isolation.level

    Controls how to read messages written transactionally. If set to , consumer.poll() will only return transactional messages which have been committed. If set to (the default), consumer.poll() will return all messages, even transactional messages which have been aborted. Non-transactional messages will be returned unconditionally in either mode. read_committedread_uncommitted

    Messages will always be returned in offset order. Hence, in mode, consumer.poll() will only return messages up to the last stable offset (LSO), which is the one less than the offset of the first open transaction. In particular any messages appearing after messages belonging to ongoing transactions will be withheld until the relevant transaction has been completed. As a result, consumers will not be able to read up to the high watermark when there are in flight transactions.read_committedread_committed

    Further, when in the seekToEnd method will return the LSOread_committed

    Type:string
    Default:read_uncommitted
    Valid Values:[read_committed, read_uncommitted]
    Importance:medium
  • max.poll.interval.ms

    The maximum delay between invocations of poll() when using consumer group management. This places an upper bound on the amount of time that the consumer can be idle before fetching more records. If poll() is not called before expiration of this timeout, then the consumer is considered failed and the group will rebalance in order to reassign the partitions to another member. For consumers using a non-null which reach this timeout, partitions will not be immediately reassigned. Instead, the consumer will stop sending heartbeats and partitions will be reassigned after expiration of . This mirrors the behavior of a static consumer which has shutdown.group.instance.idsession.timeout.ms

    Type:int
    Default:300000 (5 minutes)
    Valid Values:[1,...]
    Importance:medium
  • max.poll.records

    The maximum number of records returned in a single call to poll(). Note, that does not impact the underlying fetching behavior. The consumer will cache the records from each fetch request and returns them incrementally from each poll.max.poll.records

    Type:int
    Default:500
    Valid Values:[1,...]
    Importance:medium
  • partition.assignment.strategy

    A list of class names or class types, ordered by preference, of supported partition assignment strategies that the client will use to distribute partition ownership amongst consumer instances when group management is used. Available options are:

    • org.apache.kafka.clients.consumer.RangeAssignor: Assigns partitions on a per-topic basis.
    • org.apache.kafka.clients.consumer.RoundRobinAssignor: Assigns partitions to consumers in a round-robin fashion.
    • org.apache.kafka.clients.consumer.StickyAssignor: Guarantees an assignment that is maximally balanced while preserving as many existing partition assignments as possible.
    • org.apache.kafka.clients.consumer.CooperativeStickyAssignor: Follows the same StickyAssignor logic, but allows for cooperative rebalancing.

    The default assignor is [RangeAssignor, CooperativeStickyAssignor], which will use the RangeAssignor by default, but allows upgrading to the CooperativeStickyAssignor with just a single rolling bounce that removes the RangeAssignor from the list.

    Implementing the interface allows you to plug in a custom assignment strategy.org.apache.kafka.clients.consumer.ConsumerPartitionAssignor

    Type:list
    Default:class org.apache.kafka.clients.consumer.RangeAssignor,class org.apache.kafka.clients.consumer.CooperativeStickyAssignor
    Valid Values:non-null string
    Importance:medium
  • receive.buffer.bytes

    The size of the TCP receive buffer (SO_RCVBUF) to use when reading data. If the value is -1, the OS default will be used.

    Type:int
    Default:65536 (64 kibibytes)
    Valid Values:[-1,...]
    Importance:medium
  • request.timeout.ms

    The configuration controls the maximum amount of time the client will wait for the response of a request. If the response is not received before the timeout elapses the client will resend the request if necessary or fail the request if retries are exhausted.

    Type:int
    Default:30000 (30 seconds)
    Valid Values:[0,...]
    Importance:medium
  • sasl.client.callback.handler.class

    The fully qualified name of a SASL client callback handler class that implements the AuthenticateCallbackHandler interface.

    Type:class
    Default:null
    Valid Values:
    Importance:medium
  • sasl.jaas.config

    JAAS login context parameters for SASL connections in the format used by JAAS configuration files. JAAS configuration file format is described here. The format for the value is: . For brokers, the config must be prefixed with listener prefix and SASL mechanism name in lower-case. For example, listener.name.sasl_ssl.scram-sha-256.sasl.jaas.config=com.example.ScramLoginModule required;loginModuleClass controlFlag (optionName=optionValue)*;

    Type:password
    Default:null
    Valid Values:
    Importance:medium
  • sasl.kerberos.service.name

    The Kerberos principal name that Kafka runs as. This can be defined either in Kafka's JAAS config or in Kafka's config.

    Type:string
    Default:null
    Valid Values:
    Importance:medium
  • sasl.login.callback.handler.class

    The fully qualified name of a SASL login callback handler class that implements the AuthenticateCallbackHandler interface. For brokers, login callback handler config must be prefixed with listener prefix and SASL mechanism name in lower-case. For example, listener.name.sasl_ssl.scram-sha-256.sasl.login.callback.handler.class=com.example.CustomScramLoginCallbackHandler

    Type:class
    Default:null
    Valid Values:
    Importance:medium
  • sasl.login.class

    The fully qualified name of a class that implements the Login interface. For brokers, login config must be prefixed with listener prefix and SASL mechanism name in lower-case. For example, listener.name.sasl_ssl.scram-sha-256.sasl.login.class=com.example.CustomScramLogin

    Type:class
    Default:null
    Valid Values:
    Importance:medium
  • sasl.mechanism

    SASL mechanism used for client connections. This may be any mechanism for which a security provider is available. GSSAPI is the default mechanism.

    Type:string
    Default:GSSAPI
    Valid Values:
    Importance:medium
  • sasl.oauthbearer.jwks.endpoint.url

    The OAuth/OIDC provider URL from which the provider's JWKS (JSON Web Key Set) can be retrieved. The URL can be HTTP(S)-based or file-based. If the URL is HTTP(S)-based, the JWKS data will be retrieved from the OAuth/OIDC provider via the configured URL on broker startup. All then-current keys will be cached on the broker for incoming requests. If an authentication request is received for a JWT that includes a "kid" header claim value that isn't yet in the cache, the JWKS endpoint will be queried again on demand. However, the broker polls the URL every sasl.oauthbearer.jwks.endpoint.refresh.ms milliseconds to refresh the cache with any forthcoming keys before any JWT requests that include them are received. If the URL is file-based, the broker will load the JWKS file from a configured location on startup. In the event that the JWT includes a "kid" header value that isn't in the JWKS file, the broker will reject the JWT and authentication will fail.

    Type:string
    Default:null
    Valid Values:
    Importance:medium
  • sasl.oauthbearer.token.endpoint.url

    The URL for the OAuth/OIDC identity provider. If the URL is HTTP(S)-based, it is the issuer's token endpoint URL to which requests will be made to login based on the configuration in sasl.jaas.config. If the URL is file-based, it specifies a file containing an access token (in JWT serialized form) issued by the OAuth/OIDC identity provider to use for authorization.

    Type:string
    Default:null
    Valid Values:
    Importance:medium
  • security.protocol

    Protocol used to communicate with brokers. Valid values are: PLAINTEXT, SSL, SASL_PLAINTEXT, SASL_SSL.

    Type:string
    Default:PLAINTEXT
    Valid Values:(case insensitive) [SASL_SSL, PLAINTEXT, SSL, SASL_PLAINTEXT]
    Importance:medium
  • send.buffer.bytes

    The size of the TCP send buffer (SO_SNDBUF) to use when sending data. If the value is -1, the OS default will be used.

    Type:int
    Default:131072 (128 kibibytes)
    Valid Values:[-1,...]
    Importance:medium
  • socket.connection.setup.timeout.max.ms

    The maximum amount of time the client will wait for the socket connection to be established. The connection setup timeout will increase exponentially for each consecutive connection failure up to this maximum. To avoid connection storms, a randomization factor of 0.2 will be applied to the timeout resulting in a random range between 20% below and 20% above the computed value.

    Type:long
    Default:30000 (30 seconds)
    Valid Values:
    Importance:medium
  • socket.connection.setup.timeout.ms

    The amount of time the client will wait for the socket connection to be established. If the connection is not built before the timeout elapses, clients will close the socket channel.

    Type:long
    Default:10000 (10 seconds)
    Valid Values:
    Importance:medium
  • ssl.enabled.protocols

    The list of protocols enabled for SSL connections. The default is 'TLSv1.2,TLSv1.3' when running with Java 11 or newer, 'TLSv1.2' otherwise. With the default value for Java 11, clients and servers will prefer TLSv1.3 if both support it and fallback to TLSv1.2 otherwise (assuming both support at least TLSv1.2). This default should be fine for most cases. Also see the config documentation for `ssl.protocol`.

    Type:list
    Default:TLSv1.2,TLSv1.3
    Valid Values:
    Importance:medium
  • ssl.keystore.type

    The file format of the key store file. This is optional for client. The values currently supported by the default `ssl.engine.factory.class` are [JKS, PKCS12, PEM].

    Type:string
    Default:JKS
    Valid Values:
    Importance:medium
  • ssl.protocol

    The SSL protocol used to generate the SSLContext. The default is 'TLSv1.3' when running with Java 11 or newer, 'TLSv1.2' otherwise. This value should be fine for most use cases. Allowed values in recent JVMs are 'TLSv1.2' and 'TLSv1.3'. 'TLS', 'TLSv1.1', 'SSL', 'SSLv2' and 'SSLv3' may be supported in older JVMs, but their usage is discouraged due to known security vulnerabilities. With the default value for this config and 'ssl.enabled.protocols', clients will downgrade to 'TLSv1.2' if the server does not support 'TLSv1.3'. If this config is set to 'TLSv1.2', clients will not use 'TLSv1.3' even if it is one of the values in ssl.enabled.protocols and the server only supports 'TLSv1.3'.

    Type:string
    Default:TLSv1.3
    Valid Values:
    Importance:medium
  • ssl.provider

    The name of the security provider used for SSL connections. Default value is the default security provider of the JVM.

    Type:string
    Default:null
    Valid Values:
    Importance:medium
  • ssl.truststore.type

    The file format of the trust store file. The values currently supported by the default `ssl.engine.factory.class` are [JKS, PKCS12, PEM].

    Type:string
    Default:JKS
    Valid Values:
    Importance:medium
  • auto.commit.interval.ms

    The frequency in milliseconds that the consumer offsets are auto-committed to Kafka if is set to .enable.auto.committrue

    Type:int
    Default:5000 (5 seconds)
    Valid Values:[0,...]
    Importance:low
  • auto.include.jmx.reporter

    Deprecated. Whether to automatically include JmxReporter even if it's not listed in . This configuration will be removed in Kafka 4.0, users should instead include in in order to enable the JmxReporter.metric.reportersorg.apache.kafka.common.metrics.JmxReportermetric.reporters

    Type:boolean
    Default:true
    Valid Values:
    Importance:low
  • check.crcs

    Automatically check the CRC32 of the records consumed. This ensures no on-the-wire or on-disk corruption to the messages occurred. This check adds some overhead, so it may be disabled in cases seeking extreme performance.

    Type:boolean
    Default:true
    Valid Values:
    Importance:low
  • client.id

    An id string to pass to the server when making requests. The purpose of this is to be able to track the source of requests beyond just ip/port by allowing a logical application name to be included in server-side request logging.

    Type:string
    Default:""
    Valid Values:
    Importance:low
  • client.rack

    A rack identifier for this client. This can be any string value which indicates where this client is physically located. It corresponds with the broker config 'broker.rack'

    Type:string
    Default:""
    Valid Values:
    Importance:low
  • fetch.max.wait.ms

    The maximum amount of time the server will block before answering the fetch request if there isn't sufficient data to immediately satisfy the requirement given by fetch.min.bytes.

    Type:int
    Default:500
    Valid Values:[0,...]
    Importance:low
  • interceptor.classes

    A list of classes to use as interceptors. Implementing the interface allows you to intercept (and possibly mutate) records received by the consumer. By default, there are no interceptors.org.apache.kafka.clients.consumer.ConsumerInterceptor

    Type:list
    Default:""
    Valid Values:non-null string
    Importance:low
  • metadata.max.age.ms

    The period of time in milliseconds after which we force a refresh of metadata even if we haven't seen any partition leadership changes to proactively discover any new brokers or partitions.

    Type:long
    Default:300000 (5 minutes)
    Valid Values:[0,...]
    Importance:low
  • metric.reporters

    A list of classes to use as metrics reporters. Implementing the interface allows plugging in classes that will be notified of new metric creation. The JmxReporter is always included to register JMX statistics.org.apache.kafka.common.metrics.MetricsReporter

    Type:list
    Default:""
    Valid Values:non-null string
    Importance:low
  • metrics.num.samples

    The number of samples maintained to compute metrics.

    Type:int
    Default:2
    Valid Values:[1,...]
    Importance:low
  • metrics.recording.level

    The highest recording level for metrics.

    Type:string
    Default:INFO
    Valid Values:[INFO, DEBUG, TRACE]
    Importance:low
  • metrics.sample.window.ms

    The window of time a metrics sample is computed over.

    Type:long
    Default:30000 (30 seconds)
    Valid Values:[0,...]
    Importance:low
  • reconnect.backoff.max.ms

    The maximum amount of time in milliseconds to wait when reconnecting to a broker that has repeatedly failed to connect. If provided, the backoff per host will increase exponentially for each consecutive connection failure, up to this maximum. After calculating the backoff increase, 20% random jitter is added to avoid connection storms.

    Type:long
    Default:1000 (1 second)
    Valid Values:[0,...]
    Importance:low
  • reconnect.backoff.ms

    The base amount of time to wait before attempting to reconnect to a given host. This avoids repeatedly connecting to a host in a tight loop. This backoff applies to all connection attempts by the client to a broker.

    Type:long
    Default:50
    Valid Values:[0,...]
    Importance:low
  • retry.backoff.ms

    The amount of time to wait before attempting to retry a failed request to a given topic partition. This avoids repeatedly sending requests in a tight loop under some failure scenarios.

    Type:long
    Default:100
    Valid Values:[0,...]
    Importance:low
  • sasl.kerberos.kinit.cmd

    Kerberos kinit command path.

    Type:string
    Default:/usr/bin/kinit
    Valid Values:
    Importance:low
  • sasl.kerberos.min.time.before.relogin

    Login thread sleep time between refresh attempts.

    Type:long
    Default:60000
    Valid Values:
    Importance:low
  • sasl.kerberos.ticket.renew.jitter

    Percentage of random jitter added to the renewal time.

    Type:double
    Default:0.05
    Valid Values:
    Importance:low
  • sasl.kerberos.ticket.renew.window.factor

    Login thread will sleep until the specified window factor of time from last refresh to ticket's expiry has been reached, at which time it will try to renew the ticket.

    Type:double
    Default:0.8
    Valid Values:
    Importance:low
  • sasl.login.connect.timeout.ms

    The (optional) value in milliseconds for the external authentication provider connection timeout. Currently applies only to OAUTHBEARER.

    Type:int
    Default:null
    Valid Values:
    Importance:low
  • sasl.login.read.timeout.ms

    The (optional) value in milliseconds for the external authentication provider read timeout. Currently applies only to OAUTHBEARER.

    Type:int
    Default:null
    Valid Values:
    Importance:low
  • sasl.login.refresh.buffer.seconds

    The amount of buffer time before credential expiration to maintain when refreshing a credential, in seconds. If a refresh would otherwise occur closer to expiration than the number of buffer seconds then the refresh will be moved up to maintain as much of the buffer time as possible. Legal values are between 0 and 3600 (1 hour); a default value of 300 (5 minutes) is used if no value is specified. This value and sasl.login.refresh.min.period.seconds are both ignored if their sum exceeds the remaining lifetime of a credential. Currently applies only to OAUTHBEARER.

    Type:short
    Default:300
    Valid Values:[0,...,3600]
    Importance:low
  • sasl.login.refresh.min.period.seconds

    The desired minimum time for the login refresh thread to wait before refreshing a credential, in seconds. Legal values are between 0 and 900 (15 minutes); a default value of 60 (1 minute) is used if no value is specified. This value and sasl.login.refresh.buffer.seconds are both ignored if their sum exceeds the remaining lifetime of a credential. Currently applies only to OAUTHBEARER.

    Type:short
    Default:60
    Valid Values:[0,...,900]
    Importance:low
  • sasl.login.refresh.window.factor

    Login refresh thread will sleep until the specified window factor relative to the credential's lifetime has been reached, at which time it will try to refresh the credential. Legal values are between 0.5 (50%) and 1.0 (100%) inclusive; a default value of 0.8 (80%) is used if no value is specified. Currently applies only to OAUTHBEARER.

    Type:double
    Default:0.8
    Valid Values:[0.5,...,1.0]
    Importance:low
  • sasl.login.refresh.window.jitter

    The maximum amount of random jitter relative to the credential's lifetime that is added to the login refresh thread's sleep time. Legal values are between 0 and 0.25 (25%) inclusive; a default value of 0.05 (5%) is used if no value is specified. Currently applies only to OAUTHBEARER.

    Type:double
    Default:0.05
    Valid Values:[0.0,...,0.25]
    Importance:low
  • sasl.login.retry.backoff.max.ms

    The (optional) value in milliseconds for the maximum wait between login attempts to the external authentication provider. Login uses an exponential backoff algorithm with an initial wait based on the sasl.login.retry.backoff.ms setting and will double in wait length between attempts up to a maximum wait length specified by the sasl.login.retry.backoff.max.ms setting. Currently applies only to OAUTHBEARER.

    Type:long
    Default:10000 (10 seconds)
    Valid Values:
    Importance:low
  • sasl.login.retry.backoff.ms

    The (optional) value in milliseconds for the initial wait between login attempts to the external authentication provider. Login uses an exponential backoff algorithm with an initial wait based on the sasl.login.retry.backoff.ms setting and will double in wait length between attempts up to a maximum wait length specified by the sasl.login.retry.backoff.max.ms setting. Currently applies only to OAUTHBEARER.

    Type:long
    Default:100
    Valid Values:
    Importance:low
  • sasl.oauthbearer.clock.skew.seconds

    The (optional) value in seconds to allow for differences between the time of the OAuth/OIDC identity provider and the broker.

    Type:int
    Default:30
    Valid Values:
    Importance:low
  • sasl.oauthbearer.expected.audience

    The (optional) comma-delimited setting for the broker to use to verify that the JWT was issued for one of the expected audiences. The JWT will be inspected for the standard OAuth "aud" claim and if this value is set, the broker will match the value from JWT's "aud" claim to see if there is an exact match. If there is no match, the broker will reject the JWT and authentication will fail.

    Type:list
    Default:null
    Valid Values:
    Importance:low
  • sasl.oauthbearer.expected.issuer

    The (optional) setting for the broker to use to verify that the JWT was created by the expected issuer. The JWT will be inspected for the standard OAuth "iss" claim and if this value is set, the broker will match it exactly against what is in the JWT's "iss" claim. If there is no match, the broker will reject the JWT and authentication will fail.

    Type:string
    Default:null
    Valid Values:
    Importance:low
  • sasl.oauthbearer.jwks.endpoint.refresh.ms

    The (optional) value in milliseconds for the broker to wait between refreshing its JWKS (JSON Web Key Set) cache that contains the keys to verify the signature of the JWT.

    Type:long
    Default:3600000 (1 hour)
    Valid Values:
    Importance:low
  • sasl.oauthbearer.jwks.endpoint.retry.backoff.max.ms

    The (optional) value in milliseconds for the maximum wait between attempts to retrieve the JWKS (JSON Web Key Set) from the external authentication provider. JWKS retrieval uses an exponential backoff algorithm with an initial wait based on the sasl.oauthbearer.jwks.endpoint.retry.backoff.ms setting and will double in wait length between attempts up to a maximum wait length specified by the sasl.oauthbearer.jwks.endpoint.retry.backoff.max.ms setting.

    Type:long
    Default:10000 (10 seconds)
    Valid Values:
    Importance:low
  • sasl.oauthbearer.jwks.endpoint.retry.backoff.ms

    The (optional) value in milliseconds for the initial wait between JWKS (JSON Web Key Set) retrieval attempts from the external authentication provider. JWKS retrieval uses an exponential backoff algorithm with an initial wait based on the sasl.oauthbearer.jwks.endpoint.retry.backoff.ms setting and will double in wait length between attempts up to a maximum wait length specified by the sasl.oauthbearer.jwks.endpoint.retry.backoff.max.ms setting.

    Type:long
    Default:100
    Valid Values:
    Importance:low
  • sasl.oauthbearer.scope.claim.name

    The OAuth claim for the scope is often named "scope", but this (optional) setting can provide a different name to use for the scope included in the JWT payload's claims if the OAuth/OIDC provider uses a different name for that claim.

    Type:string
    Default:scope
    Valid Values:
    Importance:low
  • sasl.oauthbearer.sub.claim.name

    The OAuth claim for the subject is often named "sub", but this (optional) setting can provide a different name to use for the subject included in the JWT payload's claims if the OAuth/OIDC provider uses a different name for that claim.

    Type:string
    Default:sub
    Valid Values:
    Importance:low
  • security.providers

    A list of configurable creator classes each returning a provider implementing security algorithms. These classes should implement the interface.org.apache.kafka.common.security.auth.SecurityProviderCreator

    Type:string
    Default:null
    Valid Values:
    Importance:low
  • ssl.cipher.suites

    A list of cipher suites. This is a named combination of authentication, encryption, MAC and key exchange algorithm used to negotiate the security settings for a network connection using TLS or SSL network protocol. By default all the available cipher suites are supported.

    Type:list
    Default:null
    Valid Values:
    Importance:low
  • ssl.endpoint.identification.algorithm

    The endpoint identification algorithm to validate server hostname using server certificate.

    Type:string
    Default:https
    Valid Values:
    Importance:low
  • ssl.engine.factory.class

    The class of type org.apache.kafka.common.security.auth.SslEngineFactory to provide SSLEngine objects. Default value is org.apache.kafka.common.security.ssl.DefaultSslEngineFactory

    Type:class
    Default:null
    Valid Values:
    Importance:low
  • ssl.keymanager.algorithm

    The algorithm used by key manager factory for SSL connections. Default value is the key manager factory algorithm configured for the Java Virtual Machine.

    Type:string
    Default:SunX509
    Valid Values:
    Importance:low
  • ssl.secure.random.implementation

    The SecureRandom PRNG implementation to use for SSL cryptography operations.

    Type:string
    Default:null
    Valid Values:
    Importance:low
  • ssl.trustmanager.algorithm

    The algorithm used by trust manager factory for SSL connections. Default value is the trust manager factory algorithm configured for the Java Virtual Machine.

    Type:string
    Default:PKIX
    Valid Values:
    Importance:low

3.5 Kafka Connect Configs

Below is the configuration of the Kafka Connect framework.
  • config.storage.topic

    The name of the Kafka topic where connector configurations are stored

    Type:string
    Default:
    Valid Values:
    Importance:high
  • group.id

    A unique string that identifies the Connect cluster group this worker belongs to.

    Type:string
    Default:
    Valid Values:
    Importance:high
  • key.converter

    Converter class used to convert between Kafka Connect format and the serialized form that is written to Kafka. This controls the format of the keys in messages written to or read from Kafka, and since this is independent of connectors it allows any connector to work with any serialization format. Examples of common formats include JSON and Avro.

    Type:class
    Default:
    Valid Values:
    Importance:high
  • offset.storage.topic

    The name of the Kafka topic where source connector offsets are stored

    Type:string
    Default:
    Valid Values:
    Importance:high
  • status.storage.topic

    The name of the Kafka topic where connector and task status are stored

    Type:string
    Default:
    Valid Values:
    Importance:high
  • value.converter

    Converter class used to convert between Kafka Connect format and the serialized form that is written to Kafka. This controls the format of the values in messages written to or read from Kafka, and since this is independent of connectors it allows any connector to work with any serialization format. Examples of common formats include JSON and Avro.

    Type:class
    Default:
    Valid Values:
    Importance:high
  • bootstrap.servers

    A list of host/port pairs to use for establishing the initial connection to the Kafka cluster. The client will make use of all servers irrespective of which servers are specified here for bootstrapping—this list only impacts the initial hosts used to discover the full set of servers. This list should be in the form . Since these servers are just used for the initial connection to discover the full cluster membership (which may change dynamically), this list need not contain the full set of servers (you may want more than one, though, in case a server is down).host1:port1,host2:port2,...

    Type:list
    Default:localhost:9092
    Valid Values:
    Importance:high
  • exactly.once.source.support

    Whether to enable exactly-once support for source connectors in the cluster by using transactions to write source records and their source offsets, and by proactively fencing out old task generations before bringing up new ones.
    To enable exactly-once source support on a new cluster, set this property to 'enabled'. To enable support on an existing cluster, first set to 'preparing' on every worker in the cluster, then set to 'enabled'. A rolling upgrade may be used for both changes. For more information on this feature, see the exactly-once source support documentation.

    Type:string
    Default:disabled
    Valid Values:(case insensitive) [DISABLED, ENABLED, PREPARING]
    Importance:high
  • heartbeat.interval.ms

    The expected time between heartbeats to the group coordinator when using Kafka's group management facilities. Heartbeats are used to ensure that the worker's session stays active and to facilitate rebalancing when new members join or leave the group. The value must be set lower than , but typically should be set no higher than 1/3 of that value. It can be adjusted even lower to control the expected time for normal rebalances.session.timeout.ms

    Type:int
    Default:3000 (3 seconds)
    Valid Values:
    Importance:high
  • rebalance.timeout.ms

    The maximum allowed time for each worker to join the group once a rebalance has begun. This is basically a limit on the amount of time needed for all tasks to flush any pending data and commit offsets. If the timeout is exceeded, then the worker will be removed from the group, which will cause offset commit failures.

    Type:int
    Default:60000 (1 minute)
    Valid Values:
    Importance:high
  • session.timeout.ms

    The timeout used to detect worker failures. The worker sends periodic heartbeats to indicate its liveness to the broker. If no heartbeats are received by the broker before the expiration of this session timeout, then the broker will remove the worker from the group and initiate a rebalance. Note that the value must be in the allowable range as configured in the broker configuration by and .group.min.session.timeout.msgroup.max.session.timeout.ms

    Type:int
    Default:10000 (10 seconds)
    Valid Values:
    Importance:high
  • ssl.key.password

    The password of the private key in the key store file or the PEM key specified in 'ssl.keystore.key'.

    Type:password
    Default:null
    Valid Values:
    Importance:high
  • ssl.keystore.certificate.chain

    Certificate chain in the format specified by 'ssl.keystore.type'. Default SSL engine factory supports only PEM format with a list of X.509 certificates

    Type:password
    Default:null
    Valid Values:
    Importance:high
  • ssl.keystore.key

    Private key in the format specified by 'ssl.keystore.type'. Default SSL engine factory supports only PEM format with PKCS#8 keys. If the key is encrypted, key password must be specified using 'ssl.key.password'

    Type:password
    Default:null
    Valid Values:
    Importance:high
  • ssl.keystore.location

    The location of the key store file. This is optional for client and can be used for two-way authentication for client.

    Type:string
    Default:null
    Valid Values:
    Importance:high
  • ssl.keystore.password

    The store password for the key store file. This is optional for client and only needed if 'ssl.keystore.location' is configured. Key store password is not supported for PEM format.

    Type:password
    Default:null
    Valid Values:
    Importance:high
  • ssl.truststore.certificates

    Trusted certificates in the format specified by 'ssl.truststore.type'. Default SSL engine factory supports only PEM format with X.509 certificates.

    Type:password
    Default:null
    Valid Values:
    Importance:high
  • ssl.truststore.location

    The location of the trust store file.

    Type:string
    Default:null
    Valid Values:
    Importance:high
  • ssl.truststore.password

    The password for the trust store file. If a password is not set, trust store file configured will still be used, but integrity checking is disabled. Trust store password is not supported for PEM format.

    Type:password
    Default:null
    Valid Values:
    Importance:high
  • client.dns.lookup

    Controls how the client uses DNS lookups. If set to , connect to each returned IP address in sequence until a successful connection is established. After a disconnection, the next IP is used. Once all IPs have been used once, the client resolves the IP(s) from the hostname again (both the JVM and the OS cache DNS name lookups, however). If set to , resolve each bootstrap address into a list of canonical names. After the bootstrap phase, this behaves the same as .use_all_dns_ipsresolve_canonical_bootstrap_servers_onlyuse_all_dns_ips

    Type:string
    Default:use_all_dns_ips
    Valid Values:[use_all_dns_ips, resolve_canonical_bootstrap_servers_only]
    Importance:medium
  • connections.max.idle.ms

    Close idle connections after the number of milliseconds specified by this config.

    Type:long
    Default:540000 (9 minutes)
    Valid Values:
    Importance:medium
  • connector.client.config.override.policy

    Class name or alias of implementation of . Defines what client configurations can be overridden by the connector. The default implementation is `All`, meaning connector configurations can override all client properties. The other possible policies in the framework include `None` to disallow connectors from overriding client properties, and `Principal` to allow connectors to override only client principals.ConnectorClientConfigOverridePolicy

    Type:string
    Default:All
    Valid Values:
    Importance:medium
  • receive.buffer.bytes

    The size of the TCP receive buffer (SO_RCVBUF) to use when reading data. If the value is -1, the OS default will be used.

    Type:int
    Default:32768 (32 kibibytes)
    Valid Values:[-1,...]
    Importance:medium
  • request.timeout.ms

    The configuration controls the maximum amount of time the client will wait for the response of a request. If the response is not received before the timeout elapses the client will resend the request if necessary or fail the request if retries are exhausted.

    Type:int
    Default:40000 (40 seconds)
    Valid Values:[0,...]
    Importance:medium
  • sasl.client.callback.handler.class

    The fully qualified name of a SASL client callback handler class that implements the AuthenticateCallbackHandler interface.

    Type:class
    Default:null
    Valid Values:
    Importance:medium
  • sasl.jaas.config

    JAAS login context parameters for SASL connections in the format used by JAAS configuration files. JAAS configuration file format is described here. The format for the value is: . For brokers, the config must be prefixed with listener prefix and SASL mechanism name in lower-case. For example, listener.name.sasl_ssl.scram-sha-256.sasl.jaas.config=com.example.ScramLoginModule required;loginModuleClass controlFlag (optionName=optionValue)*;

    Type:password
    Default:null
    Valid Values:
    Importance:medium
  • sasl.kerberos.service.name

    The Kerberos principal name that Kafka runs as. This can be defined either in Kafka's JAAS config or in Kafka's config.

    Type:string
    Default:null
    Valid Values:
    Importance:medium
  • sasl.login.callback.handler.class

    The fully qualified name of a SASL login callback handler class that implements the AuthenticateCallbackHandler interface. For brokers, login callback handler config must be prefixed with listener prefix and SASL mechanism name in lower-case. For example, listener.name.sasl_ssl.scram-sha-256.sasl.login.callback.handler.class=com.example.CustomScramLoginCallbackHandler

    Type:class
    Default:null
    Valid Values:
    Importance:medium
  • sasl.login.class

    The fully qualified name of a class that implements the Login interface. For brokers, login config must be prefixed with listener prefix and SASL mechanism name in lower-case. For example, listener.name.sasl_ssl.scram-sha-256.sasl.login.class=com.example.CustomScramLogin

    Type:class
    Default:null
    Valid Values:
    Importance:medium
  • sasl.mechanism

    SASL mechanism used for client connections. This may be any mechanism for which a security provider is available. GSSAPI is the default mechanism.

    Type:string
    Default:GSSAPI
    Valid Values:
    Importance:medium
  • sasl.oauthbearer.jwks.endpoint.url

    The OAuth/OIDC provider URL from which the provider's JWKS (JSON Web Key Set) can be retrieved. The URL can be HTTP(S)-based or file-based. If the URL is HTTP(S)-based, the JWKS data will be retrieved from the OAuth/OIDC provider via the configured URL on broker startup. All then-current keys will be cached on the broker for incoming requests. If an authentication request is received for a JWT that includes a "kid" header claim value that isn't yet in the cache, the JWKS endpoint will be queried again on demand. However, the broker polls the URL every sasl.oauthbearer.jwks.endpoint.refresh.ms milliseconds to refresh the cache with any forthcoming keys before any JWT requests that include them are received. If the URL is file-based, the broker will load the JWKS file from a configured location on startup. In the event that the JWT includes a "kid" header value that isn't in the JWKS file, the broker will reject the JWT and authentication will fail.

    Type:string
    Default:null
    Valid Values:
    Importance:medium
  • sasl.oauthbearer.token.endpoint.url

    The URL for the OAuth/OIDC identity provider. If the URL is HTTP(S)-based, it is the issuer's token endpoint URL to which requests will be made to login based on the configuration in sasl.jaas.config. If the URL is file-based, it specifies a file containing an access token (in JWT serialized form) issued by the OAuth/OIDC identity provider to use for authorization.

    Type:string
    Default:null
    Valid Values:
    Importance:medium
  • security.protocol

    Protocol used to communicate with brokers. Valid values are: PLAINTEXT, SSL, SASL_PLAINTEXT, SASL_SSL.

    Type:string
    Default:PLAINTEXT
    Valid Values:(case insensitive) [SASL_SSL, PLAINTEXT, SSL, SASL_PLAINTEXT]
    Importance:medium
  • send.buffer.bytes

    The size of the TCP send buffer (SO_SNDBUF) to use when sending data. If the value is -1, the OS default will be used.

    Type:int
    Default:131072 (128 kibibytes)
    Valid Values:[-1,...]
    Importance:medium
  • ssl.enabled.protocols

    The list of protocols enabled for SSL connections. The default is 'TLSv1.2,TLSv1.3' when running with Java 11 or newer, 'TLSv1.2' otherwise. With the default value for Java 11, clients and servers will prefer TLSv1.3 if both support it and fallback to TLSv1.2 otherwise (assuming both support at least TLSv1.2). This default should be fine for most cases. Also see the config documentation for `ssl.protocol`.

    Type:list
    Default:TLSv1.2,TLSv1.3
    Valid Values:
    Importance:medium
  • ssl.keystore.type

    The file format of the key store file. This is optional for client. The values currently supported by the default `ssl.engine.factory.class` are [JKS, PKCS12, PEM].

    Type:string
    Default:JKS
    Valid Values:
    Importance:medium
  • ssl.protocol

    The SSL protocol used to generate the SSLContext. The default is 'TLSv1.3' when running with Java 11 or newer, 'TLSv1.2' otherwise. This value should be fine for most use cases. Allowed values in recent JVMs are 'TLSv1.2' and 'TLSv1.3'. 'TLS', 'TLSv1.1', 'SSL', 'SSLv2' and 'SSLv3' may be supported in older JVMs, but their usage is discouraged due to known security vulnerabilities. With the default value for this config and 'ssl.enabled.protocols', clients will downgrade to 'TLSv1.2' if the server does not support 'TLSv1.3'. If this config is set to 'TLSv1.2', clients will not use 'TLSv1.3' even if it is one of the values in ssl.enabled.protocols and the server only supports 'TLSv1.3'.

    Type:string
    Default:TLSv1.3
    Valid Values:
    Importance:medium
  • ssl.provider

    The name of the security provider used for SSL connections. Default value is the default security provider of the JVM.

    Type:string
    Default:null
    Valid Values:
    Importance:medium
  • ssl.truststore.type

    The file format of the trust store file. The values currently supported by the default `ssl.engine.factory.class` are [JKS, PKCS12, PEM].

    Type:string
    Default:JKS
    Valid Values:
    Importance:medium
  • worker.sync.timeout.ms

    When the worker is out of sync with other workers and needs to resynchronize configurations, wait up to this amount of time before giving up, leaving the group, and waiting a backoff period before rejoining.

    Type:int
    Default:3000 (3 seconds)
    Valid Values:
    Importance:medium
  • worker.unsync.backoff.ms

    When the worker is out of sync with other workers and fails to catch up within worker.sync.timeout.ms, leave the Connect cluster for this long before rejoining.

    Type:int
    Default:300000 (5 minutes)
    Valid Values:
    Importance:medium
  • access.control.allow.methods

    Sets the methods supported for cross origin requests by setting the Access-Control-Allow-Methods header. The default value of the Access-Control-Allow-Methods header allows cross origin requests for GET, POST and HEAD.

    Type:string
    Default:""
    Valid Values:
    Importance:low
  • access.control.allow.origin

    Value to set the Access-Control-Allow-Origin header to for REST API requests.To enable cross origin access, set this to the domain of the application that should be permitted to access the API, or '*' to allow access from any domain. The default value only allows access from the domain of the REST API.

    Type:string
    Default:""
    Valid Values:
    Importance:low
  • admin.listeners

    List of comma-separated URIs the Admin REST API will listen on. The supported protocols are HTTP and HTTPS. An empty or blank string will disable this feature. The default behavior is to use the regular listener (specified by the 'listeners' property).

    Type:list
    Default:null
    Valid Values:List of comma-separated URLs, ex: http://localhost:8080,https://localhost:8443.
    Importance:low
  • auto.include.jmx.reporter

    Deprecated. Whether to automatically include JmxReporter even if it's not listed in . This configuration will be removed in Kafka 4.0, users should instead include in in order to enable the JmxReporter.metric.reportersorg.apache.kafka.common.metrics.JmxReportermetric.reporters

    Type:boolean
    Default:true
    Valid Values:
    Importance:low
  • client.id

    An id string to pass to the server when making requests. The purpose of this is to be able to track the source of requests beyond just ip/port by allowing a logical application name to be included in server-side request logging.

    Type:string
    Default:""
    Valid Values:
    Importance:low
  • config.providers

    Comma-separated names of classes, loaded and used in the order specified. Implementing the interface allows you to replace variable references in connector configurations, such as for externalized secrets. ConfigProviderConfigProvider

    Type:list
    Default:""
    Valid Values:
    Importance:low
  • config.storage.replication.factor

    Replication factor used when creating the configuration storage topic

    Type:short
    Default:3
    Valid Values:Positive number not larger than the number of brokers in the Kafka cluster, or -1 to use the broker's default
    Importance:low
  • connect.protocol

    Compatibility mode for Kafka Connect Protocol

    Type:string
    Default:sessioned
    Valid Values:[eager, compatible, sessioned]
    Importance:low
  • header.converter

    HeaderConverter class used to convert between Kafka Connect format and the serialized form that is written to Kafka. This controls the format of the header values in messages written to or read from Kafka, and since this is independent of connectors it allows any connector to work with any serialization format. Examples of common formats include JSON and Avro. By default, the SimpleHeaderConverter is used to serialize header values to strings and deserialize them by inferring the schemas.

    Type:class
    Default:org.apache.kafka.connect.storage.SimpleHeaderConverter
    Valid Values:
    Importance:low
  • inter.worker.key.generation.algorithm

    The algorithm to use for generating internal request keys. The algorithm 'HmacSHA256' will be used as a default on JVMs that support it; on other JVMs, no default is used and a value for this property must be manually specified in the worker config.

    Type:string
    Default:HmacSHA256
    Valid Values:Any KeyGenerator algorithm supported by the worker JVM
    Importance:low
  • inter.worker.key.size

    The size of the key to use for signing internal requests, in bits. If null, the default key size for the key generation algorithm will be used.

    Type:int
    Default:null
    Valid Values:
    Importance:low
  • inter.worker.key.ttl.ms

    The TTL of generated session keys used for internal request validation (in milliseconds)

    Type:int
    Default:3600000 (1 hour)
    Valid Values:[0,...,2147483647]
    Importance:low
  • inter.worker.signature.algorithm

    The algorithm used to sign internal requestsThe algorithm 'inter.worker.signature.algorithm' will be used as a default on JVMs that support it; on other JVMs, no default is used and a value for this property must be manually specified in the worker config.

    Type:string
    Default:HmacSHA256
    Valid Values:Any MAC algorithm supported by the worker JVM
    Importance:low
  • inter.worker.verification.algorithms

    A list of permitted algorithms for verifying internal requests, which must include the algorithm used for the inter.worker.signature.algorithm property. The algorithm(s) '[HmacSHA256]' will be used as a default on JVMs that provide them; on other JVMs, no default is used and a value for this property must be manually specified in the worker config.

    Type:list
    Default:HmacSHA256
    Valid Values:A list of one or more MAC algorithms, each supported by the worker JVM
    Importance:low
  • listeners

    List of comma-separated URIs the REST API will listen on. The supported protocols are HTTP and HTTPS.
    Specify hostname as 0.0.0.0 to bind to all interfaces.
    Leave hostname empty to bind to default interface.
    Examples of legal listener lists: HTTP://myhost:8083,HTTPS://myhost:8084

    Type:list
    Default:http://:8083
    Valid Values:List of comma-separated URLs, ex: http://localhost:8080,https://localhost:8443.
    Importance:low
  • metadata.max.age.ms

    The period of time in milliseconds after which we force a refresh of metadata even if we haven't seen any partition leadership changes to proactively discover any new brokers or partitions.

    Type:long
    Default:300000 (5 minutes)
    Valid Values:[0,...]
    Importance:low
  • metric.reporters

    A list of classes to use as metrics reporters. Implementing the interface allows plugging in classes that will be notified of new metric creation. The JmxReporter is always included to register JMX statistics.org.apache.kafka.common.metrics.MetricsReporter

    Type:list
    Default:""
    Valid Values:
    Importance:low
  • metrics.num.samples

    The number of samples maintained to compute metrics.

    Type:int
    Default:2
    Valid Values:[1,...]
    Importance:low
  • metrics.recording.level

    The highest recording level for metrics.

    Type:string
    Default:INFO
    Valid Values:[INFO, DEBUG]
    Importance:low
  • metrics.sample.window.ms

    The window of time a metrics sample is computed over.

    Type:long
    Default:30000 (30 seconds)
    Valid Values:[0,...]
    Importance:low
  • offset.flush.interval.ms

    Interval at which to try committing offsets for tasks.

    Type:long
    Default:60000 (1 minute)
    Valid Values:
    Importance:low
  • offset.flush.timeout.ms

    Maximum number of milliseconds to wait for records to flush and partition offset data to be committed to offset storage before cancelling the process and restoring the offset data to be committed in a future attempt. This property has no effect for source connectors running with exactly-once support.

    Type:long
    Default:5000 (5 seconds)
    Valid Values:
    Importance:low
  • offset.storage.partitions

    The number of partitions used when creating the offset storage topic

    Type:int
    Default:25
    Valid Values:Positive number, or -1 to use the broker's default
    Importance:low
  • offset.storage.replication.factor

    Replication factor used when creating the offset storage topic

    Type:short
    Default:3
    Valid Values:Positive number not larger than the number of brokers in the Kafka cluster, or -1 to use the broker's default
    Importance:low
  • plugin.path

    List of paths separated by commas (,) that contain plugins (connectors, converters, transformations). The list should consist of top level directories that include any combination of:
    a) directories immediately containing jars with plugins and their dependencies
    b) uber-jars with plugins and their dependencies
    c) directories immediately containing the package directory structure of classes of plugins and their dependencies
    Note: symlinks will be followed to discover dependencies or plugins.
    Examples: plugin.path=/usr/local/share/java,/usr/local/share/kafka/plugins,/opt/connectors
    Do not use config provider variables in this property, since the raw path is used by the worker's scanner before config providers are initialized and used to replace variables.

    Type:list
    Default:null
    Valid Values:
    Importance:low
  • reconnect.backoff.max.ms

    The maximum amount of time in milliseconds to wait when reconnecting to a broker that has repeatedly failed to connect. If provided, the backoff per host will increase exponentially for each consecutive connection failure, up to this maximum. After calculating the backoff increase, 20% random jitter is added to avoid connection storms.

    Type:long
    Default:1000 (1 second)
    Valid Values:[0,...]
    Importance:low
  • reconnect.backoff.ms

    The base amount of time to wait before attempting to reconnect to a given host. This avoids repeatedly connecting to a host in a tight loop. This backoff applies to all connection attempts by the client to a broker.

    Type:long
    Default:50
    Valid Values:[0,...]
    Importance:low
  • response.http.headers.config

    Rules for REST API HTTP response headers

    Type:string
    Default:""
    Valid Values:Comma-separated header rules, where each header rule is of the form '[action] [header name]:[header value]' and optionally surrounded by double quotes if any part of a header rule contains a comma
    Importance:low
  • rest.advertised.host.name

    If this is set, this is the hostname that will be given out to other workers to connect to.

    Type:string
    Default:null
    Valid Values:
    Importance:low
  • rest.advertised.listener

    Sets the advertised listener (HTTP or HTTPS) which will be given to other workers to use.

    Type:string
    Default:null
    Valid Values:
    Importance:low
  • rest.advertised.port

    If this is set, this is the port that will be given out to other workers to connect to.

    Type:int
    Default:null
    Valid Values:
    Importance:low
  • rest.extension.classes

    Comma-separated names of classes, loaded and called in the order specified. Implementing the interface allows you to inject into Connect's REST API user defined resources like filters. Typically used to add custom capability like logging, security, etc. ConnectRestExtensionConnectRestExtension

    Type:list
    Default:""
    Valid Values:
    Importance:low
  • retry.backoff.ms

    The amount of time to wait before attempting to retry a failed request to a given topic partition. This avoids repeatedly sending requests in a tight loop under some failure scenarios.

    Type:long
    Default:100
    Valid Values:[0,...]
    Importance:low
  • sasl.kerberos.kinit.cmd

    Kerberos kinit command path.

    Type:string
    Default:/usr/bin/kinit
    Valid Values:
    Importance:low
  • sasl.kerberos.min.time.before.relogin

    Login thread sleep time between refresh attempts.

    Type:long
    Default:60000
    Valid Values:
    Importance:low
  • sasl.kerberos.ticket.renew.jitter

    Percentage of random jitter added to the renewal time.

    Type:double
    Default:0.05
    Valid Values:
    Importance:low
  • sasl.kerberos.ticket.renew.window.factor

    Login thread will sleep until the specified window factor of time from last refresh to ticket's expiry has been reached, at which time it will try to renew the ticket.

    Type:double
    Default:0.8
    Valid Values:
    Importance:low
  • sasl.login.connect.timeout.ms

    The (optional) value in milliseconds for the external authentication provider connection timeout. Currently applies only to OAUTHBEARER.

    Type:int
    Default:null
    Valid Values:
    Importance:low
  • sasl.login.read.timeout.ms

    The (optional) value in milliseconds for the external authentication provider read timeout. Currently applies only to OAUTHBEARER.

    Type:int
    Default:null
    Valid Values:
    Importance:low
  • sasl.login.refresh.buffer.seconds

    The amount of buffer time before credential expiration to maintain when refreshing a credential, in seconds. If a refresh would otherwise occur closer to expiration than the number of buffer seconds then the refresh will be moved up to maintain as much of the buffer time as possible. Legal values are between 0 and 3600 (1 hour); a default value of 300 (5 minutes) is used if no value is specified. This value and sasl.login.refresh.min.period.seconds are both ignored if their sum exceeds the remaining lifetime of a credential. Currently applies only to OAUTHBEARER.

    Type:short
    Default:300
    Valid Values:[0,...,3600]
    Importance:low
  • sasl.login.refresh.min.period.seconds

    The desired minimum time for the login refresh thread to wait before refreshing a credential, in seconds. Legal values are between 0 and 900 (15 minutes); a default value of 60 (1 minute) is used if no value is specified. This value and sasl.login.refresh.buffer.seconds are both ignored if their sum exceeds the remaining lifetime of a credential. Currently applies only to OAUTHBEARER.

    Type:short
    Default:60
    Valid Values:[0,...,900]
    Importance:low
  • sasl.login.refresh.window.factor

    Login refresh thread will sleep until the specified window factor relative to the credential's lifetime has been reached, at which time it will try to refresh the credential. Legal values are between 0.5 (50%) and 1.0 (100%) inclusive; a default value of 0.8 (80%) is used if no value is specified. Currently applies only to OAUTHBEARER.

    Type:double
    Default:0.8
    Valid Values:[0.5,...,1.0]
    Importance:low
  • sasl.login.refresh.window.jitter

    The maximum amount of random jitter relative to the credential's lifetime that is added to the login refresh thread's sleep time. Legal values are between 0 and 0.25 (25%) inclusive; a default value of 0.05 (5%) is used if no value is specified. Currently applies only to OAUTHBEARER.

    Type:double
    Default:0.05
    Valid Values:[0.0,...,0.25]
    Importance:low
  • sasl.login.retry.backoff.max.ms

    The (optional) value in milliseconds for the maximum wait between login attempts to the external authentication provider. Login uses an exponential backoff algorithm with an initial wait based on the sasl.login.retry.backoff.ms setting and will double in wait length between attempts up to a maximum wait length specified by the sasl.login.retry.backoff.max.ms setting. Currently applies only to OAUTHBEARER.

    Type:long
    Default:10000 (10 seconds)
    Valid Values:
    Importance:low
  • sasl.login.retry.backoff.ms

    The (optional) value in milliseconds for the initial wait between login attempts to the external authentication provider. Login uses an exponential backoff algorithm with an initial wait based on the sasl.login.retry.backoff.ms setting and will double in wait length between attempts up to a maximum wait length specified by the sasl.login.retry.backoff.max.ms setting. Currently applies only to OAUTHBEARER.

    Type:long
    Default:100
    Valid Values:
    Importance:low
  • sasl.oauthbearer.clock.skew.seconds

    The (optional) value in seconds to allow for differences between the time of the OAuth/OIDC identity provider and the broker.

    Type:int
    Default:30
    Valid Values:
    Importance:low
  • sasl.oauthbearer.expected.audience

    The (optional) comma-delimited setting for the broker to use to verify that the JWT was issued for one of the expected audiences. The JWT will be inspected for the standard OAuth "aud" claim and if this value is set, the broker will match the value from JWT's "aud" claim to see if there is an exact match. If there is no match, the broker will reject the JWT and authentication will fail.

    Type:list
    Default:null
    Valid Values:
    Importance:low
  • sasl.oauthbearer.expected.issuer

    The (optional) setting for the broker to use to verify that the JWT was created by the expected issuer. The JWT will be inspected for the standard OAuth "iss" claim and if this value is set, the broker will match it exactly against what is in the JWT's "iss" claim. If there is no match, the broker will reject the JWT and authentication will fail.

    Type:string
    Default:null
    Valid Values:
    Importance:low
  • sasl.oauthbearer.jwks.endpoint.refresh.ms

    The (optional) value in milliseconds for the broker to wait between refreshing its JWKS (JSON Web Key Set) cache that contains the keys to verify the signature of the JWT.

    Type:long
    Default:3600000 (1 hour)
    Valid Values:
    Importance:low
  • sasl.oauthbearer.jwks.endpoint.retry.backoff.max.ms

    The (optional) value in milliseconds for the maximum wait between attempts to retrieve the JWKS (JSON Web Key Set) from the external authentication provider. JWKS retrieval uses an exponential backoff algorithm with an initial wait based on the sasl.oauthbearer.jwks.endpoint.retry.backoff.ms setting and will double in wait length between attempts up to a maximum wait length specified by the sasl.oauthbearer.jwks.endpoint.retry.backoff.max.ms setting.

    Type:long
    Default:10000 (10 seconds)
    Valid Values:
    Importance:low
  • sasl.oauthbearer.jwks.endpoint.retry.backoff.ms

    The (optional) value in milliseconds for the initial wait between JWKS (JSON Web Key Set) retrieval attempts from the external authentication provider. JWKS retrieval uses an exponential backoff algorithm with an initial wait based on the sasl.oauthbearer.jwks.endpoint.retry.backoff.ms setting and will double in wait length between attempts up to a maximum wait length specified by the sasl.oauthbearer.jwks.endpoint.retry.backoff.max.ms setting.

    Type:long
    Default:100
    Valid Values:
    Importance:low
  • sasl.oauthbearer.scope.claim.name

    The OAuth claim for the scope is often named "scope", but this (optional) setting can provide a different name to use for the scope included in the JWT payload's claims if the OAuth/OIDC provider uses a different name for that claim.

    Type:string
    Default:scope
    Valid Values:
    Importance:low
  • sasl.oauthbearer.sub.claim.name

    The OAuth claim for the subject is often named "sub", but this (optional) setting can provide a different name to use for the subject included in the JWT payload's claims if the OAuth/OIDC provider uses a different name for that claim.

    Type:string
    Default:sub
    Valid Values:
    Importance:low
  • scheduled.rebalance.max.delay.ms

    The maximum delay that is scheduled in order to wait for the return of one or more departed workers before rebalancing and reassigning their connectors and tasks to the group. During this period the connectors and tasks of the departed workers remain unassigned

    Type:int
    Default:300000 (5 minutes)
    Valid Values:[0,...,2147483647]
    Importance:low
  • socket.connection.setup.timeout.max.ms

    The maximum amount of time the client will wait for the socket connection to be established. The connection setup timeout will increase exponentially for each consecutive connection failure up to this maximum. To avoid connection storms, a randomization factor of 0.2 will be applied to the timeout resulting in a random range between 20% below and 20% above the computed value.

    Type:long
    Default:30000 (30 seconds)
    Valid Values:[0,...]
    Importance:low
  • socket.connection.setup.timeout.ms

    The amount of time the client will wait for the socket connection to be established. If the connection is not built before the timeout elapses, clients will close the socket channel.

    Type:long
    Default:10000 (10 seconds)
    Valid Values:[0,...]
    Importance:low
  • ssl.cipher.suites

    A list of cipher suites. This is a named combination of authentication, encryption, MAC and key exchange algorithm used to negotiate the security settings for a network connection using TLS or SSL network protocol. By default all the available cipher suites are supported.

    Type:list
    Default:null
    Valid Values:
    Importance:low
  • ssl.client.auth

    Configures kafka broker to request client authentication. The following settings are common:

    • ssl.client.auth=required If set to required client authentication is required.
    • ssl.client.auth=requested This means client authentication is optional. unlike required, if this option is set client can choose not to provide authentication information about itself
    • ssl.client.auth=none This means client authentication is not needed.

    Type:string
    Default:none
    Valid Values:[required, requested, none]
    Importance:low
  • ssl.endpoint.identification.algorithm

    The endpoint identification algorithm to validate server hostname using server certificate.

    Type:string
    Default:https
    Valid Values:
    Importance:low
  • ssl.engine.factory.class

    The class of type org.apache.kafka.common.security.auth.SslEngineFactory to provide SSLEngine objects. Default value is org.apache.kafka.common.security.ssl.DefaultSslEngineFactory

    Type:class
    Default:null
    Valid Values:
    Importance:low
  • ssl.keymanager.algorithm

    The algorithm used by key manager factory for SSL connections. Default value is the key manager factory algorithm configured for the Java Virtual Machine.

    Type:string
    Default:SunX509
    Valid Values:
    Importance:low
  • ssl.secure.random.implementation

    The SecureRandom PRNG implementation to use for SSL cryptography operations.

    Type:string
    Default:null
    Valid Values:
    Importance:low
  • ssl.trustmanager.algorithm

    The algorithm used by trust manager factory for SSL connections. Default value is the trust manager factory algorithm configured for the Java Virtual Machine.

    Type:string
    Default:PKIX
    Valid Values:
    Importance:low
  • status.storage.partitions

    The number of partitions used when creating the status storage topic

    Type:int
    Default:5
    Valid Values:Positive number, or -1 to use the broker's default
    Importance:low
  • status.storage.replication.factor

    Replication factor used when creating the status storage topic

    Type:short
    Default:3
    Valid Values:Positive number not larger than the number of brokers in the Kafka cluster, or -1 to use the broker's default
    Importance:low
  • task.shutdown.graceful.timeout.ms

    Amount of time to wait for tasks to shutdown gracefully. This is the total amount of time, not per task. All task have shutdown triggered, then they are waited on sequentially.

    Type:long
    Default:5000 (5 seconds)
    Valid Values:
    Importance:low
  • topic.creation.enable

    Whether to allow automatic creation of topics used by source connectors, when source connectors are configured with `topic.creation.` properties. Each task will use an admin client to create its topics and will not depend on the Kafka brokers to create topics automatically.

    Type:boolean
    Default:true
    Valid Values:
    Importance:low
  • topic.tracking.allow.reset

    If set to true, it allows user requests to reset the set of active topics per connector.

    Type:boolean
    Default:true
    Valid Values:
    Importance:low
  • topic.tracking.enable

    Enable tracking the set of active topics per connector during runtime.

    Type:boolean
    Default:true
    Valid Values:
    Importance:low

3.5.1 Source Connector Configs

Below is the configuration of a source connector.
  • name

    Globally unique name to use for this connector.

    Type:string
    Default:
    Valid Values:non-empty string without ISO control characters
    Importance:high
  • connector.class

    Name or alias of the class for this connector. Must be a subclass of org.apache.kafka.connect.connector.Connector. If the connector is org.apache.kafka.connect.file.FileStreamSinkConnector, you can either specify this full name, or use "FileStreamSink" or "FileStreamSinkConnector" to make the configuration a bit shorter

    Type:string
    Default:
    Valid Values:
    Importance:high
  • tasks.max

    Maximum number of tasks to use for this connector.

    Type:int
    Default:1
    Valid Values:[1,...]
    Importance:high
  • key.converter

    Converter class used to convert between Kafka Connect format and the serialized form that is written to Kafka. This controls the format of the keys in messages written to or read from Kafka, and since this is independent of connectors it allows any connector to work with any serialization format. Examples of common formats include JSON and Avro.

    Type:class
    Default:null
    Valid Values:
    Importance:low
  • value.converter

    Converter class used to convert between Kafka Connect format and the serialized form that is written to Kafka. This controls the format of the values in messages written to or read from Kafka, and since this is independent of connectors it allows any connector to work with any serialization format. Examples of common formats include JSON and Avro.

    Type:class
    Default:null
    Valid Values:
    Importance:low
  • header.converter

    HeaderConverter class used to convert between Kafka Connect format and the serialized form that is written to Kafka. This controls the format of the header values in messages written to or read from Kafka, and since this is independent of connectors it allows any connector to work with any serialization format. Examples of common formats include JSON and Avro. By default, the SimpleHeaderConverter is used to serialize header values to strings and deserialize them by inferring the schemas.

    Type:class
    Default:null
    Valid Values:
    Importance:low
  • config.action.reload

    The action that Connect should take on the connector when changes in external configuration providers result in a change in the connector's configuration properties. A value of 'none' indicates that Connect will do nothing. A value of 'restart' indicates that Connect should restart/reload the connector with the updated configuration properties.The restart may actually be scheduled in the future if the external configuration provider indicates that a configuration value will expire in the future.

    Type:string
    Default:restart
    Valid Values:[none, restart]
    Importance:low
  • transforms

    Aliases for the transformations to be applied to records.

    Type:list
    Default:""
    Valid Values:non-null string, unique transformation aliases
    Importance:low
  • predicates

    Aliases for the predicates used by transformations.

    Type:list
    Default:""
    Valid Values:non-null string, unique predicate aliases
    Importance:low
  • errors.retry.timeout

    The maximum duration in milliseconds that a failed operation will be reattempted. The default is 0, which means no retries will be attempted. Use -1 for infinite retries.

    Type:long
    Default:0
    Valid Values:
    Importance:medium
  • errors.retry.delay.max.ms

    The maximum duration in milliseconds between consecutive retry attempts. Jitter will be added to the delay once this limit is reached to prevent thundering herd issues.

    Type:long
    Default:60000 (1 minute)
    Valid Values:
    Importance:medium
  • errors.tolerance

    Behavior for tolerating errors during connector operation. 'none' is the default value and signals that any error will result in an immediate connector task failure; 'all' changes the behavior to skip over problematic records.

    Type:string
    Default:none
    Valid Values:[none, all]
    Importance:medium
  • errors.log.enable

    If true, write each error and the details of the failed operation and problematic record to the Connect application log. This is 'false' by default, so that only errors that are not tolerated are reported.

    Type:boolean
    Default:false
    Valid Values:
    Importance:medium
  • errors.log.include.messages

    Whether to include in the log the Connect record that resulted in a failure.For sink records, the topic, partition, offset, and timestamp will be logged. For source records, the key and value (and their schemas), all headers, and the timestamp, Kafka topic, Kafka partition, source partition, and source offset will be logged. This is 'false' by default, which will prevent record keys, values, and headers from being written to log files.

    Type:boolean
    Default:false
    Valid Values:
    Importance:medium
  • topic.creation.groups

    Groups of configurations for topics created by source connectors

    Type:list
    Default:""
    Valid Values:non-null string, unique topic creation groups
    Importance:low
  • exactly.once.support

    Permitted values are requested, required. If set to "required", forces a preflight check for the connector to ensure that it can provide exactly-once semantics with the given configuration. Some connectors may be capable of providing exactly-once semantics but not signal to Connect that they support this; in that case, documentation for the connector should be consulted carefully before creating it, and the value for this property should be set to "requested". Additionally, if the value is set to "required" but the worker that performs preflight validation does not have exactly-once support enabled for source connectors, requests to create or validate the connector will fail.

    Type:string
    Default:requested
    Valid Values:(case insensitive) [REQUIRED, REQUESTED]
    Importance:medium
  • transaction.boundary

    Permitted values are: poll, interval, connector. If set to 'poll', a new producer transaction will be started and committed for every batch of records that each task from this connector provides to Connect. If set to 'connector', relies on connector-defined transaction boundaries; note that not all connectors are capable of defining their own transaction boundaries, and in that case, attempts to instantiate a connector with this value will fail. Finally, if set to 'interval', commits transactions only after a user-defined time interval has passed.

    Type:string
    Default:poll
    Valid Values:(case insensitive) [INTERVAL, POLL, CONNECTOR]
    Importance:medium
  • transaction.boundary.interval.ms

    If 'transaction.boundary' is set to 'interval', determines the interval for producer transaction commits by connector tasks. If unset, defaults to the value of the worker-level 'offset.flush.interval.ms' property. It has no effect if a different transaction.boundary is specified.

    Type:long
    Default:null
    Valid Values:[0,...]
    Importance:low
  • offsets.storage.topic

    The name of a separate offsets topic to use for this connector. If empty or not specified, the worker’s global offsets topic name will be used. If specified, the offsets topic will be created if it does not already exist on the Kafka cluster targeted by this connector (which may be different from the one used for the worker's global offsets topic if the bootstrap.servers property of the connector's producer has been overridden from the worker's). Only applicable in distributed mode; in standalone mode, setting this property will have no effect.

    Type:string
    Default:null
    Valid Values:non-empty string
    Importance:low

3.5.2 Sink Connector Configs

Below is the configuration of a sink connector.
  • name

    Globally unique name to use for this connector.

    Type:string
    Default:
    Valid Values:non-empty string without ISO control characters
    Importance:high
  • connector.class

    Name or alias of the class for this connector. Must be a subclass of org.apache.kafka.connect.connector.Connector. If the connector is org.apache.kafka.connect.file.FileStreamSinkConnector, you can either specify this full name, or use "FileStreamSink" or "FileStreamSinkConnector" to make the configuration a bit shorter

    Type:string
    Default:
    Valid Values:
    Importance:high
  • tasks.max

    Maximum number of tasks to use for this connector.

    Type:int
    Default:1
    Valid Values:[1,...]
    Importance:high
  • topics

    List of topics to consume, separated by commas

    Type:list
    Default:""
    Valid Values:
    Importance:high
  • topics.regex

    Regular expression giving topics to consume. Under the hood, the regex is compiled to a . Only one of topics or topics.regex should be specified.java.util.regex.Pattern

    Type:string
    Default:""
    Valid Values:valid regex
    Importance:high
  • key.converter

    Converter class used to convert between Kafka Connect format and the serialized form that is written to Kafka. This controls the format of the keys in messages written to or read from Kafka, and since this is independent of connectors it allows any connector to work with any serialization format. Examples of common formats include JSON and Avro.

    Type:class
    Default:null
    Valid Values:
    Importance:low
  • value.converter

    Converter class used to convert between Kafka Connect format and the serialized form that is written to Kafka. This controls the format of the values in messages written to or read from Kafka, and since this is independent of connectors it allows any connector to work with any serialization format. Examples of common formats include JSON and Avro.

    Type:class
    Default:null
    Valid Values:
    Importance:low
  • header.converter

    HeaderConverter class used to convert between Kafka Connect format and the serialized form that is written to Kafka. This controls the format of the header values in messages written to or read from Kafka, and since this is independent of connectors it allows any connector to work with any serialization format. Examples of common formats include JSON and Avro. By default, the SimpleHeaderConverter is used to serialize header values to strings and deserialize them by inferring the schemas.

    Type:class
    Default:null
    Valid Values:
    Importance:low
  • config.action.reload

    The action that Connect should take on the connector when changes in external configuration providers result in a change in the connector's configuration properties. A value of 'none' indicates that Connect will do nothing. A value of 'restart' indicates that Connect should restart/reload the connector with the updated configuration properties.The restart may actually be scheduled in the future if the external configuration provider indicates that a configuration value will expire in the future.

    Type:string
    Default:restart
    Valid Values:[none, restart]
    Importance:low
  • transforms

    Aliases for the transformations to be applied to records.

    Type:list
    Default:""
    Valid Values:non-null string, unique transformation aliases
    Importance:low
  • predicates

    Aliases for the predicates used by transformations.

    Type:list
    Default:""
    Valid Values:non-null string, unique predicate aliases
    Importance:low
  • errors.retry.timeout

    The maximum duration in milliseconds that a failed operation will be reattempted. The default is 0, which means no retries will be attempted. Use -1 for infinite retries.

    Type:long
    Default:0
    Valid Values:
    Importance:medium
  • errors.retry.delay.max.ms

    The maximum duration in milliseconds between consecutive retry attempts. Jitter will be added to the delay once this limit is reached to prevent thundering herd issues.

    Type:long
    Default:60000 (1 minute)
    Valid Values:
    Importance:medium
  • errors.tolerance

    Behavior for tolerating errors during connector operation. 'none' is the default value and signals that any error will result in an immediate connector task failure; 'all' changes the behavior to skip over problematic records.

    Type:string
    Default:none
    Valid Values:[none, all]
    Importance:medium
  • errors.log.enable

    If true, write each error and the details of the failed operation and problematic record to the Connect application log. This is 'false' by default, so that only errors that are not tolerated are reported.

    Type:boolean
    Default:false
    Valid Values:
    Importance:medium
  • errors.log.include.messages

    Whether to include in the log the Connect record that resulted in a failure.For sink records, the topic, partition, offset, and timestamp will be logged. For source records, the key and value (and their schemas), all headers, and the timestamp, Kafka topic, Kafka partition, source partition, and source offset will be logged. This is 'false' by default, which will prevent record keys, values, and headers from being written to log files.

    Type:boolean
    Default:false
    Valid Values:
    Importance:medium
  • errors.deadletterqueue.topic.name

    The name of the topic to be used as the dead letter queue (DLQ) for messages that result in an error when processed by this sink connector, or its transformations or converters. The topic name is blank by default, which means that no messages are to be recorded in the DLQ.

    Type:string
    Default:""
    Valid Values:
    Importance:medium
  • errors.deadletterqueue.topic.replication.factor

    Replication factor used to create the dead letter queue topic when it doesn't already exist.

    Type:short
    Default:3
    Valid Values:
    Importance:medium
  • errors.deadletterqueue.context.headers.enable

    If true, add headers containing error context to the messages written to the dead letter queue. To avoid clashing with headers from the original record, all error context header keys, all error context header keys will start with __connect.errors.

    Type:boolean
    Default:false
    Valid Values:
    Importance:medium

3.6 Kafka Streams Configs

Below is the configuration of the Kafka Streams client library.
  • application.id

    An identifier for the stream processing application. Must be unique within the Kafka cluster. It is used as 1) the default client-id prefix, 2) the group-id for membership management, 3) the changelog topic prefix.

    Type:string
    Default:
    Valid Values:
    Importance:high
  • bootstrap.servers

    A list of host/port pairs to use for establishing the initial connection to the Kafka cluster. The client will make use of all servers irrespective of which servers are specified here for bootstrapping—this list only impacts the initial hosts used to discover the full set of servers. This list should be in the form . Since these servers are just used for the initial connection to discover the full cluster membership (which may change dynamically), this list need not contain the full set of servers (you may want more than one, though, in case a server is down).host1:port1,host2:port2,...

    Type:list
    Default:
    Valid Values:
    Importance:high
  • num.standby.replicas

    The number of standby replicas for each task.

    Type:int
    Default:0
    Valid Values:
    Importance:high
  • state.dir

    Directory location for state store. This path must be unique for each streams instance sharing the same underlying filesystem.

    Type:string
    Default:/var/folders/qq/2qmvd8cd11x3fcd6wbgpn9pw0000gn/T//kafka-streams
    Valid Values:
    Importance:high
  • acceptable.recovery.lag

    The maximum acceptable lag (number of offsets to catch up) for a client to be considered caught-up enough to receive an active task assignment. Upon assignment, it will still restore the rest of the changelog before processing. To avoid a pause in processing during rebalances, this config should correspond to a recovery time of well under a minute for a given workload. Must be at least 0.

    Type:long
    Default:10000
    Valid Values:[0,...]
    Importance:medium
  • cache.max.bytes.buffering

    Maximum number of memory bytes to be used for buffering across all threads

    Type:long
    Default:10485760
    Valid Values:[0,...]
    Importance:medium
  • client.id

    An ID prefix string used for the client IDs of internal consumer, producer and restore-consumer, with pattern .<client.id>-StreamThread-<threadSequenceNumber$gt;-<consumer|producer|restore-consumer>

    Type:string
    Default:""
    Valid Values:
    Importance:medium
  • default.deserialization.exception.handler

    Exception handling class that implements the interface.org.apache.kafka.streams.errors.DeserializationExceptionHandler

    Type:class
    Default:org.apache.kafka.streams.errors.LogAndFailExceptionHandler
    Valid Values:
    Importance:medium
  • default.key.serde

    Default serializer / deserializer class for key that implements the interface. Note when windowed serde class is used, one needs to set the inner serde class that implements the interface via 'default.windowed.key.serde.inner' or 'default.windowed.value.serde.inner' as wellorg.apache.kafka.common.serialization.Serdeorg.apache.kafka.common.serialization.Serde

    Type:class
    Default:null
    Valid Values:
    Importance:medium
  • default.list.key.serde.inner

    Default inner class of list serde for key that implements the interface. This configuration will be read if and only if configuration is set to org.apache.kafka.common.serialization.Serdedefault.key.serdeorg.apache.kafka.common.serialization.Serdes.ListSerde

    Type:class
    Default:null
    Valid Values:
    Importance:medium
  • default.list.key.serde.type

    Default class for key that implements the interface. This configuration will be read if and only if configuration is set to Note when list serde class is used, one needs to set the inner serde class that implements the interface via 'default.list.key.serde.inner'java.util.Listdefault.key.serdeorg.apache.kafka.common.serialization.Serdes.ListSerdeorg.apache.kafka.common.serialization.Serde

    Type:class
    Default:null
    Valid Values:
    Importance:medium
  • default.list.value.serde.inner

    Default inner class of list serde for value that implements the interface. This configuration will be read if and only if configuration is set to org.apache.kafka.common.serialization.Serdedefault.value.serdeorg.apache.kafka.common.serialization.Serdes.ListSerde

    Type:class
    Default:null
    Valid Values:
    Importance:medium
  • default.list.value.serde.type

    Default class for value that implements the interface. This configuration will be read if and only if configuration is set to Note when list serde class is used, one needs to set the inner serde class that implements the interface via 'default.list.value.serde.inner'java.util.Listdefault.value.serdeorg.apache.kafka.common.serialization.Serdes.ListSerdeorg.apache.kafka.common.serialization.Serde

    Type:class
    Default:null
    Valid Values:
    Importance:medium
  • default.production.exception.handler

    Exception handling class that implements the interface.org.apache.kafka.streams.errors.ProductionExceptionHandler

    Type:class
    Default:org.apache.kafka.streams.errors.DefaultProductionExceptionHandler
    Valid Values:
    Importance:medium
  • default.timestamp.extractor

    Default timestamp extractor class that implements the interface.org.apache.kafka.streams.processor.TimestampExtractor

    Type:class
    Default:org.apache.kafka.streams.processor.FailOnInvalidTimestamp
    Valid Values:
    Importance:medium
  • default.value.serde

    Default serializer / deserializer class for value that implements the interface. Note when windowed serde class is used, one needs to set the inner serde class that implements the interface via 'default.windowed.key.serde.inner' or 'default.windowed.value.serde.inner' as wellorg.apache.kafka.common.serialization.Serdeorg.apache.kafka.common.serialization.Serde

    Type:class
    Default:null
    Valid Values:
    Importance:medium
  • max.task.idle.ms

    This config controls whether joins and merges may produce out-of-order results. The config value is the maximum amount of time in milliseconds a stream task will stay idle when it is fully caught up on some (but not all) input partitions to wait for producers to send additional records and avoid potential out-of-order record processing across multiple input streams. The default (zero) does not wait for producers to send more records, but it does wait to fetch data that is already present on the brokers. This default means that for records that are already present on the brokers, Streams will process them in timestamp order. Set to -1 to disable idling entirely and process any locally available data, even though doing so may produce out-of-order processing.

    Type:long
    Default:0
    Valid Values:
    Importance:medium
  • max.warmup.replicas

    The maximum number of warmup replicas (extra standbys beyond the configured num.standbys) that can be assigned at once for the purpose of keeping the task available on one instance while it is warming up on another instance it has been reassigned to. Used to throttle how much extra broker traffic and cluster state can be used for high availability. Must be at least 1.Note that one warmup replica corresponds to one Stream Task. Furthermore, note that each warmup replica can only be promoted to an active task during a rebalance (normally during a so-called probing rebalance, which occur at a frequency specified by the `probing.rebalance.interval.ms` config). This means that the maximum rate at which active tasks can be migrated from one Kafka Streams Instance to another instance can be determined by (`max.warmup.replicas` / `probing.rebalance.interval.ms`).

    Type:int
    Default:2
    Valid Values:[1,...]
    Importance:medium
  • num.stream.threads

    The number of threads to execute stream processing.

    Type:int
    Default:1
    Valid Values:
    Importance:medium
  • processing.guarantee

    The processing guarantee that should be used. Possible values are (default) and (requires brokers version 2.5 or higher). Deprecated options are (requires brokers version 0.11.0 or higher) and (requires brokers version 2.5 or higher). Note that exactly-once processing requires a cluster of at least three brokers by default what is the recommended setting for production; for development you can change this, by adjusting broker setting and .at_least_onceexactly_once_v2exactly_onceexactly_once_betatransaction.state.log.replication.factortransaction.state.log.min.isr

    Type:string
    Default:at_least_once
    Valid Values:[at_least_once, exactly_once, exactly_once_beta, exactly_once_v2]
    Importance:medium
  • rack.aware.assignment.tags

    List of client tag keys used to distribute standby replicas across Kafka Streams instances. When configured, Kafka Streams will make a best-effort to distribute the standby tasks over each client tag dimension.

    Type:list
    Default:""
    Valid Values:List containing maximum of 5 elements
    Importance:medium
  • replication.factor

    The replication factor for change log topics and repartition topics created by the stream processing application. The default of (meaning: use broker default replication factor) requires broker version 2.4 or newer-1

    Type:int
    Default:-1
    Valid Values:
    Importance:medium
  • security.protocol

    Protocol used to communicate with brokers. Valid values are: PLAINTEXT, SSL, SASL_PLAINTEXT, SASL_SSL.

    Type:string
    Default:PLAINTEXT
    Valid Values:(case insensitive) [SASL_SSL, PLAINTEXT, SSL, SASL_PLAINTEXT]
    Importance:medium
  • statestore.cache.max.bytes

    Maximum number of memory bytes to be used for statestore cache across all threads

    Type:long
    Default:10485760 (10 mebibytes)
    Valid Values:[0,...]
    Importance:medium
  • task.timeout.ms

    The maximum amount of time in milliseconds a task might stall due to internal errors and retries until an error is raised. For a timeout of 0ms, a task would raise an error for the first internal error. For any timeout larger than 0ms, a task will retry at least once before an error is raised.

    Type:long
    Default:300000 (5 minutes)
    Valid Values:[0,...]
    Importance:medium
  • topology.optimization

    A configuration telling Kafka Streams if it should optimize the topology and what optimizations to apply. Acceptable values are: "+NO_OPTIMIZATION+", "+OPTIMIZE+", or a comma separated list of specific optimizations: ("+REUSE_KTABLE_SOURCE_TOPICS+", "+MERGE_REPARTITION_TOPICS+" + "SINGLE_STORE_SELF_JOIN+")."NO_OPTIMIZATION" by default.

    Type:string
    Default:none
    Valid Values:[all, none, reuse.ktable.source.topics, merge.repartition.topics, single.store.self.join]
    Importance:medium
  • application.server

    A host:port pair pointing to a user-defined endpoint that can be used for state store discovery and interactive queries on this KafkaStreams instance.

    Type:string
    Default:""
    Valid Values:
    Importance:low
  • auto.include.jmx.reporter

    Deprecated. Whether to automatically include JmxReporter even if it's not listed in . This configuration will be removed in Kafka 4.0, users should instead include in in order to enable the JmxReporter.metric.reportersorg.apache.kafka.common.metrics.JmxReportermetric.reporters

    Type:boolean
    Default:true
    Valid Values:
    Importance:low
  • buffered.records.per.partition

    Maximum number of records to buffer per partition.

    Type:int
    Default:1000
    Valid Values:
    Importance:low
  • built.in.metrics.version

    Version of the built-in metrics to use.

    Type:string
    Default:latest
    Valid Values:[latest]
    Importance:low
  • commit.interval.ms

    The frequency in milliseconds with which to commit processing progress. For at-least-once processing, committing means to save the position (ie, offsets) of the processor. For exactly-once processing, it means to commit the transaction which includes to save the position and to make the committed data in the output topic visible to consumers with isolation level read_committed. (Note, if is set to , ,the default value is , otherwise the default value is .processing.guaranteeexactly_once_v2exactly_once10030000

    Type:long
    Default:30000 (30 seconds)
    Valid Values:[0,...]
    Importance:low
  • connections.max.idle.ms

    Close idle connections after the number of milliseconds specified by this config.

    Type:long
    Default:540000 (9 minutes)
    Valid Values:
    Importance:low
  • default.client.supplier

    Client supplier class that implements the interface.org.apache.kafka.streams.KafkaClientSupplier

    Type:class
    Default:org.apache.kafka.streams.processor.internals.DefaultKafkaClientSupplier
    Valid Values:
    Importance:low
  • default.dsl.store

    The default state store type used by DSL operators.

    Type:string
    Default:rocksDB
    Valid Values:[rocksDB, in_memory]
    Importance:low
  • metadata.max.age.ms

    The period of time in milliseconds after which we force a refresh of metadata even if we haven't seen any partition leadership changes to proactively discover any new brokers or partitions.

    Type:long
    Default:300000 (5 minutes)
    Valid Values:[0,...]
    Importance:low
  • metric.reporters

    A list of classes to use as metrics reporters. Implementing the interface allows plugging in classes that will be notified of new metric creation. The JmxReporter is always included to register JMX statistics.org.apache.kafka.common.metrics.MetricsReporter

    Type:list
    Default:""
    Valid Values:
    Importance:low
  • metrics.num.samples

    The number of samples maintained to compute metrics.

    Type:int
    Default:2
    Valid Values:[1,...]
    Importance:low
  • metrics.recording.level

    The highest recording level for metrics.

    Type:string
    Default:INFO
    Valid Values:[INFO, DEBUG, TRACE]
    Importance:low
  • metrics.sample.window.ms

    The window of time a metrics sample is computed over.

    Type:long
    Default:30000 (30 seconds)
    Valid Values:[0,...]
    Importance:low
  • poll.ms

    The amount of time in milliseconds to block waiting for input.

    Type:long
    Default:100
    Valid Values:
    Importance:low
  • probing.rebalance.interval.ms

    The maximum time in milliseconds to wait before triggering a rebalance to probe for warmup replicas that have finished warming up and are ready to become active. Probing rebalances will continue to be triggered until the assignment is balanced. Must be at least 1 minute.

    Type:long
    Default:600000 (10 minutes)
    Valid Values:[60000,...]
    Importance:low
  • receive.buffer.bytes

    The size of the TCP receive buffer (SO_RCVBUF) to use when reading data. If the value is -1, the OS default will be used.

    Type:int
    Default:32768 (32 kibibytes)
    Valid Values:[-1,...]
    Importance:low
  • reconnect.backoff.max.ms

    The maximum amount of time in milliseconds to wait when reconnecting to a broker that has repeatedly failed to connect. If provided, the backoff per host will increase exponentially for each consecutive connection failure, up to this maximum. After calculating the backoff increase, 20% random jitter is added to avoid connection storms.

    Type:long
    Default:1000 (1 second)
    Valid Values:[0,...]
    Importance:low
  • reconnect.backoff.ms

    The base amount of time to wait before attempting to reconnect to a given host. This avoids repeatedly connecting to a host in a tight loop. This backoff applies to all connection attempts by the client to a broker.

    Type:long
    Default:50
    Valid Values:[0,...]
    Importance:low
  • repartition.purge.interval.ms

    The frequency in milliseconds with which to delete fully consumed records from repartition topics. Purging will occur after at least this value since the last purge, but may be delayed until later. (Note, unlike , the default for this value remains unchanged when is set to ).commit.interval.msprocessing.guaranteeexactly_once_v2

    Type:long
    Default:30000 (30 seconds)
    Valid Values:[0,...]
    Importance:low
  • request.timeout.ms

    The configuration controls the maximum amount of time the client will wait for the response of a request. If the response is not received before the timeout elapses the client will resend the request if necessary or fail the request if retries are exhausted.

    Type:int
    Default:40000 (40 seconds)
    Valid Values:[0,...]
    Importance:low
  • retries

    Setting a value greater than zero will cause the client to resend any request that fails with a potentially transient error. It is recommended to set the value to either zero or `MAX_VALUE` and use corresponding timeout parameters to control how long a client should retry a request.

    Type:int
    Default:0
    Valid Values:[0,...,2147483647]
    Importance:low
  • retry.backoff.ms

    The amount of time to wait before attempting to retry a failed request to a given topic partition. This avoids repeatedly sending requests in a tight loop under some failure scenarios.

    Type:long
    Default:100
    Valid Values:[0,...]
    Importance:low
  • rocksdb.config.setter

    A Rocks DB config setter class or class name that implements the interfaceorg.apache.kafka.streams.state.RocksDBConfigSetter

    Type:class
    Default:null
    Valid Values:
    Importance:low
  • send.buffer.bytes

    The size of the TCP send buffer (SO_SNDBUF) to use when sending data. If the value is -1, the OS default will be used.

    Type:int
    Default:131072 (128 kibibytes)
    Valid Values:[-1,...]
    Importance:low
  • state.cleanup.delay.ms

    The amount of time in milliseconds to wait before deleting state when a partition has migrated. Only state directories that have not been modified for at least will be removedstate.cleanup.delay.ms

    Type:long
    Default:600000 (10 minutes)
    Valid Values:
    Importance:low
  • upgrade.from

    Allows upgrading in a backward compatible way. This is needed when upgrading from [0.10.0, 1.1] to 2.0+, or when upgrading from [2.0, 2.3] to 2.4+. When upgrading from 3.3 to a newer version it is not required to specify this config. Default is `null`. Accepted values are "0.10.0", "0.10.1", "0.10.2", "0.11.0", "1.0", "1.1", "2.0", "2.1", "2.2", "2.3", "2.4", "2.5", "2.6", "2.7", "2.8", "3.0", "3.1", "3.2", "3.3", "3.4" (for upgrading from the corresponding old version).

    Type:string
    Default:null
    Valid Values:[null, 0.10.0, 0.10.1, 0.10.2, 0.11.0, 1.0, 1.1, 2.0, 2.1, 2.2, 2.3, 2.4, 2.5, 2.6, 2.7, 2.8, 3.0, 3.1, 3.2, 3.3, 3.4]
    Importance:low
  • window.size.ms

    Sets window size for the deserializer in order to calculate window end times.

    Type:long
    Default:null
    Valid Values:
    Importance:low
  • windowed.inner.class.serde

    Default serializer / deserializer for the inner class of a windowed record. Must implement the interface. Note that setting this config in KafkaStreams application would result in an error as it is meant to be used only from Plain consumer client.org.apache.kafka.common.serialization.Serde

    Type:string
    Default:null
    Valid Values:
    Importance:low
  • windowstore.changelog.additional.retention.ms

    Added to a windows maintainMs to ensure data is not deleted from the log prematurely. Allows for clock drift. Default is 1 day

    Type:long
    Default:86400000 (1 day)
    Valid Values:
    Importance:low

3.7 Admin Configs

Below is the configuration of the Kafka Admin client library.
  • bootstrap.servers

    A list of host/port pairs to use for establishing the initial connection to the Kafka cluster. The client will make use of all servers irrespective of which servers are specified here for bootstrapping—this list only impacts the initial hosts used to discover the full set of servers. This list should be in the form . Since these servers are just used for the initial connection to discover the full cluster membership (which may change dynamically), this list need not contain the full set of servers (you may want more than one, though, in case a server is down).host1:port1,host2:port2,...

    Type:list
    Default:
    Valid Values:
    Importance:high
  • ssl.key.password

    The password of the private key in the key store file or the PEM key specified in 'ssl.keystore.key'.

    Type:password
    Default:null
    Valid Values:
    Importance:high
  • ssl.keystore.certificate.chain

    Certificate chain in the format specified by 'ssl.keystore.type'. Default SSL engine factory supports only PEM format with a list of X.509 certificates

    Type:password
    Default:null
    Valid Values:
    Importance:high
  • ssl.keystore.key

    Private key in the format specified by 'ssl.keystore.type'. Default SSL engine factory supports only PEM format with PKCS#8 keys. If the key is encrypted, key password must be specified using 'ssl.key.password'

    Type:password
    Default:null
    Valid Values:
    Importance:high
  • ssl.keystore.location

    The location of the key store file. This is optional for client and can be used for two-way authentication for client.

    Type:string
    Default:null
    Valid Values:
    Importance:high
  • ssl.keystore.password

    The store password for the key store file. This is optional for client and only needed if 'ssl.keystore.location' is configured. Key store password is not supported for PEM format.

    Type:password
    Default:null
    Valid Values:
    Importance:high
  • ssl.truststore.certificates

    Trusted certificates in the format specified by 'ssl.truststore.type'. Default SSL engine factory supports only PEM format with X.509 certificates.

    Type:password
    Default:null
    Valid Values:
    Importance:high
  • ssl.truststore.location

    The location of the trust store file.

    Type:string
    Default:null
    Valid Values:
    Importance:high
  • ssl.truststore.password

    The password for the trust store file. If a password is not set, trust store file configured will still be used, but integrity checking is disabled. Trust store password is not supported for PEM format.

    Type:password
    Default:null
    Valid Values:
    Importance:high
  • client.dns.lookup

    Controls how the client uses DNS lookups. If set to , connect to each returned IP address in sequence until a successful connection is established. After a disconnection, the next IP is used. Once all IPs have been used once, the client resolves the IP(s) from the hostname again (both the JVM and the OS cache DNS name lookups, however). If set to , resolve each bootstrap address into a list of canonical names. After the bootstrap phase, this behaves the same as .use_all_dns_ipsresolve_canonical_bootstrap_servers_onlyuse_all_dns_ips

    Type:string
    Default:use_all_dns_ips
    Valid Values:[use_all_dns_ips, resolve_canonical_bootstrap_servers_only]
    Importance:medium
  • client.id

    An id string to pass to the server when making requests. The purpose of this is to be able to track the source of requests beyond just ip/port by allowing a logical application name to be included in server-side request logging.

    Type:string
    Default:""
    Valid Values:
    Importance:medium
  • connections.max.idle.ms

    Close idle connections after the number of milliseconds specified by this config.

    Type:long
    Default:300000 (5 minutes)
    Valid Values:
    Importance:medium
  • default.api.timeout.ms

    Specifies the timeout (in milliseconds) for client APIs. This configuration is used as the default timeout for all client operations that do not specify a parameter.timeout

    Type:int
    Default:60000 (1 minute)
    Valid Values:[0,...]
    Importance:medium
  • receive.buffer.bytes

    The size of the TCP receive buffer (SO_RCVBUF) to use when reading data. If the value is -1, the OS default will be used.

    Type:int
    Default:65536 (64 kibibytes)
    Valid Values:[-1,...]
    Importance:medium
  • request.timeout.ms

    The configuration controls the maximum amount of time the client will wait for the response of a request. If the response is not received before the timeout elapses the client will resend the request if necessary or fail the request if retries are exhausted.

    Type:int
    Default:30000 (30 seconds)
    Valid Values:[0,...]
    Importance:medium
  • sasl.client.callback.handler.class

    The fully qualified name of a SASL client callback handler class that implements the AuthenticateCallbackHandler interface.

    Type:class
    Default:null
    Valid Values:
    Importance:medium
  • sasl.jaas.config

    JAAS login context parameters for SASL connections in the format used by JAAS configuration files. JAAS configuration file format is described here. The format for the value is: . For brokers, the config must be prefixed with listener prefix and SASL mechanism name in lower-case. For example, listener.name.sasl_ssl.scram-sha-256.sasl.jaas.config=com.example.ScramLoginModule required;loginModuleClass controlFlag (optionName=optionValue)*;

    Type:password
    Default:null
    Valid Values:
    Importance:medium
  • sasl.kerberos.service.name

    The Kerberos principal name that Kafka runs as. This can be defined either in Kafka's JAAS config or in Kafka's config.

    Type:string
    Default:null
    Valid Values:
    Importance:medium
  • sasl.login.callback.handler.class

    The fully qualified name of a SASL login callback handler class that implements the AuthenticateCallbackHandler interface. For brokers, login callback handler config must be prefixed with listener prefix and SASL mechanism name in lower-case. For example, listener.name.sasl_ssl.scram-sha-256.sasl.login.callback.handler.class=com.example.CustomScramLoginCallbackHandler

    Type:class
    Default:null
    Valid Values:
    Importance:medium
  • sasl.login.class

    The fully qualified name of a class that implements the Login interface. For brokers, login config must be prefixed with listener prefix and SASL mechanism name in lower-case. For example, listener.name.sasl_ssl.scram-sha-256.sasl.login.class=com.example.CustomScramLogin

    Type:class
    Default:null
    Valid Values:
    Importance:medium
  • sasl.mechanism

    SASL mechanism used for client connections. This may be any mechanism for which a security provider is available. GSSAPI is the default mechanism.

    Type:string
    Default:GSSAPI
    Valid Values:
    Importance:medium
  • sasl.oauthbearer.jwks.endpoint.url

    The OAuth/OIDC provider URL from which the provider's JWKS (JSON Web Key Set) can be retrieved. The URL can be HTTP(S)-based or file-based. If the URL is HTTP(S)-based, the JWKS data will be retrieved from the OAuth/OIDC provider via the configured URL on broker startup. All then-current keys will be cached on the broker for incoming requests. If an authentication request is received for a JWT that includes a "kid" header claim value that isn't yet in the cache, the JWKS endpoint will be queried again on demand. However, the broker polls the URL every sasl.oauthbearer.jwks.endpoint.refresh.ms milliseconds to refresh the cache with any forthcoming keys before any JWT requests that include them are received. If the URL is file-based, the broker will load the JWKS file from a configured location on startup. In the event that the JWT includes a "kid" header value that isn't in the JWKS file, the broker will reject the JWT and authentication will fail.

    Type:string
    Default:null
    Valid Values:
    Importance:medium
  • sasl.oauthbearer.token.endpoint.url

    The URL for the OAuth/OIDC identity provider. If the URL is HTTP(S)-based, it is the issuer's token endpoint URL to which requests will be made to login based on the configuration in sasl.jaas.config. If the URL is file-based, it specifies a file containing an access token (in JWT serialized form) issued by the OAuth/OIDC identity provider to use for authorization.

    Type:string
    Default:null
    Valid Values:
    Importance:medium
  • security.protocol

    Protocol used to communicate with brokers. Valid values are: PLAINTEXT, SSL, SASL_PLAINTEXT, SASL_SSL.

    Type:string
    Default:PLAINTEXT
    Valid Values:(case insensitive) [SASL_SSL, PLAINTEXT, SSL, SASL_PLAINTEXT]
    Importance:medium
  • send.buffer.bytes

    The size of the TCP send buffer (SO_SNDBUF) to use when sending data. If the value is -1, the OS default will be used.

    Type:int
    Default:131072 (128 kibibytes)
    Valid Values:[-1,...]
    Importance:medium
  • socket.connection.setup.timeout.max.ms

    The maximum amount of time the client will wait for the socket connection to be established. The connection setup timeout will increase exponentially for each consecutive connection failure up to this maximum. To avoid connection storms, a randomization factor of 0.2 will be applied to the timeout resulting in a random range between 20% below and 20% above the computed value.

    Type:long
    Default:30000 (30 seconds)
    Valid Values:
    Importance:medium
  • socket.connection.setup.timeout.ms

    The amount of time the client will wait for the socket connection to be established. If the connection is not built before the timeout elapses, clients will close the socket channel.

    Type:long
    Default:10000 (10 seconds)
    Valid Values:
    Importance:medium
  • ssl.enabled.protocols

    The list of protocols enabled for SSL connections. The default is 'TLSv1.2,TLSv1.3' when running with Java 11 or newer, 'TLSv1.2' otherwise. With the default value for Java 11, clients and servers will prefer TLSv1.3 if both support it and fallback to TLSv1.2 otherwise (assuming both support at least TLSv1.2). This default should be fine for most cases. Also see the config documentation for `ssl.protocol`.

    Type:list
    Default:TLSv1.2,TLSv1.3
    Valid Values:
    Importance:medium
  • ssl.keystore.type

    The file format of the key store file. This is optional for client. The values currently supported by the default `ssl.engine.factory.class` are [JKS, PKCS12, PEM].

    Type:string
    Default:JKS
    Valid Values:
    Importance:medium
  • ssl.protocol

    The SSL protocol used to generate the SSLContext. The default is 'TLSv1.3' when running with Java 11 or newer, 'TLSv1.2' otherwise. This value should be fine for most use cases. Allowed values in recent JVMs are 'TLSv1.2' and 'TLSv1.3'. 'TLS', 'TLSv1.1', 'SSL', 'SSLv2' and 'SSLv3' may be supported in older JVMs, but their usage is discouraged due to known security vulnerabilities. With the default value for this config and 'ssl.enabled.protocols', clients will downgrade to 'TLSv1.2' if the server does not support 'TLSv1.3'. If this config is set to 'TLSv1.2', clients will not use 'TLSv1.3' even if it is one of the values in ssl.enabled.protocols and the server only supports 'TLSv1.3'.

    Type:string
    Default:TLSv1.3
    Valid Values:
    Importance:medium
  • ssl.provider

    The name of the security provider used for SSL connections. Default value is the default security provider of the JVM.

    Type:string
    Default:null
    Valid Values:
    Importance:medium
  • ssl.truststore.type

    The file format of the trust store file. The values currently supported by the default `ssl.engine.factory.class` are [JKS, PKCS12, PEM].

    Type:string
    Default:JKS
    Valid Values:
    Importance:medium
  • auto.include.jmx.reporter

    Deprecated. Whether to automatically include JmxReporter even if it's not listed in . This configuration will be removed in Kafka 4.0, users should instead include in in order to enable the JmxReporter.metric.reportersorg.apache.kafka.common.metrics.JmxReportermetric.reporters

    Type:boolean
    Default:true
    Valid Values:
    Importance:low
  • metadata.max.age.ms

    The period of time in milliseconds after which we force a refresh of metadata even if we haven't seen any partition leadership changes to proactively discover any new brokers or partitions.

    Type:long
    Default:300000 (5 minutes)
    Valid Values:[0,...]
    Importance:low
  • metric.reporters

    A list of classes to use as metrics reporters. Implementing the interface allows plugging in classes that will be notified of new metric creation. The JmxReporter is always included to register JMX statistics.org.apache.kafka.common.metrics.MetricsReporter

    Type:list
    Default:""
    Valid Values:
    Importance:low
  • metrics.num.samples

    The number of samples maintained to compute metrics.

    Type:int
    Default:2
    Valid Values:[1,...]
    Importance:low
  • metrics.recording.level

    The highest recording level for metrics.

    Type:string
    Default:INFO
    Valid Values:[INFO, DEBUG, TRACE]
    Importance:low
  • metrics.sample.window.ms

    The window of time a metrics sample is computed over.

    Type:long
    Default:30000 (30 seconds)
    Valid Values:[0,...]
    Importance:low
  • reconnect.backoff.max.ms

    The maximum amount of time in milliseconds to wait when reconnecting to a broker that has repeatedly failed to connect. If provided, the backoff per host will increase exponentially for each consecutive connection failure, up to this maximum. After calculating the backoff increase, 20% random jitter is added to avoid connection storms.

    Type:long
    Default:1000 (1 second)
    Valid Values:[0,...]
    Importance:low
  • reconnect.backoff.ms

    The base amount of time to wait before attempting to reconnect to a given host. This avoids repeatedly connecting to a host in a tight loop. This backoff applies to all connection attempts by the client to a broker.

    Type:long
    Default:50
    Valid Values:[0,...]
    Importance:low
  • retries

    Setting a value greater than zero will cause the client to resend any request that fails with a potentially transient error. It is recommended to set the value to either zero or `MAX_VALUE` and use corresponding timeout parameters to control how long a client should retry a request.

    Type:int
    Default:2147483647
    Valid Values:[0,...,2147483647]
    Importance:low
  • retry.backoff.ms

    The amount of time to wait before attempting to retry a failed request. This avoids repeatedly sending requests in a tight loop under some failure scenarios.

    Type:long
    Default:100
    Valid Values:[0,...]
    Importance:low
  • sasl.kerberos.kinit.cmd

    Kerberos kinit command path.

    Type:string
    Default:/usr/bin/kinit
    Valid Values:
    Importance:low
  • sasl.kerberos.min.time.before.relogin

    Login thread sleep time between refresh attempts.

    Type:long
    Default:60000
    Valid Values:
    Importance:low
  • sasl.kerberos.ticket.renew.jitter

    Percentage of random jitter added to the renewal time.

    Type:double
    Default:0.05
    Valid Values:
    Importance:low
  • sasl.kerberos.ticket.renew.window.factor

    Login thread will sleep until the specified window factor of time from last refresh to ticket's expiry has been reached, at which time it will try to renew the ticket.

    Type:double
    Default:0.8
    Valid Values:
    Importance:low
  • sasl.login.connect.timeout.ms

    The (optional) value in milliseconds for the external authentication provider connection timeout. Currently applies only to OAUTHBEARER.

    Type:int
    Default:null
    Valid Values:
    Importance:low
  • sasl.login.read.timeout.ms

    The (optional) value in milliseconds for the external authentication provider read timeout. Currently applies only to OAUTHBEARER.

    Type:int
    Default:null
    Valid Values:
    Importance:low
  • sasl.login.refresh.buffer.seconds

    The amount of buffer time before credential expiration to maintain when refreshing a credential, in seconds. If a refresh would otherwise occur closer to expiration than the number of buffer seconds then the refresh will be moved up to maintain as much of the buffer time as possible. Legal values are between 0 and 3600 (1 hour); a default value of 300 (5 minutes) is used if no value is specified. This value and sasl.login.refresh.min.period.seconds are both ignored if their sum exceeds the remaining lifetime of a credential. Currently applies only to OAUTHBEARER.

    Type:short
    Default:300
    Valid Values:[0,...,3600]
    Importance:low
  • sasl.login.refresh.min.period.seconds

    The desired minimum time for the login refresh thread to wait before refreshing a credential, in seconds. Legal values are between 0 and 900 (15 minutes); a default value of 60 (1 minute) is used if no value is specified. This value and sasl.login.refresh.buffer.seconds are both ignored if their sum exceeds the remaining lifetime of a credential. Currently applies only to OAUTHBEARER.

    Type:short
    Default:60
    Valid Values:[0,...,900]
    Importance:low
  • sasl.login.refresh.window.factor

    Login refresh thread will sleep until the specified window factor relative to the credential's lifetime has been reached, at which time it will try to refresh the credential. Legal values are between 0.5 (50%) and 1.0 (100%) inclusive; a default value of 0.8 (80%) is used if no value is specified. Currently applies only to OAUTHBEARER.

    Type:double
    Default:0.8
    Valid Values:[0.5,...,1.0]
    Importance:low
  • sasl.login.refresh.window.jitter

    The maximum amount of random jitter relative to the credential's lifetime that is added to the login refresh thread's sleep time. Legal values are between 0 and 0.25 (25%) inclusive; a default value of 0.05 (5%) is used if no value is specified. Currently applies only to OAUTHBEARER.

    Type:double
    Default:0.05
    Valid Values:[0.0,...,0.25]
    Importance:low
  • sasl.login.retry.backoff.max.ms

    The (optional) value in milliseconds for the maximum wait between login attempts to the external authentication provider. Login uses an exponential backoff algorithm with an initial wait based on the sasl.login.retry.backoff.ms setting and will double in wait length between attempts up to a maximum wait length specified by the sasl.login.retry.backoff.max.ms setting. Currently applies only to OAUTHBEARER.

    Type:long
    Default:10000 (10 seconds)
    Valid Values:
    Importance:low
  • sasl.login.retry.backoff.ms

    The (optional) value in milliseconds for the initial wait between login attempts to the external authentication provider. Login uses an exponential backoff algorithm with an initial wait based on the sasl.login.retry.backoff.ms setting and will double in wait length between attempts up to a maximum wait length specified by the sasl.login.retry.backoff.max.ms setting. Currently applies only to OAUTHBEARER.

    Type:long
    Default:100
    Valid Values:
    Importance:low
  • sasl.oauthbearer.clock.skew.seconds

    The (optional) value in seconds to allow for differences between the time of the OAuth/OIDC identity provider and the broker.

    Type:int
    Default:30
    Valid Values:
    Importance:low
  • sasl.oauthbearer.expected.audience

    The (optional) comma-delimited setting for the broker to use to verify that the JWT was issued for one of the expected audiences. The JWT will be inspected for the standard OAuth "aud" claim and if this value is set, the broker will match the value from JWT's "aud" claim to see if there is an exact match. If there is no match, the broker will reject the JWT and authentication will fail.

    Type:list
    Default:null
    Valid Values:
    Importance:low
  • sasl.oauthbearer.expected.issuer

    The (optional) setting for the broker to use to verify that the JWT was created by the expected issuer. The JWT will be inspected for the standard OAuth "iss" claim and if this value is set, the broker will match it exactly against what is in the JWT's "iss" claim. If there is no match, the broker will reject the JWT and authentication will fail.

    Type:string
    Default:null
    Valid Values:
    Importance:low
  • sasl.oauthbearer.jwks.endpoint.refresh.ms

    The (optional) value in milliseconds for the broker to wait between refreshing its JWKS (JSON Web Key Set) cache that contains the keys to verify the signature of the JWT.

    Type:long
    Default:3600000 (1 hour)
    Valid Values:
    Importance:low
  • sasl.oauthbearer.jwks.endpoint.retry.backoff.max.ms

    The (optional) value in milliseconds for the maximum wait between attempts to retrieve the JWKS (JSON Web Key Set) from the external authentication provider. JWKS retrieval uses an exponential backoff algorithm with an initial wait based on the sasl.oauthbearer.jwks.endpoint.retry.backoff.ms setting and will double in wait length between attempts up to a maximum wait length specified by the sasl.oauthbearer.jwks.endpoint.retry.backoff.max.ms setting.

    Type:long
    Default:10000 (10 seconds)
    Valid Values:
    Importance:low
  • sasl.oauthbearer.jwks.endpoint.retry.backoff.ms

    The (optional) value in milliseconds for the initial wait between JWKS (JSON Web Key Set) retrieval attempts from the external authentication provider. JWKS retrieval uses an exponential backoff algorithm with an initial wait based on the sasl.oauthbearer.jwks.endpoint.retry.backoff.ms setting and will double in wait length between attempts up to a maximum wait length specified by the sasl.oauthbearer.jwks.endpoint.retry.backoff.max.ms setting.

    Type:long
    Default:100
    Valid Values:
    Importance:low
  • sasl.oauthbearer.scope.claim.name

    The OAuth claim for the scope is often named "scope", but this (optional) setting can provide a different name to use for the scope included in the JWT payload's claims if the OAuth/OIDC provider uses a different name for that claim.

    Type:string
    Default:scope
    Valid Values:
    Importance:low
  • sasl.oauthbearer.sub.claim.name

    The OAuth claim for the subject is often named "sub", but this (optional) setting can provide a different name to use for the subject included in the JWT payload's claims if the OAuth/OIDC provider uses a different name for that claim.

    Type:string
    Default:sub
    Valid Values:
    Importance:low
  • security.providers

    A list of configurable creator classes each returning a provider implementing security algorithms. These classes should implement the interface.org.apache.kafka.common.security.auth.SecurityProviderCreator

    Type:string
    Default:null
    Valid Values:
    Importance:low
  • ssl.cipher.suites

    A list of cipher suites. This is a named combination of authentication, encryption, MAC and key exchange algorithm used to negotiate the security settings for a network connection using TLS or SSL network protocol. By default all the available cipher suites are supported.

    Type:list
    Default:null
    Valid Values:
    Importance:low
  • ssl.endpoint.identification.algorithm

    The endpoint identification algorithm to validate server hostname using server certificate.

    Type:string
    Default:https
    Valid Values:
    Importance:low
  • ssl.engine.factory.class

    The class of type org.apache.kafka.common.security.auth.SslEngineFactory to provide SSLEngine objects. Default value is org.apache.kafka.common.security.ssl.DefaultSslEngineFactory

    Type:class
    Default:null
    Valid Values:
    Importance:low
  • ssl.keymanager.algorithm

    The algorithm used by key manager factory for SSL connections. Default value is the key manager factory algorithm configured for the Java Virtual Machine.

    Type:string
    Default:SunX509
    Valid Values:
    Importance:low
  • ssl.secure.random.implementation

    The SecureRandom PRNG implementation to use for SSL cryptography operations.

    Type:string
    Default:null
    Valid Values:
    Importance:low
  • ssl.trustmanager.algorithm

    The algorithm used by trust manager factory for SSL connections. Default value is the trust manager factory algorithm configured for the Java Virtual Machine.

    Type:string
    Default:PKIX
    Valid Values:
    Importance:low

3.8 System Properties

Kafka supports some configuration that can be enabled through Java system properties. System properties are usually set by passing the -D flag to the Java virtual machine in which Kafka components are running. Below are the supported system properties.
  • org.apache.kafka.disallowed.login.modules

    This system property is used to disable the problematic login modules usage in SASL JAAS configuration. This property accepts comma-separated list of loginModule names. By default com.sun.security.auth.module.JndiLoginModule loginModule is disabled.

    If users want to enable JndiLoginModule, users need to explicitly reset the system property like below. We advise the users to validate configurations and only allow trusted JNDI configurations. For more details CVE-2023-25194.

     -Dorg.apache.kafka.disallowed.login.modules=

    To disable more loginModules, update the system property with comma-separated loginModule names. Make sure to explicitly add JndiLoginModule module name to the comma-separated list like below.

     -Dorg.apache.kafka.disallowed.login.modules=com.sun.security.auth.module.JndiLoginModule,com.ibm.security.auth.module.LdapLoginModule,com.ibm.security.auth.module.Krb5LoginModule
    Since:3.4.0
    Default Value:com.sun.security.auth.module.JndiLoginModule

4. 设计

4.1 Motivation

We designed Kafka to be able to act as a unified platform for handling all the real-time data feeds a large company might have. To do this we had to think through a fairly broad set of use cases.

It would have to have high-throughput to support high volume event streams such as real-time log aggregation.

It would need to deal gracefully with large data backlogs to be able to support periodic data loads from offline systems.

It also meant the system would have to handle low-latency delivery to handle more traditional messaging use-cases.

We wanted to support partitioned, distributed, real-time processing of these feeds to create new, derived feeds. This motivated our partitioning and consumer model.

Finally in cases where the stream is fed into other data systems for serving, we knew the system would have to be able to guarantee fault-tolerance in the presence of machine failures.

Supporting these uses led us to a design with a number of unique elements, more akin to a database log than a traditional messaging system. We will outline some elements of the design in the following sections.

4.2 Persistence

Don't fear the filesystem!

Kafka relies heavily on the filesystem for storing and caching messages. There is a general perception that "disks are slow" which makes people skeptical that a persistent structure can offer competitive performance. In fact disks are both much slower and much faster than people expect depending on how they are used; and a properly designed disk structure can often be as fast as the network.

The key fact about disk performance is that the throughput of hard drives has been diverging from the latency of a disk seek for the last decade. As a result the performance of linear writes on a JBOD configuration with six 7200rpm SATA RAID-5 array is about 600MB/sec but the performance of random writes is only about 100k/sec—a difference of over 6000X. These linear reads and writes are the most predictable of all usage patterns, and are heavily optimized by the operating system. A modern operating system provides read-ahead and write-behind techniques that prefetch data in large block multiples and group smaller logical writes into large physical writes. A further discussion of this issue can be found in this ACM Queue article; they actually find that sequential disk access can in some cases be faster than random memory access!

To compensate for this performance divergence, modern operating systems have become increasingly aggressive in their use of main memory for disk caching. A modern OS will happily divert all free memory to disk caching with little performance penalty when the memory is reclaimed. All disk reads and writes will go through this unified cache. This feature cannot easily be turned off without using direct I/O, so even if a process maintains an in-process cache of the data, this data will likely be duplicated in OS pagecache, effectively storing everything twice.

Furthermore, we are building on top of the JVM, and anyone who has spent any time with Java memory usage knows two things:

  1. The memory overhead of objects is very high, often doubling the size of the data stored (or worse).
  2. Java garbage collection becomes increasingly fiddly and slow as the in-heap data increases.

As a result of these factors using the filesystem and relying on pagecache is superior to maintaining an in-memory cache or other structure—we at least double the available cache by having automatic access to all free memory, and likely double again by storing a compact byte structure rather than individual objects. Doing so will result in a cache of up to 28-30GB on a 32GB machine without GC penalties. Furthermore, this cache will stay warm even if the service is restarted, whereas the in-process cache will need to be rebuilt in memory (which for a 10GB cache may take 10 minutes) or else it will need to start with a completely cold cache (which likely means terrible initial performance). This also greatly simplifies the code as all logic for maintaining coherency between the cache and filesystem is now in the OS, which tends to do so more efficiently and more correctly than one-off in-process attempts. If your disk usage favors linear reads then read-ahead is effectively pre-populating this cache with useful data on each disk read.

This suggests a design which is very simple: rather than maintain as much as possible in-memory and flush it all out to the filesystem in a panic when we run out of space, we invert that. All data is immediately written to a persistent log on the filesystem without necessarily flushing to disk. In effect this just means that it is transferred into the kernel's pagecache.

This style of pagecache-centric design is described in an article on the design of Varnish here (along with a healthy dose of arrogance).

Constant Time Suffices

The persistent data structure used in messaging systems are often a per-consumer queue with an associated BTree or other general-purpose random access data structures to maintain metadata about messages. BTrees are the most versatile data structure available, and make it possible to support a wide variety of transactional and non-transactional semantics in the messaging system. They do come with a fairly high cost, though: Btree operations are O(log N). Normally O(log N) is considered essentially equivalent to constant time, but this is not true for disk operations. Disk seeks come at 10 ms a pop, and each disk can do only one seek at a time so parallelism is limited. Hence even a handful of disk seeks leads to very high overhead. Since storage systems mix very fast cached operations with very slow physical disk operations, the observed performance of tree structures is often superlinear as data increases with fixed cache--i.e. doubling your data makes things much worse than twice as slow.

Intuitively a persistent queue could be built on simple reads and appends to files as is commonly the case with logging solutions. This structure has the advantage that all operations are O(1) and reads do not block writes or each other. This has obvious performance advantages since the performance is completely decoupled from the data size—one server can now take full advantage of a number of cheap, low-rotational speed 1+TB SATA drives. Though they have poor seek performance, these drives have acceptable performance for large reads and writes and come at 1/3 the price and 3x the capacity.

Having access to virtually unlimited disk space without any performance penalty means that we can provide some features not usually found in a messaging system. For example, in Kafka, instead of attempting to delete messages as soon as they are consumed, we can retain messages for a relatively long period (say a week). This leads to a great deal of flexibility for consumers, as we will describe.

4.3 Efficiency

We have put significant effort into efficiency. One of our primary use cases is handling web activity data, which is very high volume: each page view may generate dozens of writes. Furthermore, we assume each message published is read by at least one consumer (often many), hence we strive to make consumption as cheap as possible.

We have also found, from experience building and running a number of similar systems, that efficiency is a key to effective multi-tenant operations. If the downstream infrastructure service can easily become a bottleneck due to a small bump in usage by the application, such small changes will often create problems. By being very fast we help ensure that the application will tip-over under load before the infrastructure. This is particularly important when trying to run a centralized service that supports dozens or hundreds of applications on a centralized cluster as changes in usage patterns are a near-daily occurrence.

We discussed disk efficiency in the previous section. Once poor disk access patterns have been eliminated, there are two common causes of inefficiency in this type of system: too many small I/O operations, and excessive byte copying.

The small I/O problem happens both between the client and the server and in the server's own persistent operations.

To avoid this, our protocol is built around a "message set" abstraction that naturally groups messages together. This allows network requests to group messages together and amortize the overhead of the network roundtrip rather than sending a single message at a time. The server in turn appends chunks of messages to its log in one go, and the consumer fetches large linear chunks at a time.

This simple optimization produces orders of magnitude speed up. Batching leads to larger network packets, larger sequential disk operations, contiguous memory blocks, and so on, all of which allows Kafka to turn a bursty stream of random message writes into linear writes that flow to the consumers.

The other inefficiency is in byte copying. At low message rates this is not an issue, but under load the impact is significant. To avoid this we employ a standardized binary message format that is shared by the producer, the broker, and the consumer (so data chunks can be transferred without modification between them).

The message log maintained by the broker is itself just a directory of files, each populated by a sequence of message sets that have been written to disk in the same format used by the producer and consumer. Maintaining this common format allows optimization of the most important operation: network transfer of persistent log chunks. Modern unix operating systems offer a highly optimized code path for transferring data out of pagecache to a socket; in Linux this is done with the sendfile system call.

To understand the impact of sendfile, it is important to understand the common data path for transfer of data from file to socket:

  1. The operating system reads data from the disk into pagecache in kernel space
  2. The application reads the data from kernel space into a user-space buffer
  3. The application writes the data back into kernel space into a socket buffer
  4. The operating system copies the data from the socket buffer to the NIC buffer where it is sent over the network

This is clearly inefficient, there are four copies and two system calls. Using sendfile, this re-copying is avoided by allowing the OS to send the data from pagecache to the network directly. So in this optimized path, only the final copy to the NIC buffer is needed.

We expect a common use case to be multiple consumers on a topic. Using the zero-copy optimization above, data is copied into pagecache exactly once and reused on each consumption instead of being stored in memory and copied out to user-space every time it is read. This allows messages to be consumed at a rate that approaches the limit of the network connection.

This combination of pagecache and sendfile means that on a Kafka cluster where the consumers are mostly caught up you will see no read activity on the disks whatsoever as they will be serving data entirely from cache.

TLS/SSL libraries operate at the user space (in-kernel is currently not supported by Kafka). Due to this restriction, is not used when SSL is enabled. For enabling SSL configuration, refer to and SSL_sendfilesendfilesecurity.protocolsecurity.inter.broker.protocol

For more background on the sendfile and zero-copy support in Java, see this article.

End-to-end Batch Compression

In some cases the bottleneck is actually not CPU or disk but network bandwidth. This is particularly true for a data pipeline that needs to send messages between data centers over a wide-area network. Of course, the user can always compress its messages one at a time without any support needed from Kafka, but this can lead to very poor compression ratios as much of the redundancy is due to repetition between messages of the same type (e.g. field names in JSON or user agents in web logs or common string values). Efficient compression requires compressing multiple messages together rather than compressing each message individually.

Kafka supports this with an efficient batching format. A batch of messages can be clumped together compressed and sent to the server in this form. This batch of messages will be written in compressed form and will remain compressed in the log and will only be decompressed by the consumer.

Kafka supports GZIP, Snappy, LZ4 and ZStandard compression protocols. More details on compression can be found here.

4.4 The Producer

Load balancing

The producer sends data directly to the broker that is the leader for the partition without any intervening routing tier. To help the producer do this all Kafka nodes can answer a request for metadata about which servers are alive and where the leaders for the partitions of a topic are at any given time to allow the producer to appropriately direct its requests.

The client controls which partition it publishes messages to. This can be done at random, implementing a kind of random load balancing, or it can be done by some semantic partitioning function. We expose the interface for semantic partitioning by allowing the user to specify a key to partition by and using this to hash to a partition (there is also an option to override the partition function if need be). For example if the key chosen was a user id then all data for a given user would be sent to the same partition. This in turn will allow consumers to make locality assumptions about their consumption. This style of partitioning is explicitly designed to allow locality-sensitive processing in consumers.

Asynchronous send

Batching is one of the big drivers of efficiency, and to enable batching the Kafka producer will attempt to accumulate data in memory and to send out larger batches in a single request. The batching can be configured to accumulate no more than a fixed number of messages and to wait no longer than some fixed latency bound (say 64k or 10 ms). This allows the accumulation of more bytes to send, and few larger I/O operations on the servers. This buffering is configurable and gives a mechanism to trade off a small amount of additional latency for better throughput.

Details on configuration and the api for the producer can be found elsewhere in the documentation.

4.5 The Consumer

The Kafka consumer works by issuing "fetch" requests to the brokers leading the partitions it wants to consume. The consumer specifies its offset in the log with each request and receives back a chunk of log beginning from that position. The consumer thus has significant control over this position and can rewind it to re-consume data if need be.

Push vs. pull

An initial question we considered is whether consumers should pull data from brokers or brokers should push data to the consumer. In this respect Kafka follows a more traditional design, shared by most messaging systems, where data is pushed to the broker from the producer and pulled from the broker by the consumer. Some logging-centric systems, such as Scribe and Apache Flume, follow a very different push-based path where data is pushed downstream. There are pros and cons to both approaches. However, a push-based system has difficulty dealing with diverse consumers as the broker controls the rate at which data is transferred. The goal is generally for the consumer to be able to consume at the maximum possible rate; unfortunately, in a push system this means the consumer tends to be overwhelmed when its rate of consumption falls below the rate of production (a denial of service attack, in essence). A pull-based system has the nicer property that the consumer simply falls behind and catches up when it can. This can be mitigated with some kind of backoff protocol by which the consumer can indicate it is overwhelmed, but getting the rate of transfer to fully utilize (but never over-utilize) the consumer is trickier than it seems. Previous attempts at building systems in this fashion led us to go with a more traditional pull model.

Another advantage of a pull-based system is that it lends itself to aggressive batching of data sent to the consumer. A push-based system must choose to either send a request immediately or accumulate more data and then send it later without knowledge of whether the downstream consumer will be able to immediately process it. If tuned for low latency, this will result in sending a single message at a time only for the transfer to end up being buffered anyway, which is wasteful. A pull-based design fixes this as the consumer always pulls all available messages after its current position in the log (or up to some configurable max size). So one gets optimal batching without introducing unnecessary latency.

The deficiency of a naive pull-based system is that if the broker has no data the consumer may end up polling in a tight loop, effectively busy-waiting for data to arrive. To avoid this we have parameters in our pull request that allow the consumer request to block in a "long poll" waiting until data arrives (and optionally waiting until a given number of bytes is available to ensure large transfer sizes).

You could imagine other possible designs which would be only pull, end-to-end. The producer would locally write to a local log, and brokers would pull from that with consumers pulling from them. A similar type of "store-and-forward" producer is often proposed. This is intriguing but we felt not very suitable for our target use cases which have thousands of producers. Our experience running persistent data systems at scale led us to feel that involving thousands of disks in the system across many applications would not actually make things more reliable and would be a nightmare to operate. And in practice we have found that we can run a pipeline with strong SLAs at large scale without a need for producer persistence.

Consumer Position

Keeping track of what has been consumed is, surprisingly, one of the key performance points of a messaging system.

Most messaging systems keep metadata about what messages have been consumed on the broker. That is, as a message is handed out to a consumer, the broker either records that fact locally immediately or it may wait for acknowledgement from the consumer. This is a fairly intuitive choice, and indeed for a single machine server it is not clear where else this state could go. Since the data structures used for storage in many messaging systems scale poorly, this is also a pragmatic choice--since the broker knows what is consumed it can immediately delete it, keeping the data size small.

What is perhaps not obvious is that getting the broker and consumer to come into agreement about what has been consumed is not a trivial problem. If the broker records a message as consumed immediately every time it is handed out over the network, then if the consumer fails to process the message (say because it crashes or the request times out or whatever) that message will be lost. To solve this problem, many messaging systems add an acknowledgement feature which means that messages are only marked as sent not consumed when they are sent; the broker waits for a specific acknowledgement from the consumer to record the message as consumed. This strategy fixes the problem of losing messages, but creates new problems. First of all, if the consumer processes the message but fails before it can send an acknowledgement then the message will be consumed twice. The second problem is around performance, now the broker must keep multiple states about every single message (first to lock it so it is not given out a second time, and then to mark it as permanently consumed so that it can be removed). Tricky problems must be dealt with, like what to do with messages that are sent but never acknowledged.

Kafka handles this differently. Our topic is divided into a set of totally ordered partitions, each of which is consumed by exactly one consumer within each subscribing consumer group at any given time. This means that the position of a consumer in each partition is just a single integer, the offset of the next message to consume. This makes the state about what has been consumed very small, just one number for each partition. This state can be periodically checkpointed. This makes the equivalent of message acknowledgements very cheap.

There is a side benefit of this decision. A consumer can deliberately rewind back to an old offset and re-consume data. This violates the common contract of a queue, but turns out to be an essential feature for many consumers. For example, if the consumer code has a bug and is discovered after some messages are consumed, the consumer can re-consume those messages once the bug is fixed.

Offline Data Load

Scalable persistence allows for the possibility of consumers that only periodically consume such as batch data loads that periodically bulk-load data into an offline system such as Hadoop or a relational data warehouse.

In the case of Hadoop we parallelize the data load by splitting the load over individual map tasks, one for each node/topic/partition combination, allowing full parallelism in the loading. Hadoop provides the task management, and tasks which fail can restart without danger of duplicate data—they simply restart from their original position.

Static Membership

Static membership aims to improve the availability of stream applications, consumer groups and other applications built on top of the group rebalance protocol. The rebalance protocol relies on the group coordinator to allocate entity ids to group members. These generated ids are ephemeral and will change when members restart and rejoin. For consumer based apps, this "dynamic membership" can cause a large percentage of tasks re-assigned to different instances during administrative operations such as code deploys, configuration updates and periodic restarts. For large state applications, shuffled tasks need a long time to recover their local states before processing and cause applications to be partially or entirely unavailable. Motivated by this observation, Kafka’s group management protocol allows group members to provide persistent entity ids. Group membership remains unchanged based on those ids, thus no rebalance will be triggered.

If you want to use static membership,

  • Upgrade both broker cluster and client apps to 2.3 or beyond, and also make sure the upgraded brokers are using of 2.3 or beyond as well.inter.broker.protocol.version
  • Set the config to a unique value for each consumer instance under one group.ConsumerConfig#GROUP_INSTANCE_ID_CONFIG
  • For Kafka Streams applications, it is sufficient to set a unique per KafkaStreams instance, independent of the number of used threads for an instance.ConsumerConfig#GROUP_INSTANCE_ID_CONFIG
If your broker is on an older version than 2.3, but you choose to set on the client side, the application will detect the broker version and then throws an UnsupportedException. If you accidentally configure duplicate ids for different instances, a fencing mechanism on broker side will inform your duplicate client to shutdown immediately by triggering a . For more details, see KIP-345ConsumerConfig#GROUP_INSTANCE_ID_CONFIGorg.apache.kafka.common.errors.FencedInstanceIdException

4.6 Message Delivery Semantics

Now that we understand a little about how producers and consumers work, let's discuss the semantic guarantees Kafka provides between producer and consumer. Clearly there are multiple possible message delivery guarantees that could be provided:

  • At most once—Messages may be lost but are never redelivered.
  • At least once—Messages are never lost but may be redelivered.
  • Exactly once—this is what people actually want, each message is delivered once and only once.
It's worth noting that this breaks down into two problems: the durability guarantees for publishing a message and the guarantees when consuming a message.

Many systems claim to provide "exactly once" delivery semantics, but it is important to read the fine print, most of these claims are misleading (i.e. they don't translate to the case where consumers or producers can fail, cases where there are multiple consumer processes, or cases where data written to disk can be lost).

Kafka's semantics are straight-forward. When publishing a message we have a notion of the message being "committed" to the log. Once a published message is committed it will not be lost as long as one broker that replicates the partition to which this message was written remains "alive". The definition of committed message, alive partition as well as a description of which types of failures we attempt to handle will be described in more detail in the next section. For now let's assume a perfect, lossless broker and try to understand the guarantees to the producer and consumer. If a producer attempts to publish a message and experiences a network error it cannot be sure if this error happened before or after the message was committed. This is similar to the semantics of inserting into a database table with an autogenerated key.

Prior to 0.11.0.0, if a producer failed to receive a response indicating that a message was committed, it had little choice but to resend the message. This provides at-least-once delivery semantics since the message may be written to the log again during resending if the original request had in fact succeeded. Since 0.11.0.0, the Kafka producer also supports an idempotent delivery option which guarantees that resending will not result in duplicate entries in the log. To achieve this, the broker assigns each producer an ID and deduplicates messages using a sequence number that is sent by the producer along with every message. Also beginning with 0.11.0.0, the producer supports the ability to send messages to multiple topic partitions using transaction-like semantics: i.e. either all messages are successfully written or none of them are. The main use case for this is exactly-once processing between Kafka topics (described below).

Not all use cases require such strong guarantees. For uses which are latency sensitive we allow the producer to specify the durability level it desires. If the producer specifies that it wants to wait on the message being committed this can take on the order of 10 ms. However the producer can also specify that it wants to perform the send completely asynchronously or that it wants to wait only until the leader (but not necessarily the followers) have the message.

Now let's describe the semantics from the point-of-view of the consumer. All replicas have the exact same log with the same offsets. The consumer controls its position in this log. If the consumer never crashed it could just store this position in memory, but if the consumer fails and we want this topic partition to be taken over by another process the new process will need to choose an appropriate position from which to start processing. Let's say the consumer reads some messages -- it has several options for processing the messages and updating its position.

  1. It can read the messages, then save its position in the log, and finally process the messages. In this case there is a possibility that the consumer process crashes after saving its position but before saving the output of its message processing. In this case the process that took over processing would start at the saved position even though a few messages prior to that position had not been processed. This corresponds to "at-most-once" semantics as in the case of a consumer failure messages may not be processed.
  2. It can read the messages, process the messages, and finally save its position. In this case there is a possibility that the consumer process crashes after processing messages but before saving its position. In this case when the new process takes over the first few messages it receives will already have been processed. This corresponds to the "at-least-once" semantics in the case of consumer failure. In many cases messages have a primary key and so the updates are idempotent (receiving the same message twice just overwrites a record with another copy of itself).

So what about exactly once semantics (i.e. the thing you actually want)? When consuming from a Kafka topic and producing to another topic (as in a Kafka Streams application), we can leverage the new transactional producer capabilities in 0.11.0.0 that were mentioned above. The consumer's position is stored as a message in a topic, so we can write the offset to Kafka in the same transaction as the output topics receiving the processed data. If the transaction is aborted, the consumer's position will revert to its old value and the produced data on the output topics will not be visible to other consumers, depending on their "isolation level." In the default "read_uncommitted" isolation level, all messages are visible to consumers even if they were part of an aborted transaction, but in "read_committed," the consumer will only return messages from transactions which were committed (and any messages which were not part of a transaction).

When writing to an external system, the limitation is in the need to coordinate the consumer's position with what is actually stored as output. The classic way of achieving this would be to introduce a two-phase commit between the storage of the consumer position and the storage of the consumers output. But this can be handled more simply and generally by letting the consumer store its offset in the same place as its output. This is better because many of the output systems a consumer might want to write to will not support a two-phase commit. As an example of this, consider a Kafka Connect connector which populates data in HDFS along with the offsets of the data it reads so that it is guaranteed that either data and offsets are both updated or neither is. We follow similar patterns for many other data systems which require these stronger semantics and for which the messages do not have a primary key to allow for deduplication.

So effectively Kafka supports exactly-once delivery in Kafka Streams, and the transactional producer/consumer can be used generally to provide exactly-once delivery when transferring and processing data between Kafka topics. Exactly-once delivery for other destination systems generally requires cooperation with such systems, but Kafka provides the offset which makes implementing this feasible (see also Kafka Connect). Otherwise, Kafka guarantees at-least-once delivery by default, and allows the user to implement at-most-once delivery by disabling retries on the producer and committing offsets in the consumer prior to processing a batch of messages.

4.7 Replication

Kafka replicates the log for each topic's partitions across a configurable number of servers (you can set this replication factor on a topic-by-topic basis). This allows automatic failover to these replicas when a server in the cluster fails so messages remain available in the presence of failures.

Other messaging systems provide some replication-related features, but, in our (totally biased) opinion, this appears to be a tacked-on thing, not heavily used, and with large downsides: replicas are inactive, throughput is heavily impacted, it requires fiddly manual configuration, etc. Kafka is meant to be used with replication by default—in fact we implement un-replicated topics as replicated topics where the replication factor is one.

The unit of replication is the topic partition. Under non-failure conditions, each partition in Kafka has a single leader and zero or more followers. The total number of replicas including the leader constitute the replication factor. All writes go to the leader of the partition, and reads can go to the leader or the followers of the partition. Typically, there are many more partitions than brokers and the leaders are evenly distributed among brokers. The logs on the followers are identical to the leader's log—all have the same offsets and messages in the same order (though, of course, at any given time the leader may have a few as-yet unreplicated messages at the end of its log).

Followers consume messages from the leader just as a normal Kafka consumer would and apply them to their own log. Having the followers pull from the leader has the nice property of allowing the follower to naturally batch together log entries they are applying to their log.

As with most distributed systems, automatically handling failures requires a precise definition of what it means for a node to be "alive." In Kafka, a special node known as the "controller" is responsible for managing the registration of brokers in the cluster. Broker liveness has two conditions:

  1. Brokers must maintain an active session with the controller in order to receive regular metadata updates.
  2. Brokers acting as followers must replicate the writes from the leader and not fall "too far" behind.

What is meant by an "active session" depends on the cluster configuration. For KRaft clusters, an active session is maintained by sending periodic heartbeats to the controller. If the controller fails to receive a heartbeat before the timeout configured by expires, then the node is considered offline. broker.session.timeout.ms

For clusters using Zookeeper, liveness is determined indirectly through the existence of an ephemeral node which is created by the broker on initialization of its Zookeeper session. If the broker loses its session after failing to send heartbeats to Zookeeper before expiration of , then the node gets deleted. The controller would then notice the node deletion through a Zookeeper watch and mark the broker offline. zookeeper.session.timeout.ms

We refer to nodes satisfying these two conditions as being "in sync" to avoid the vagueness of "alive" or "failed". The leader keeps track of the set of "in sync" replicas, which is known as the ISR. If either of these conditions fail to be satisified, then the broker will be removed from the ISR. For example, if a follower dies, then the controller will notice the failure through the loss of its session, and will remove the broker from the ISR. On the other hand, if the follower lags too far behind the leader but still has an active session, then the leader can also remove it from the ISR. The determination of lagging replicas is controlled through the configuration. Replicas that cannot catch up to the end of the log on the leader within the max time set by this configuration are removed from the ISR. replica.lag.time.max.ms

In distributed systems terminology we only attempt to handle a "fail/recover" model of failures where nodes suddenly cease working and then later recover (perhaps without knowing that they have died). Kafka does not handle so-called "Byzantine" failures in which nodes produce arbitrary or malicious responses (perhaps due to bugs or foul play).

We can now more precisely define that a message is considered committed when all replicas in the ISR for that partition have applied it to their log. Only committed messages are ever given out to the consumer. This means that the consumer need not worry about potentially seeing a message that could be lost if the leader fails. Producers, on the other hand, have the option of either waiting for the message to be committed or not, depending on their preference for tradeoff between latency and durability. This preference is controlled by the acks setting that the producer uses. Note that topics have a setting for the "minimum number" of in-sync replicas that is checked when the producer requests acknowledgment that a message has been written to the full set of in-sync replicas. If a less stringent acknowledgement is requested by the producer, then the message can be committed, and consumed, even if the number of in-sync replicas is lower than the minimum (e.g. it can be as low as just the leader).

The guarantee that Kafka offers is that a committed message will not be lost, as long as there is at least one in sync replica alive, at all times.

Kafka will remain available in the presence of node failures after a short fail-over period, but may not remain available in the presence of network partitions.

Replicated Logs: Quorums, ISRs, and State Machines (Oh my!)

At its heart a Kafka partition is a replicated log. The replicated log is one of the most basic primitives in distributed data systems, and there are many approaches for implementing one. A replicated log can be used by other systems as a primitive for implementing other distributed systems in the state-machine style.

A replicated log models the process of coming into consensus on the order of a series of values (generally numbering the log entries 0, 1, 2, ...). There are many ways to implement this, but the simplest and fastest is with a leader who chooses the ordering of values provided to it. As long as the leader remains alive, all followers need to only copy the values and ordering the leader chooses.

Of course if leaders didn't fail we wouldn't need followers! When the leader does die we need to choose a new leader from among the followers. But followers themselves may fall behind or crash so we must ensure we choose an up-to-date follower. The fundamental guarantee a log replication algorithm must provide is that if we tell the client a message is committed, and the leader fails, the new leader we elect must also have that message. This yields a tradeoff: if the leader waits for more followers to acknowledge a message before declaring it committed then there will be more potentially electable leaders.

If you choose the number of acknowledgements required and the number of logs that must be compared to elect a leader such that there is guaranteed to be an overlap, then this is called a Quorum.

A common approach to this tradeoff is to use a majority vote for both the commit decision and the leader election. This is not what Kafka does, but let's explore it anyway to understand the tradeoffs. Let's say we have 2f+1 replicas. If f+1 replicas must receive a message prior to a commit being declared by the leader, and if we elect a new leader by electing the follower with the most complete log from at least f+1 replicas, then, with no more than f failures, the leader is guaranteed to have all committed messages. This is because among any f+1 replicas, there must be at least one replica that contains all committed messages. That replica's log will be the most complete and therefore will be selected as the new leader. There are many remaining details that each algorithm must handle (such as precisely defined what makes a log more complete, ensuring log consistency during leader failure or changing the set of servers in the replica set) but we will ignore these for now.

This majority vote approach has a very nice property: the latency is dependent on only the fastest servers. That is, if the replication factor is three, the latency is determined by the faster follower not the slower one.

There are a rich variety of algorithms in this family including ZooKeeper's Zab, Raft, and Viewstamped Replication. The most similar academic publication we are aware of to Kafka's actual implementation is PacificA from Microsoft.

The downside of majority vote is that it doesn't take many failures to leave you with no electable leaders. To tolerate one failure requires three copies of the data, and to tolerate two failures requires five copies of the data. In our experience having only enough redundancy to tolerate a single failure is not enough for a practical system, but doing every write five times, with 5x the disk space requirements and 1/5th the throughput, is not very practical for large volume data problems. This is likely why quorum algorithms more commonly appear for shared cluster configuration such as ZooKeeper but are less common for primary data storage. For example in HDFS the namenode's high-availability feature is built on a majority-vote-based journal, but this more expensive approach is not used for the data itself.

Kafka takes a slightly different approach to choosing its quorum set. Instead of majority vote, Kafka dynamically maintains a set of in-sync replicas (ISR) that are caught-up to the leader. Only members of this set are eligible for election as leader. A write to a Kafka partition is not considered committed until all in-sync replicas have received the write. This ISR set is persisted in the cluster metadata whenever it changes. Because of this, any replica in the ISR is eligible to be elected leader. This is an important factor for Kafka's usage model where there are many partitions and ensuring leadership balance is important. With this ISR model and f+1 replicas, a Kafka topic can tolerate f failures without losing committed messages.

For most use cases we hope to handle, we think this tradeoff is a reasonable one. In practice, to tolerate f failures, both the majority vote and the ISR approach will wait for the same number of replicas to acknowledge before committing a message (e.g. to survive one failure a majority quorum needs three replicas and one acknowledgement and the ISR approach requires two replicas and one acknowledgement). The ability to commit without the slowest servers is an advantage of the majority vote approach. However, we think it is ameliorated by allowing the client to choose whether they block on the message commit or not, and the additional throughput and disk space due to the lower required replication factor is worth it.

Another important design distinction is that Kafka does not require that crashed nodes recover with all their data intact. It is not uncommon for replication algorithms in this space to depend on the existence of "stable storage" that cannot be lost in any failure-recovery scenario without potential consistency violations. There are two primary problems with this assumption. First, disk errors are the most common problem we observe in real operation of persistent data systems and they often do not leave data intact. Secondly, even if this were not a problem, we do not want to require the use of fsync on every write for our consistency guarantees as this can reduce performance by two to three orders of magnitude. Our protocol for allowing a replica to rejoin the ISR ensures that before rejoining, it must fully re-sync again even if it lost unflushed data in its crash.

Unclean leader election: What if they all die?

Note that Kafka's guarantee with respect to data loss is predicated on at least one replica remaining in sync. If all the nodes replicating a partition die, this guarantee no longer holds.

However a practical system needs to do something reasonable when all the replicas die. If you are unlucky enough to have this occur, it is important to consider what will happen. There are two behaviors that could be implemented:

  1. Wait for a replica in the ISR to come back to life and choose this replica as the leader (hopefully it still has all its data).
  2. Choose the first replica (not necessarily in the ISR) that comes back to life as the leader.

This is a simple tradeoff between availability and consistency. If we wait for replicas in the ISR, then we will remain unavailable as long as those replicas are down. If such replicas were destroyed or their data was lost, then we are permanently down. If, on the other hand, a non-in-sync replica comes back to life and we allow it to become leader, then its log becomes the source of truth even though it is not guaranteed to have every committed message. By default from version 0.11.0.0, Kafka chooses the first strategy and favor waiting for a consistent replica. This behavior can be changed using configuration property unclean.leader.election.enable, to support use cases where uptime is preferable to consistency.

This dilemma is not specific to Kafka. It exists in any quorum-based scheme. For example in a majority voting scheme, if a majority of servers suffer a permanent failure, then you must either choose to lose 100% of your data or violate consistency by taking what remains on an existing server as your new source of truth.

Availability and Durability Guarantees

When writing to Kafka, producers can choose whether they wait for the message to be acknowledged by 0,1 or all (-1) replicas. Note that "acknowledgement by all replicas" does not guarantee that the full set of assigned replicas have received the message. By default, when acks=all, acknowledgement happens as soon as all the current in-sync replicas have received the message. For example, if a topic is configured with only two replicas and one fails (i.e., only one in sync replica remains), then writes that specify acks=all will succeed. However, these writes could be lost if the remaining replica also fails. Although this ensures maximum availability of the partition, this behavior may be undesirable to some users who prefer durability over availability. Therefore, we provide two topic-level configurations that can be used to prefer message durability over availability:
  1. Disable unclean leader election - if all replicas become unavailable, then the partition will remain unavailable until the most recent leader becomes available again. This effectively prefers unavailability over the risk of message loss. See the previous section on Unclean Leader Election for clarification.
  2. Specify a minimum ISR size - the partition will only accept writes if the size of the ISR is above a certain minimum, in order to prevent the loss of messages that were written to just a single replica, which subsequently becomes unavailable. This setting only takes effect if the producer uses acks=all and guarantees that the message will be acknowledged by at least this many in-sync replicas. This setting offers a trade-off between consistency and availability. A higher setting for minimum ISR size guarantees better consistency since the message is guaranteed to be written to more replicas which reduces the probability that it will be lost. However, it reduces availability since the partition will be unavailable for writes if the number of in-sync replicas drops below the minimum threshold.

Replica Management

The above discussion on replicated logs really covers only a single log, i.e. one topic partition. However a Kafka cluster will manage hundreds or thousands of these partitions. We attempt to balance partitions within a cluster in a round-robin fashion to avoid clustering all partitions for high-volume topics on a small number of nodes. Likewise we try to balance leadership so that each node is the leader for a proportional share of its partitions.

It is also important to optimize the leadership election process as that is the critical window of unavailability. A naive implementation of leader election would end up running an election per partition for all partitions a node hosted when that node failed. As discussed above in the section on replication, Kafka clusters have a special role known as the "controller" which is responsible for managing the registration of brokers. If the controller detects the failure of a broker, it is responsible for electing one of the remaining members of the ISR to serve as the new leader. The result is that we are able to batch together many of the required leadership change notifications which makes the election process far cheaper and faster for a large number of partitions. If the controller itself fails, then another controller will be elected.

4.8 Log Compaction

Log compaction ensures that Kafka will always retain at least the last known value for each message key within the log of data for a single topic partition. It addresses use cases and scenarios such as restoring state after application crashes or system failure, or reloading caches after application restarts during operational maintenance. Let's dive into these use cases in more detail and then describe how compaction works.

So far we have described only the simpler approach to data retention where old log data is discarded after a fixed period of time or when the log reaches some predetermined size. This works well for temporal event data such as logging where each record stands alone. However an important class of data streams are the log of changes to keyed, mutable data (for example, the changes to a database table).

Let's discuss a concrete example of such a stream. Say we have a topic containing user email addresses; every time a user updates their email address we send a message to this topic using their user id as the primary key. Now say we send the following messages over some time period for a user with id 123, each message corresponding to a change in email address (messages for other ids are omitted):

123 => bill@microsoft.com
        .
        .
        .
123 => bill@gatesfoundation.org
        .
        .
        .
123 => bill@gmail.com
Log compaction gives us a more granular retention mechanism so that we are guaranteed to retain at least the last update for each primary key (e.g. ). By doing this we guarantee that the log contains a full snapshot of the final value for every key not just keys that changed recently. This means downstream consumers can restore their own state off this topic without us having to retain a complete log of all changes. bill@gmail.com

Let's start by looking at a few use cases where this is useful, then we'll see how it can be used.

  1. Database change subscription. It is often necessary to have a data set in multiple data systems, and often one of these systems is a database of some kind (either a RDBMS or perhaps a new-fangled key-value store). For example you might have a database, a cache, a search cluster, and a Hadoop cluster. Each change to the database will need to be reflected in the cache, the search cluster, and eventually in Hadoop. In the case that one is only handling the real-time updates you only need recent log. But if you want to be able to reload the cache or restore a failed search node you may need a complete data set.
  2. Event sourcing. This is a style of application design which co-locates query processing with application design and uses a log of changes as the primary store for the application.
  3. Journaling for high-availability. A process that does local computation can be made fault-tolerant by logging out changes that it makes to its local state so another process can reload these changes and carry on if it should fail. A concrete example of this is handling counts, aggregations, and other "group by"-like processing in a stream query system. Samza, a real-time stream-processing framework, uses this feature for exactly this purpose.
In each of these cases one needs primarily to handle the real-time feed of changes, but occasionally, when a machine crashes or data needs to be re-loaded or re-processed, one needs to do a full load. Log compaction allows feeding both of these use cases off the same backing topic. This style of usage of a log is described in more detail in this blog post.

The general idea is quite simple. If we had infinite log retention, and we logged each change in the above cases, then we would have captured the state of the system at each time from when it first began. Using this complete log, we could restore to any point in time by replaying the first N records in the log. This hypothetical complete log is not very practical for systems that update a single record many times as the log will grow without bound even for a stable dataset. The simple log retention mechanism which throws away old updates will bound space but the log is no longer a way to restore the current state—now restoring from the beginning of the log no longer recreates the current state as old updates may not be captured at all.

Log compaction is a mechanism to give finer-grained per-record retention, rather than the coarser-grained time-based retention. The idea is to selectively remove records where we have a more recent update with the same primary key. This way the log is guaranteed to have at least the last state for each key.

This retention policy can be set per-topic, so a single cluster can have some topics where retention is enforced by size or time and other topics where retention is enforced by compaction.

This functionality is inspired by one of LinkedIn's oldest and most successful pieces of infrastructure—a database changelog caching service called Databus. Unlike most log-structured storage systems Kafka is built for subscription and organizes data for fast linear reads and writes. Unlike Databus, Kafka acts as a source-of-truth store so it is useful even in situations where the upstream data source would not otherwise be replayable.

Log Compaction Basics

Here is a high-level picture that shows the logical structure of a Kafka log with the offset for each message.

The head of the log is identical to a traditional Kafka log. It has dense, sequential offsets and retains all messages. Log compaction adds an option for handling the tail of the log. The picture above shows a log with a compacted tail. Note that the messages in the tail of the log retain the original offset assigned when they were first written—that never changes. Note also that all offsets remain valid positions in the log, even if the message with that offset has been compacted away; in this case this position is indistinguishable from the next highest offset that does appear in the log. For example, in the picture above the offsets 36, 37, and 38 are all equivalent positions and a read beginning at any of these offsets would return a message set beginning with 38.

Compaction also allows for deletes. A message with a key and a null payload will be treated as a delete from the log. Such a record is sometimes referred to as a tombstone. This delete marker will cause any prior message with that key to be removed (as would any new message with that key), but delete markers are special in that they will themselves be cleaned out of the log after a period of time to free up space. The point in time at which deletes are no longer retained is marked as the "delete retention point" in the above diagram.

The compaction is done in the background by periodically recopying log segments. Cleaning does not block reads and can be throttled to use no more than a configurable amount of I/O throughput to avoid impacting producers and consumers. The actual process of compacting a log segment looks something like this:

What guarantees does log compaction provide?

Log compaction guarantees the following:
  1. Any consumer that stays caught-up to within the head of the log will see every message that is written; these messages will have sequential offsets. The topic's can be used to guarantee the minimum length of time must pass after a message is written before it could be compacted. I.e. it provides a lower bound on how long each message will remain in the (uncompacted) head. The topic's can be used to guarantee the maximum delay between the time a message is written and the time the message becomes eligible for compaction. min.compaction.lag.msmax.compaction.lag.ms
  2. Ordering of messages is always maintained. Compaction will never re-order messages, just remove some.
  3. The offset for a message never changes. It is the permanent identifier for a position in the log.
  4. Any consumer progressing from the start of the log will see at least the final state of all records in the order they were written. Additionally, all delete markers for deleted records will be seen, provided the consumer reaches the head of the log in a time period less than the topic's setting (the default is 24 hours). In other words: since the removal of delete markers happens concurrently with reads, it is possible for a consumer to miss delete markers if it lags by more than . delete.retention.msdelete.retention.ms

Log Compaction Details

Log compaction is handled by the log cleaner, a pool of background threads that recopy log segment files, removing records whose key appears in the head of the log. Each compactor thread works as follows:
  1. It chooses the log that has the highest ratio of log head to log tail
  2. It creates a succinct summary of the last offset for each key in the head of the log
  3. It recopies the log from beginning to end removing keys which have a later occurrence in the log. New, clean segments are swapped into the log immediately so the additional disk space required is just one additional log segment (not a fully copy of the log).
  4. The summary of the log head is essentially just a space-compact hash table. It uses exactly 24 bytes per entry. As a result with 8GB of cleaner buffer one cleaner iteration can clean around 366GB of log head (assuming 1k messages).

Configuring The Log Cleaner

The log cleaner is enabled by default. This will start the pool of cleaner threads. To enable log cleaning on a particular topic, add the log-specific property The property is a broker configuration setting defined in the broker's file; it affects all of the topics in the cluster that do not have a configuration override in place as documented here. The log cleaner can be configured to retain a minimum amount of the uncompacted "head" of the log. This is enabled by setting the compaction time lag. This can be used to prevent messages newer than a minimum message age from being subject to compaction. If not set, all log segments are eligible for compaction except for the last segment, i.e. the one currently being written to. The active segment will not be compacted even if all of its messages are older than the minimum compaction time lag. The log cleaner can be configured to ensure a maximum delay after which the uncompacted "head" of the log becomes eligible for log compaction. This can be used to prevent log with low produce rate from remaining ineligible for compaction for an unbounded duration. If not set, logs that do not exceed min.cleanable.dirty.ratio are not compacted. Note that this compaction deadline is not a hard guarantee since it is still subjected to the availability of log cleaner threads and the actual compaction time. You will want to monitor the uncleanable-partitions-count, max-clean-time-secs and max-compaction-delay-secs metrics.
log.cleanup.policy=compact
log.cleanup.policyserver.properties
log.cleaner.min.compaction.lag.ms
log.cleaner.max.compaction.lag.ms

Further cleaner configurations are described here.

4.9 Quotas

Kafka cluster has the ability to enforce quotas on requests to control the broker resources used by clients. Two types of client quotas can be enforced by Kafka brokers for each group of clients sharing a quota:

  1. Network bandwidth quotas define byte-rate thresholds (since 0.9)
  2. Request rate quotas define CPU utilization thresholds as a percentage of network and I/O threads (since 0.11)

Why are quotas necessary?

It is possible for producers and consumers to produce/consume very high volumes of data or generate requests at a very high rate and thus monopolize broker resources, cause network saturation and generally DOS other clients and the brokers themselves. Having quotas protects against these issues and is all the more important in large multi-tenant clusters where a small set of badly behaved clients can degrade user experience for the well behaved ones. In fact, when running Kafka as a service this even makes it possible to enforce API limits according to an agreed upon contract.

Client groups

The identity of Kafka clients is the user principal which represents an authenticated user in a secure cluster. In a cluster that supports unauthenticated clients, user principal is a grouping of unauthenticated users chosen by the broker using a configurable . Client-id is a logical grouping of clients with a meaningful name chosen by the client application. The tuple (user, client-id) defines a secure logical group of clients that share both user principal and client-id. PrincipalBuilder

Quotas can be applied to (user, client-id), user or client-id groups. For a given connection, the most specific quota matching the connection is applied. All connections of a quota group share the quota configured for the group. For example, if (user="test-user", client-id="test-client") has a produce quota of 10MB/sec, this is shared across all producer instances of user "test-user" with the client-id "test-client".

Quota Configuration

Quota configuration may be defined for (user, client-id), user and client-id groups. It is possible to override the default quota at any of the quota levels that needs a higher (or even lower) quota. The mechanism is similar to the per-topic log config overrides. User and (user, client-id) quota overrides are written to ZooKeeper under /config/users and client-id quota overrides are written under /config/clients. These overrides are read by all brokers and are effective immediately. This lets us change quotas without having to do a rolling restart of the entire cluster. See here for details. Default quotas for each group may also be updated dynamically using the same mechanism.

The order of precedence for quota configuration is:

  1. /config/users/<user>/clients/<client-id>
  2. /config/users/<user>/clients/<default>
  3. /config/users/<user>
  4. /config/users/<default>/clients/<client-id>
  5. /config/users/<default>/clients/<default>
  6. /config/users/<default>
  7. /config/clients/<client-id>
  8. /config/clients/<default>

Network Bandwidth Quotas

Network bandwidth quotas are defined as the byte rate threshold for each group of clients sharing a quota. By default, each unique client group receives a fixed quota in bytes/sec as configured by the cluster. This quota is defined on a per-broker basis. Each group of clients can publish/fetch a maximum of X bytes/sec per broker before clients are throttled.

Request Rate Quotas

Request rate quotas are defined as the percentage of time a client can utilize on request handler I/O threads and network threads of each broker within a quota window. A quota of n% represents n% of one thread, so the quota is out of a total capacity of ((num.io.threads + num.network.threads) * 100)%. Each group of clients may use a total percentage of upto n% across all I/O and network threads in a quota window before being throttled. Since the number of threads allocated for I/O and network threads are typically based on the number of cores available on the broker host, request rate quotas represent the total percentage of CPU that may be used by each group of clients sharing the quota.

Enforcement

By default, each unique client group receives a fixed quota as configured by the cluster. This quota is defined on a per-broker basis. Each client can utilize this quota per broker before it gets throttled. We decided that defining these quotas per broker is much better than having a fixed cluster wide bandwidth per client because that would require a mechanism to share client quota usage among all the brokers. This can be harder to get right than the quota implementation itself!

How does a broker react when it detects a quota violation? In our solution, the broker first computes the amount of delay needed to bring the violating client under its quota and returns a response with the delay immediately. In case of a fetch request, the response will not contain any data. Then, the broker mutes the channel to the client, not to process requests from the client anymore, until the delay is over. Upon receiving a response with a non-zero delay duration, the Kafka client will also refrain from sending further requests to the broker during the delay. Therefore, requests from a throttled client are effectively blocked from both sides. Even with older client implementations that do not respect the delay response from the broker, the back pressure applied by the broker via muting its socket channel can still handle the throttling of badly behaving clients. Those clients who sent further requests to the throttled channel will receive responses only after the delay is over.

Byte-rate and thread utilization are measured over multiple small windows (e.g. 30 windows of 1 second each) in order to detect and correct quota violations quickly. Typically, having large measurement windows (for e.g. 10 windows of 30 seconds each) leads to large bursts of traffic followed by long delays which is not great in terms of user experience.

5. 实施

5.1 Network Layer

The network layer is a fairly straight-forward NIO server, and will not be described in great detail. The sendfile implementation is done by giving the interface a method. This allows the file-backed message set to use the more efficient implementation instead of an in-process buffered write. The threading model is a single acceptor thread and N processor threads which handle a fixed number of connections each. This design has been pretty thoroughly tested elsewhere and found to be simple to implement and fast. The protocol is kept quite simple to allow for future implementation of clients in other languages. TransferableRecordswriteTotransferTo

5.2 Messages

Messages consist of a variable-length header, a variable-length opaque key byte array and a variable-length opaque value byte array. The format of the header is described in the following section. Leaving the key and value opaque is the right decision: there is a great deal of progress being made on serialization libraries right now, and any particular choice is unlikely to be right for all uses. Needless to say a particular application using Kafka would likely mandate a particular serialization type as part of its usage. The interface is simply an iterator over messages with specialized methods for bulk reading and writing to an NIO .RecordBatchChannel

5.3 Message Format

Messages (aka Records) are always written in batches. The technical term for a batch of messages is a record batch, and a record batch contains one or more records. In the degenerate case, we could have a record batch containing a single record. Record batches and records have their own headers. The format of each is described below.

5.3.1 Record Batch

The following is the on-disk format of a RecordBatch.

baseOffset: int64
batchLength: int32
partitionLeaderEpoch: int32
magic: int8 (current magic value is 2)
crc: int32
attributes: int16
    bit 0~2:
        0: no compression
        1: gzip
        2: snappy
        3: lz4
        4: zstd
    bit 3: timestampType
    bit 4: isTransactional (0 means not transactional)
    bit 5: isControlBatch (0 means not a control batch)
    bit 6: hasDeleteHorizonMs (0 means baseTimestamp is not set as the delete horizon for compaction)
    bit 7~15: unused
lastOffsetDelta: int32
baseTimestamp: int64
maxTimestamp: int64
producerId: int64
producerEpoch: int16
baseSequence: int32
records: [Record]

Note that when compression is enabled, the compressed record data is serialized directly following the count of the number of records.

The CRC covers the data from the attributes to the end of the batch (i.e. all the bytes that follow the CRC). It is located after the magic byte, which means that clients must parse the magic byte before deciding how to interpret the bytes between the batch length and the magic byte. The partition leader epoch field is not included in the CRC computation to avoid the need to recompute the CRC when this field is assigned for every batch that is received by the broker. The CRC-32C (Castagnoli) polynomial is used for the computation.

On compaction: unlike the older message formats, magic v2 and above preserves the first and last offset/sequence numbers from the original batch when the log is cleaned. This is required in order to be able to restore the producer's state when the log is reloaded. If we did not retain the last sequence number, for example, then after a partition leader failure, the producer might see an OutOfSequence error. The base sequence number must be preserved for duplicate checking (the broker checks incoming Produce requests for duplicates by verifying that the first and last sequence numbers of the incoming batch match the last from that producer). As a result, it is possible to have empty batches in the log when all the records in the batch are cleaned but batch is still retained in order to preserve a producer's last sequence number. One oddity here is that the baseTimestamp field is not preserved during compaction, so it will change if the first record in the batch is compacted away.

Compaction may also modify the baseTimestamp if the record batch contains records with a null payload or aborted transaction markers. The baseTimestamp will be set to the timestamp of when those records should be deleted with the delete horizon attribute bit also set.

5.3.1.1 Control Batches

A control batch contains a single record called the control record. Control records should not be passed on to applications. Instead, they are used by consumers to filter out aborted transactional messages.

The key of a control record conforms to the following schema:

version: int16 (current version is 0)
type: int16 (0 indicates an abort marker, 1 indicates a commit)

The schema for the value of a control record is dependent on the type. The value is opaque to clients.

5.3.2 Record

Record level headers were introduced in Kafka 0.11.0. The on-disk format of a record with Headers is delineated below.

length: varint
attributes: int8
    bit 0~7: unused
timestampDelta: varlong
offsetDelta: varint
keyLength: varint
key: byte[]
valueLen: varint
value: byte[]
Headers => [Header]
5.3.2.1 Record Header
headerKeyLength: varint
headerKey: String
headerValueLength: varint
Value: byte[]

We use the same varint encoding as Protobuf. More information on the latter can be found here. The count of headers in a record is also encoded as a varint.

5.3.3 Old Message Format

Prior to Kafka 0.11, messages were transferred and stored in message sets. In a message set, each message has its own metadata. Note that although message sets are represented as an array, they are not preceded by an int32 array size like other array elements in the protocol.

Message Set:
MessageSet (Version: 0) => [offset message_size message]
offset => INT64
message_size => INT32
message => crc magic_byte attributes key value
    crc => INT32
    magic_byte => INT8
    attributes => INT8
        bit 0~2:
            0: no compression
            1: gzip
            2: snappy
        bit 3~7: unused
    key => BYTES
    value => BYTES
MessageSet (Version: 1) => [offset message_size message]
offset => INT64
message_size => INT32
message => crc magic_byte attributes timestamp key value
    crc => INT32
    magic_byte => INT8
    attributes => INT8
        bit 0~2:
            0: no compression
            1: gzip
            2: snappy
            3: lz4
        bit 3: timestampType
            0: create time
            1: log append time
        bit 4~7: unused
    timestamp => INT64
    key => BYTES
    value => BYTES

In versions prior to Kafka 0.10, the only supported message format version (which is indicated in the magic value) was 0. Message format version 1 was introduced with timestamp support in version 0.10.

  • Similarly to version 2 above, the lowest bits of attributes represent the compression type.
  • In version 1, the producer should always set the timestamp type bit to 0. If the topic is configured to use log append time, (through either broker level config log.message.timestamp.type = LogAppendTime or topic level config message.timestamp.type = LogAppendTime), the broker will overwrite the timestamp type and the timestamp in the message set.
  • The highest bits of attributes must be set to 0.

In message format versions 0 and 1 Kafka supports recursive messages to enable compression. In this case the message's attributes must be set to indicate one of the compression types and the value field will contain a message set compressed with that type. We often refer to the nested messages as "inner messages" and the wrapping message as the "outer message." Note that the key should be null for the outer message and its offset will be the offset of the last inner message.

When receiving recursive version 0 messages, the broker decompresses them and each inner message is assigned an offset individually. In version 1, to avoid server side re-compression, only the wrapper message will be assigned an offset. The inner messages will have relative offsets. The absolute offset can be computed using the offset from the outer message, which corresponds to the offset assigned to the last inner message.

The crc field contains the CRC32 (and not CRC-32C) of the subsequent message bytes (i.e. from magic byte to the value).

5.4 Log

A log for a topic named "my-topic" with two partitions consists of two directories (namely and ) populated with data files containing the messages for that topic. The format of the log files is a sequence of "log entries"; each log entry is a 4 byte integer N storing the message length which is followed by the N message bytes. Each message is uniquely identified by a 64-bit integer offset giving the byte position of the start of this message in the stream of all messages ever sent to that topic on that partition. The on-disk format of each message is given below. Each log file is named with the offset of the first message it contains. So the first file created will be 00000000000000000000.log, and each additional file will have an integer name roughly S bytes from the previous file where S is the max log file size given in the configuration. my-topic-0my-topic-1

The exact binary format for records is versioned and maintained as a standard interface so record batches can be transferred between producer, broker, and client without recopying or conversion when desirable. The previous section included details about the on-disk format of records.

The use of the message offset as the message id is unusual. Our original idea was to use a GUID generated by the producer, and maintain a mapping from GUID to offset on each broker. But since a consumer must maintain an ID for each server, the global uniqueness of the GUID provides no value. Furthermore, the complexity of maintaining the mapping from a random id to an offset requires a heavy weight index structure which must be synchronized with disk, essentially requiring a full persistent random-access data structure. Thus to simplify the lookup structure we decided to use a simple per-partition atomic counter which could be coupled with the partition id and node id to uniquely identify a message; this makes the lookup structure simpler, though multiple seeks per consumer request are still likely. However once we settled on a counter, the jump to directly using the offset seemed natural—both after all are monotonically increasing integers unique to a partition. Since the offset is hidden from the consumer API this decision is ultimately an implementation detail and we went with the more efficient approach.

Writes

The log allows serial appends which always go to the last file. This file is rolled over to a fresh file when it reaches a configurable size (say 1GB). The log takes two configuration parameters: M, which gives the number of messages to write before forcing the OS to flush the file to disk, and S, which gives a number of seconds after which a flush is forced. This gives a durability guarantee of losing at most M messages or S seconds of data in the event of a system crash.

Reads

Reads are done by giving the 64-bit logical offset of a message and an S-byte max chunk size. This will return an iterator over the messages contained in the S-byte buffer. S is intended to be larger than any single message, but in the event of an abnormally large message, the read can be retried multiple times, each time doubling the buffer size, until the message is read successfully. A maximum message and buffer size can be specified to make the server reject messages larger than some size, and to give a bound to the client on the maximum it needs to ever read to get a complete message. It is likely that the read buffer ends with a partial message, this is easily detected by the size delimiting.

The actual process of reading from an offset requires first locating the log segment file in which the data is stored, calculating the file-specific offset from the global offset value, and then reading from that file offset. The search is done as a simple binary search variation against an in-memory range maintained for each file.

The log provides the capability of getting the most recently written message to allow clients to start subscribing as of "right now". This is also useful in the case the consumer fails to consume its data within its SLA-specified number of days. In this case when the client attempts to consume a non-existent offset it is given an OutOfRangeException and can either reset itself or fail as appropriate to the use case.

The following is the format of the results sent to the consumer.

MessageSetSend (fetch result)

total length     : 4 bytes
error code       : 2 bytes
message 1        : x bytes
...
message n        : x bytes
MultiMessageSetSend (multiFetch result)

total length       : 4 bytes
error code         : 2 bytes
messageSetSend 1
...
messageSetSend n

Deletes

Data is deleted one log segment at a time. The log manager applies two metrics to identify segments which are eligible for deletion: time and size. For time-based policies, the record timestamps are considered, with the largest timestamp in a segment file (order of records is not relevant) defining the retention time for the entire segment. Size-based retention is disabled by default. When enabled the log manager keeps deleting the oldest segment file until the overall size of the partition is within the configured limit again. If both policies are enabled at the same time, a segment that is eligible for deletion due to either policy will be deleted. To avoid locking reads while still allowing deletes that modify the segment list we use a copy-on-write style segment list implementation that provides consistent views to allow a binary search to proceed on an immutable static snapshot view of the log segments while deletes are progressing.

Guarantees

The log provides a configuration parameter M which controls the maximum number of messages that are written before forcing a flush to disk. On startup a log recovery process is run that iterates over all messages in the newest log segment and verifies that each message entry is valid. A message entry is valid if the sum of its size and offset are less than the length of the file AND the CRC32 of the message payload matches the CRC stored with the message. In the event corruption is detected the log is truncated to the last valid offset.

Note that two kinds of corruption must be handled: truncation in which an unwritten block is lost due to a crash, and corruption in which a nonsense block is ADDED to the file. The reason for this is that in general the OS makes no guarantee of the write order between the file inode and the actual block data so in addition to losing written data the file can gain nonsense data if the inode is updated with a new size but a crash occurs before the block containing that data is written. The CRC detects this corner case, and prevents it from corrupting the log (though the unwritten messages are, of course, lost).

5.5 Distribution

Consumer Offset Tracking

Kafka consumer tracks the maximum offset it has consumed in each partition and has the capability to commit offsets so that it can resume from those offsets in the event of a restart. Kafka provides the option to store all the offsets for a given consumer group in a designated broker (for that group) called the group coordinator. i.e., any consumer instance in that consumer group should send its offset commits and fetches to that group coordinator (broker). Consumer groups are assigned to coordinators based on their group names. A consumer can look up its coordinator by issuing a FindCoordinatorRequest to any Kafka broker and reading the FindCoordinatorResponse which will contain the coordinator details. The consumer can then proceed to commit or fetch offsets from the coordinator broker. In case the coordinator moves, the consumer will need to rediscover the coordinator. Offset commits can be done automatically or manually by consumer instance.

When the group coordinator receives an OffsetCommitRequest, it appends the request to a special compacted Kafka topic named __consumer_offsets. The broker sends a successful offset commit response to the consumer only after all the replicas of the offsets topic receive the offsets. In case the offsets fail to replicate within a configurable timeout, the offset commit will fail and the consumer may retry the commit after backing off. The brokers periodically compact the offsets topic since it only needs to maintain the most recent offset commit per partition. The coordinator also caches the offsets in an in-memory table in order to serve offset fetches quickly.

When the coordinator receives an offset fetch request, it simply returns the last committed offset vector from the offsets cache. In case coordinator was just started or if it just became the coordinator for a new set of consumer groups (by becoming a leader for a partition of the offsets topic), it may need to load the offsets topic partition into the cache. In this case, the offset fetch will fail with an CoordinatorLoadInProgressException and the consumer may retry the OffsetFetchRequest after backing off.

ZooKeeper Directories

The following gives the ZooKeeper structures and algorithms used for co-ordination between consumers and brokers.

Notation

When an element in a path is denoted , that means that the value of xyz is not fixed and there is in fact a ZooKeeper znode for each possible value of xyz. For example would be a directory named /topics containing a sub-directory for each topic name. Numerical ranges are also given such as to indicate the subdirectories 0, 1, 2, 3, 4. An arrow is used to indicate the contents of a znode. For example would indicate a znode /hello containing the value "world". [xyz]/topics/[topic][0...5]->/hello -> world

Broker Node Registry

/brokers/ids/[0...N] --> {"jmx_port":...,"timestamp":...,"endpoints":[...],"host":...,"version":...,"port":...} (ephemeral node)

This is a list of all present broker nodes, each of which provides a unique logical broker id which identifies it to consumers (which must be given as part of its configuration). On startup, a broker node registers itself by creating a znode with the logical broker id under /brokers/ids. The purpose of the logical broker id is to allow a broker to be moved to a different physical machine without affecting consumers. An attempt to register a broker id that is already in use (say because two servers are configured with the same broker id) results in an error.

Since the broker registers itself in ZooKeeper using ephemeral znodes, this registration is dynamic and will disappear if the broker is shutdown or dies (thus notifying consumers it is no longer available).

Broker Topic Registry

/brokers/topics/[topic]/partitions/[0...N]/state --> {"controller_epoch":...,"leader":...,"version":...,"leader_epoch":...,"isr":[...]} (ephemeral node)

Each broker registers itself under the topics it maintains and stores the number of partitions for that topic.

Cluster Id

The cluster id is a unique and immutable identifier assigned to a Kafka cluster. The cluster id can have a maximum of 22 characters and the allowed characters are defined by the regular expression [a-zA-Z0-9_\-]+, which corresponds to the characters used by the URL-safe Base64 variant with no padding. Conceptually, it is auto-generated when a cluster is started for the first time.

Implementation-wise, it is generated when a broker with version 0.10.1 or later is successfully started for the first time. The broker tries to get the cluster id from the znode during startup. If the znode does not exist, the broker generates a new cluster id and creates the znode with this cluster id. /cluster/id

Broker node registration

The broker nodes are basically independent, so they only publish information about what they have. When a broker joins, it registers itself under the broker node registry directory and writes information about its host name and port. The broker also register the list of existing topics and their logical partitions in the broker topic registry. New topics are registered dynamically when they are created on the broker.

6. 运营

以下是根据 LinkedIn 的使用情况和经验,将 Kafka 作为生产系统实际运行的一些信息。请将您知道的任何其他提示发送给我们。

6.1 基本 Kafka作

本节将回顾您将在 Kafka 集群上执行的最常见作。本节中回顾的所有工具都可以在bin/目录下的目录中,如果每个工具在没有参数的情况下运行,它将打印所有可能的命令行选项的详细信息。

添加和删除主题

您可以选择手动添加主题,也可以在首次将数据发布到不存在的主题时自动创建主题。如果主题是自动创建的,则可能需要调整用于自动创建主题的默认主题配置

使用主题工具添加和修改主题:

  > bin/kafka-topics.sh --bootstrap-server broker_host:port --create --topic my_topic_name \
        --partitions 20 --replication-factor 3 --config x=y
复制因子控制将复制写入的每条消息的服务器数。如果您的复制因子为 3,则在您失去对数据的访问权限之前,最多 2 台服务器可能会失败。我们建议您使用 2 或 3 的复制因子,以便您可以在不中断数据使用的情况下透明地退回计算机。

分区计数控制主题将被分片到多少个日志。分区计数有多种影响。首先,每个分区必须完全适合单个服务器。因此,如果您有 20 个分区,则完整数据集(以及读写负载)将由不超过 20 个服务器(不包括副本)处理。最后,分区计数会影响使用者的最大并行度。这在概念部分中进行了更详细的讨论。

每个分片分区日志都放置在 Kafka 日志目录下自己的文件夹中。此类文件夹的名称由主题名称(附加短划线 (-) 和分区 ID 组成。由于典型的文件夹名称不能超过 255 个字符,因此主题名称的长度将受到限制。我们假设分区数永远不会超过 100,000。因此,主题名称不能超过 249 个字符。这在文件夹名称中为短划线和可能长达 5 位的分区 ID 留出了足够的空间。

在命令行上添加的配置将覆盖服务器对数据应保留时间长度等内容的默认设置。此处记录了完整的按主题配置集。

修改主题

您可以使用相同的主题工具更改主题的配置或分区。

要添加分区,您可以执行

  > bin/kafka-topics.sh --bootstrap-server broker_host:port --alter --topic my_topic_name \
        --partitions 40
请注意,分区的一个用例是对数据进行语义分区,添加分区不会更改现有数据的分区,因此,如果消费者依赖该分区,这可能会打扰他们。也就是说,如果数据按hash(key) % number_of_partitions然后,此分区可能会通过添加分区进行洗牌,但 Kafka 不会尝试以任何方式自动重新分配数据。

要添加配置:

  > bin/kafka-configs.sh --bootstrap-server broker_host:port --entity-type topics --entity-name my_topic_name --alter --add-config x=y
要删除配置:最后删除主题:
  > bin/kafka-configs.sh --bootstrap-server broker_host:port --entity-type topics --entity-name my_topic_name --alter --delete-config x
  > bin/kafka-topics.sh --bootstrap-server broker_host:port --delete --topic my_topic_name

Kafka 目前不支持减少主题的分区数量。

有关更改主题的复制因子的说明,请参阅此处

正常关闭

Kafka 集群将自动检测任何代理关闭或故障,并为该计算机上的分区选举新的领导者。无论服务器发生故障还是因维护或配置更改而故意关闭,都会发生这种情况。对于后一种情况,Kafka 支持一种更优雅的机制来停止服务器,而不仅仅是杀死它。 当服务器正常停止时,它将利用两个优化:
  1. 它会将其所有日志同步到磁盘,以避免在重新启动时需要进行任何日志恢复(即验证日志尾部所有消息的校验和)。日志恢复需要时间,因此这会加快有意重启的速度。
  2. 它会在关闭之前将服务器作为领导者的任何分区迁移到其他副本。这将使领导权转移更快,并将每个分区不可用的时间缩短到几毫秒。
每当服务器停止时,同步日志都会自动进行,而不是通过硬终止,但受控领导迁移需要使用特殊设置:请注意,只有当代理上托管的所有分区都有副本(即复制因子大于 1 这些副本中至少有一个是活的)。这通常是您想要的,因为关闭最后一个副本会使该主题分区不可用。
      controlled.shutdown.enable=true

平衡领导力

每当 broker 停止或崩溃时,该 broker 分区的领导权就会转移到其他副本。当 broker 重新启动时,它只会是其所有分区的 follower,这意味着它不会用于客户端读取和写入。

为了避免这种不平衡,Kafka 有一个首选副本的概念。如果分区的副本列表为 1,5,9,则节点 1 优先于节点 5 或 9 作为领导者,因为它在副本列表中较早。默认情况下,Kafka 集群将尝试恢复对首选副本的领导地位。此行为配置为:

      auto.leader.rebalance.enable=true
您也可以将其设置为 false,但随后需要通过运行以下命令来手动恢复对已恢复副本的领导地位:
  > bin/kafka-leader-election.sh --bootstrap-server broker_host:port --election-type preferred --all-topic-partitions

跨机架平衡副本

机架感知功能将同一分区的副本分布在不同的机架上。这将 Kafka 为代理故障提供的保证扩展到机架故障,从而限制了机架上的所有代理同时发生故障时数据丢失的风险。该功能还可以应用于其他代理分组,例如 EC2 中的可用区。 您可以通过向代理配置添加属性来指定代理属于特定机架:当创建修改主题或重新分发副本时,将遵循机架约束,确保副本跨越尽可能多的机架(分区将跨越 min(#racks, replication-factor) 不同的机架)。 用于将副本分配给 broker 的算法可确保每个 broker 的 leader 数量保持不变,而不管 broker 在机架之间的分布方式如何。这确保了平衡的吞吐量。 但是,如果为机架分配了不同数量的代理,则副本的分配将不均匀。代理较少的机架将获得更多副本,这意味着它们将使用更多存储并将更多资源投入到复制中。因此,为每个机架配置相同数量的代理是明智的。

  broker.rack=my-rack-id

在集群和地理复制之间镜像数据

Kafka 管理员可以定义跨越单个 Kafka 集群、数据中心或地理区域边界的数据流。有关更多信息,请参阅异地复制部分。

检查使用者位置

有时,了解消费者的位置很有用。我们有一个工具,可以显示消费者组内所有消费者的位置,以及他们与日志末尾的差距。要在名为 my-group 的使用者组上运行此工具,请使用名为 my-topic 的主题,如下所示:
  > bin/kafka-consumer-groups.sh --bootstrap-server localhost:9092 --describe --group my-group

  TOPIC                          PARTITION  CURRENT-OFFSET  LOG-END-OFFSET  LAG        CONSUMER-ID                                       HOST                           CLIENT-ID
  my-topic                       0          2               4               2          consumer-1-029af89c-873c-4751-a720-cefd41a669d6   /127.0.0.1                     consumer-1
  my-topic                       1          2               3               1          consumer-1-029af89c-873c-4751-a720-cefd41a669d6   /127.0.0.1                     consumer-1
  my-topic                       2          2               3               1          consumer-2-42c1abd4-e3b2-425d-a8bb-e1ea49b29bb2   /127.0.0.1                     consumer-2

管理消费组

使用 ConsumerGroupCommand 工具,我们可以列出、描述或删除使用者组。可以手动删除使用者组,也可以在该组的上次提交的偏移量过期时自动删除。仅当组没有任何活动成员时,手动删除才有效。 例如,要列出所有主题中的所有使用者组:要查看偏移量,如前所述,我们像这样“描述”使用者组:还有许多其他 “describe” 选项可用于提供有关使用者组的更多详细信息:
  > bin/kafka-consumer-groups.sh --bootstrap-server localhost:9092 --list

  test-consumer-group
  > bin/kafka-consumer-groups.sh --bootstrap-server localhost:9092 --describe --group my-group

  TOPIC           PARTITION  CURRENT-OFFSET  LOG-END-OFFSET  LAG             CONSUMER-ID                                    HOST            CLIENT-ID
  topic3          0          241019          395308          154289          consumer2-e76ea8c3-5d30-4299-9005-47eb41f3d3c4 /127.0.0.1      consumer2
  topic2          1          520678          803288          282610          consumer2-e76ea8c3-5d30-4299-9005-47eb41f3d3c4 /127.0.0.1      consumer2
  topic3          1          241018          398817          157799          consumer2-e76ea8c3-5d30-4299-9005-47eb41f3d3c4 /127.0.0.1      consumer2
  topic1          0          854144          855809          1665            consumer1-3fc8d6f1-581a-4472-bdf3-3515b4aee8c1 /127.0.0.1      consumer1
  topic2          0          460537          803290          342753          consumer1-3fc8d6f1-581a-4472-bdf3-3515b4aee8c1 /127.0.0.1      consumer1
  topic3          2          243655          398812          155157          consumer4-117fe4d3-c6c1-4178-8ee9-eb4a3954bee0 /127.0.0.1      consumer4
  • --members:此选项提供使用者组中所有活动成员的列表。
          > bin/kafka-consumer-groups.sh --bootstrap-server localhost:9092 --describe --group my-group --members
    
          CONSUMER-ID                                    HOST            CLIENT-ID       #PARTITIONS
          consumer1-3fc8d6f1-581a-4472-bdf3-3515b4aee8c1 /127.0.0.1      consumer1       2
          consumer4-117fe4d3-c6c1-4178-8ee9-eb4a3954bee0 /127.0.0.1      consumer4       1
          consumer2-e76ea8c3-5d30-4299-9005-47eb41f3d3c4 /127.0.0.1      consumer2       3
          consumer3-ecea43e4-1f01-479f-8349-f9130b75d8ee /127.0.0.1      consumer3       0
  • --members --verbose:除了上述 “--members” 选项报告的信息之外,此选项还提供分配给每个成员的分区。
          > bin/kafka-consumer-groups.sh --bootstrap-server localhost:9092 --describe --group my-group --members --verbose
    
          CONSUMER-ID                                    HOST            CLIENT-ID       #PARTITIONS     ASSIGNMENT
          consumer1-3fc8d6f1-581a-4472-bdf3-3515b4aee8c1 /127.0.0.1      consumer1       2               topic1(0), topic2(0)
          consumer4-117fe4d3-c6c1-4178-8ee9-eb4a3954bee0 /127.0.0.1      consumer4       1               topic3(2)
          consumer2-e76ea8c3-5d30-4299-9005-47eb41f3d3c4 /127.0.0.1      consumer2       3               topic2(1), topic3(0,1)
          consumer3-ecea43e4-1f01-479f-8349-f9130b75d8ee /127.0.0.1      consumer3       0               -
  • --offsets:这是默认的 describe 选项,提供与 “--describe” 选项相同的输出。
  • --state:此选项提供有用的组级别信息。
          > bin/kafka-consumer-groups.sh --bootstrap-server localhost:9092 --describe --group my-group --state
    
          COORDINATOR (ID)          ASSIGNMENT-STRATEGY       STATE                #MEMBERS
          localhost:9092 (0)        range                     Stable               4
要手动删除一个或多个消费者组,可以使用 “--delete” 选项:
  > bin/kafka-consumer-groups.sh --bootstrap-server localhost:9092 --delete --group my-group --group my-other-group

  Deletion of requested consumer groups ('my-group', 'my-other-group') was successful.

要重置消费组的偏移量,可以使用 “--reset-offsets” 选项。 此选项一次支持一个使用者组。它需要定义以下范围:--all-topics 或 --topic。必须选择一个范围,除非您使用“--from-file”方案。此外,首先确保使用者实例处于非活动状态。 有关更多详细信息,请参阅 KIP-122

它有 3 个执行选项:

  • (默认)显示要重置的偏移量。
  • --execute : 执行 --reset-offsets 进程。
  • --export :将结果导出为 CSV 格式。

--reset-offsets 还有以下场景可供选择(必须至少选择一个场景):

  • --to-datetime <String: datetime> : 将偏移量重置为与日期时间的偏移量。格式:'YYYY-MM-DDTHH:mm:SS.sss'
  • --to-earliest : 将偏移量重置为最早的偏移量。
  • --to-latest : 将偏移量重置为最新偏移量。
  • --shift-by <Long: 偏移量> : 重置偏移量 'n' 移动电流偏移量,其中 'n' 可以是正数或负数。
  • --from-file :将偏移量重置为 CSV 文件中定义的值。
  • --to-current :将偏移量重置为当前偏移量。
  • --by-duration <String: duration> : 重置当前时间戳的偏移量以按持续时间偏移量。格式:'PnDTnHnMnS'
  • --to-offset : 将偏移量重置为特定偏移量。
请注意,超出范围的偏移量将调整到可用的偏移端。例如,如果偏移端为 10,偏移偏移请求为 的 15 中,则实际上将选择 10 处的偏移量。

例如,将消费组的偏移量重置为最新的偏移量:

  > bin/kafka-consumer-groups.sh --bootstrap-server localhost:9092 --reset-offsets --group consumergroup1 --topic topic1 --to-latest

  TOPIC                          PARTITION  NEW-OFFSET
  topic1                         0          0

如果您使用的是旧的高级使用者并将组元数据存储在 ZooKeeper 中(即offsets.storage=zookeeper)、通过--zookeeper而不是--bootstrap-server:

  > bin/kafka-consumer-groups.sh --zookeeper localhost:2181 --list

扩展您的集群

将服务器添加到 Kafka 集群非常简单,只需为它们分配一个唯一的代理 ID,然后在新服务器上启动 Kafka。但是,这些新服务器不会自动分配任何数据分区,因此,除非将分区移动到这些服务器,否则在创建新主题之前,它们不会执行任何工作。因此,通常当您将计算机添加到集群时,您将希望将一些现有数据迁移到这些计算机。

迁移数据的过程是手动启动的,但完全自动化。在幕后,Kafka 会将新服务器添加为它正在迁移的分区的追随者,并允许它完全复制该分区中的现有数据。当新服务器完全复制此分区的内容并加入同步副本时,现有副本之一将删除其分区的数据。

分区重新分配工具可用于在 broker 之间移动分区。理想的分区分布将确保所有代理之间的数据负载和分区大小均匀。分区重新分配工具无法自动研究 Kafka 集群中的数据分布并移动分区以实现均匀的负载分布。因此,管理员必须弄清楚应该移动哪些主题或分区。

分区重新分配工具可以在 3 种互斥模式下运行:

  • --generate:在此模式下,给定主题列表和代理列表,该工具会生成候选重新分配,以将指定主题的所有分区移动到新代理。此选项仅提供了一种在给定主题和目标代理列表的情况下生成分区重新分配计划的便捷方法。
  • --execute:在此模式下,该工具根据用户提供的重新分配计划启动分区的重新分配。(使用 --reassignment-json-file 选项)。这可以是管理员手动制作的自定义重新分配计划,也可以是使用 --generate 选项提供的
  • --verify:在此模式下,该工具会验证上次 --execute 期间列出的所有分区的重新分配状态。状态可以是 successfully completed、failed 或 in progress
自动将数据迁移到新计算机
分区重新分配工具可用于将当前代理集中的某些主题移动到新添加的代理。这在扩展现有集群时通常很有用,因为与一次移动一个分区相比,将整个主题移动到新的代理集更容易。用于执行此作时,用户应提供应移动到新代理集的主题列表和新代理的目标列表。然后,该工具将给定主题列表的所有分区均匀分布到新的代理集。在此移动期间,主题的复制因子保持不变。实际上,主题输入列表的所有分区的副本都从旧的代理集移动到新添加的代理。

例如,以下示例会将主题 foo1,foo2 的所有分区移动到新的代理集 5,6。在这次移动结束时,主题 foo1 和 foo2 的所有分区将存在于代理 5,6 上。

由于该工具接受主题输入列表作为 json 文件,因此您首先需要确定要移动的主题并创建 json 文件,如下所示:

  > cat topics-to-move.json
  {"topics": [{"topic": "foo1"},
              {"topic": "foo2"}],
  "version":1
  }
json 文件准备就绪后,使用分区重新分配工具生成候选分配:
  > bin/kafka-reassign-partitions.sh --bootstrap-server localhost:9092 --topics-to-move-json-file topics-to-move.json --broker-list "5,6" --generate
  Current partition replica assignment

  {"version":1,
  "partitions":[{"topic":"foo1","partition":0,"replicas":[2,1]},
                {"topic":"foo1","partition":1,"replicas":[1,3]},
                {"topic":"foo1","partition":2,"replicas":[3,4]},
                {"topic":"foo2","partition":0,"replicas":[4,2]},
                {"topic":"foo2","partition":1,"replicas":[2,1]},
                {"topic":"foo2","partition":2,"replicas":[1,3]}]
  }

  Proposed partition reassignment configuration

  {"version":1,
  "partitions":[{"topic":"foo1","partition":0,"replicas":[6,5]},
                {"topic":"foo1","partition":1,"replicas":[5,6]},
                {"topic":"foo1","partition":2,"replicas":[6,5]},
                {"topic":"foo2","partition":0,"replicas":[5,6]},
                {"topic":"foo2","partition":1,"replicas":[6,5]},
                {"topic":"foo2","partition":2,"replicas":[5,6]}]
  }

该工具会生成一个候选分配,该分配会将所有分区从主题 foo1,foo2 移动到代理 5,6。但是请注意,此时分区移动尚未开始,它只是告诉您当前分配和建议的新分配。应保存当前分配,以防您要回滚到它。新分配应保存在 json 文件(例如 expand-cluster-reassignment.json)中,以便使用 --execute 选项输入到工具中,如下所示:

  > bin/kafka-reassign-partitions.sh --bootstrap-server localhost:9092 --reassignment-json-file expand-cluster-reassignment.json --execute
  Current partition replica assignment

  {"version":1,
  "partitions":[{"topic":"foo1","partition":0,"replicas":[2,1]},
                {"topic":"foo1","partition":1,"replicas":[1,3]},
                {"topic":"foo1","partition":2,"replicas":[3,4]},
                {"topic":"foo2","partition":0,"replicas":[4,2]},
                {"topic":"foo2","partition":1,"replicas":[2,1]},
                {"topic":"foo2","partition":2,"replicas":[1,3]}]
  }

  Save this to use as the --reassignment-json-file option during rollback
  Successfully started partition reassignments for foo1-0,foo1-1,foo1-2,foo2-0,foo2-1,foo2-2
  

最后,--verify 选项可以与该工具一起使用,以检查分区重新分配的状态。请注意,相同的expand-cluster-reassignment.json(与 --execute 选项一起使用)应与 --verify 选项一起使用:

  > bin/kafka-reassign-partitions.sh --bootstrap-server localhost:9092 --reassignment-json-file expand-cluster-reassignment.json --verify
  Status of partition reassignment:
  Reassignment of partition [foo1,0] is completed
  Reassignment of partition [foo1,1] is still in progress
  Reassignment of partition [foo1,2] is still in progress
  Reassignment of partition [foo2,0] is completed
  Reassignment of partition [foo2,1] is completed
  Reassignment of partition [foo2,2] is completed
自定义分区分配和迁移
分区重新分配工具还可用于有选择地将分区的副本移动到一组特定的代理。以这种方式使用时,假定用户知道重新分配计划,并且不需要该工具生成候选重新分配,从而有效地跳过 --generate 步骤并直接进入 --execute 步骤

例如,以下示例将主题 foo1 的分区 0 移动到代理 5,6,将主题 foo2 的分区 1 移动到代理 2,3:

第一步是在 json 文件中手动制作自定义重新分配计划:

  > cat custom-reassignment.json
  {"version":1,"partitions":[{"topic":"foo1","partition":0,"replicas":[5,6]},{"topic":"foo2","partition":1,"replicas":[2,3]}]}
然后,使用带有 --execute 选项的 json 文件开始重新分配过程:
  > bin/kafka-reassign-partitions.sh --bootstrap-server localhost:9092 --reassignment-json-file custom-reassignment.json --execute
  Current partition replica assignment

  {"version":1,
  "partitions":[{"topic":"foo1","partition":0,"replicas":[1,2]},
                {"topic":"foo2","partition":1,"replicas":[3,4]}]
  }

  Save this to use as the --reassignment-json-file option during rollback
  Successfully started partition reassignments for foo1-0,foo2-1
  

--verify 选项可以与该工具一起使用,以检查分区重新分配的状态。请注意,相同的custom-reassignment.json(与 --execute 选项一起使用)应与 --verify 选项一起使用:

  > bin/kafka-reassign-partitions.sh --bootstrap-server localhost:9092 --reassignment-json-file custom-reassignment.json --verify
  Status of partition reassignment:
  Reassignment of partition [foo1,0] is completed
  Reassignment of partition [foo2,1] is completed

停用代理

分区重新分配工具尚不能自动生成用于停用代理的重新分配计划。因此,管理员必须提出一个重新分配计划,将托管在 broker 上的所有分区的副本移动到其余的 broker 中。这可能相对繁琐,因为重新分配需要确保所有副本都不会从已停用的代理移动到仅另一个代理。为了简化此过程,我们计划在未来添加对停用 broker 的工具支持。

增加复制因子

增加现有分区的复制因子很容易。只需在自定义重新分配 json 文件中指定额外的副本,并将其与 --execute 选项一起使用,即可增加指定分区的复制因子。

例如,以下示例将主题 foo 的分区 0 的复制因子从 1 增加到 3。在增加复制因子之前,分区的唯一副本存在于代理 5 上。作为增加复制因子的一部分,我们将在代理 6 和 7 上添加更多副本。

第一步是在 json 文件中手动制作自定义重新分配计划:

  > cat increase-replication-factor.json
  {"version":1,
  "partitions":[{"topic":"foo","partition":0,"replicas":[5,6,7]}]}
然后,使用带有 --execute 选项的 json 文件开始重新分配过程:
  > bin/kafka-reassign-partitions.sh --bootstrap-server localhost:9092 --reassignment-json-file increase-replication-factor.json --execute
  Current partition replica assignment

  {"version":1,
  "partitions":[{"topic":"foo","partition":0,"replicas":[5]}]}

  Save this to use as the --reassignment-json-file option during rollback
  Successfully started partition reassignment for foo-0

--verify 选项可以与该工具一起使用,以检查分区重新分配的状态。请注意,相同的increase-replication-factor.json(与 --execute 选项一起使用)应与 --verify 选项一起使用:

  > bin/kafka-reassign-partitions.sh --bootstrap-server localhost:9092 --reassignment-json-file increase-replication-factor.json --verify
  Status of partition reassignment:
  Reassignment of partition [foo,0] is completed
您还可以使用 kafka-topics 工具验证复制因子的增加:
  > bin/kafka-topics.sh --bootstrap-server localhost:9092 --topic foo --describe
  Topic:foo	PartitionCount:1	ReplicationFactor:3	Configs:
    Topic: foo	Partition: 0	Leader: 5	Replicas: 5,6,7	Isr: 5,6,7

限制数据迁移期间的带宽使用

Kafka 允许您对复制流量应用限制,为用于在计算机之间移动副本的带宽设置上限。这在重新平衡集群、引导新代理或者添加或删除代理时非常有用,因为它限制了这些数据密集型作对用户的影响。 有两个接口可用于启用节流。最简单、最安全的是在调用 kafka-reassign-partitions.sh 时应用限制,但 kafka-configs.sh 也可以用于直接查看和更改限制值。 因此,例如,如果您要执行再平衡,使用以下命令,它将以不超过 50MB/s 的速度移动分区。 当您执行此脚本时,您将看到 throttle engage:

$ bin/kafka-reassign-partitions.sh --bootstrap-server localhost:9092 --execute --reassignment-json-file bigger-cluster.json --throttle 50000000
  The inter-broker throttle limit was set to 50000000 B/s
  Successfully started partition reassignment for foo1-0

如果您希望在重新平衡期间更改限制,例如增加吞吐量以使其更快地完成,您可以通过使用 --additional 选项重新运行 execute 命令来执行此作,并传递相同的 reassignment-json-file:

$ bin/kafka-reassign-partitions.sh --bootstrap-server localhost:9092  --additional --execute --reassignment-json-file bigger-cluster.json --throttle 700000000
  The inter-broker throttle limit was set to 700000000 B/s

再平衡完成后,管理员可以使用 --verify 选项检查再平衡的状态。 如果再平衡已完成,将通过 --verify 命令删除限制。重要的是 重新平衡完成后,管理员通过使用 --verify 选项。否则,可能会导致常规复制流量受到限制。

执行 --verify 选项并完成重新分配时,脚本将确认已删除限制:

  > bin/kafka-reassign-partitions.sh --bootstrap-server localhost:9092  --verify --reassignment-json-file bigger-cluster.json
  Status of partition reassignment:
  Reassignment of partition [my-topic,1] is completed
  Reassignment of partition [my-topic,0] is completed

  Clearing broker-level throttles on brokers 1,2,3
  Clearing topic-level throttles on topic my-topic

管理员还可以使用 kafka-configs.sh 验证分配的配置。有两对节气门 配置。第一对是指 throttle 值本身。这是在 broker level 中,使用动态属性:

    leader.replication.throttled.rate
    follower.replication.throttled.rate

然后是受限制副本的枚举集的配置对:

    leader.replication.throttled.replicas
    follower.replication.throttled.replicas

哪些是按主题配置的。

所有四个 config 值都由 kafka-reassign-partitions.sh 自动分配(如下所述)。

要查看限制配置,请执行以下作:

  > bin/kafka-configs.sh --describe --bootstrap-server localhost:9092 --entity-type brokers
  Configs for brokers '2' are leader.replication.throttled.rate=700000000,follower.replication.throttled.rate=700000000
  Configs for brokers '1' are leader.replication.throttled.rate=700000000,follower.replication.throttled.rate=700000000

这显示了应用于复制协议的 leader 端和 follower 端的限制。默认情况下,两侧 分配相同的受限制吞吐量值。

要查看受限制的副本列表,请执行以下作:

  > bin/kafka-configs.sh --describe --bootstrap-server localhost:9092 --entity-type topics
  Configs for topic 'my-topic' are leader.replication.throttled.replicas=1:102,0:101,
      follower.replication.throttled.replicas=1:101,0:102

在这里,我们看到领导限制应用于代理 102 上的分区 1 和代理 101 上的分区 0。同样, Follower Throttle 应用于分区 1 代理 101 和代理 102 上的分区 0。

默认情况下 kafka-reassign-partitions.sh 会将 leader 限制应用于 rebalance,其中任何一个都可能是 leader。 它将 follower 限制应用于所有移动目的地。因此,如果代理上有一个分区具有副本 101,102,被重新分配给 102,103,一个领导者限制, 对于该分区,将应用于 101,102,而 follower throttle 将仅应用于 103。

如果需要,您还可以使用 kafka-configs.sh 上的 --alter 开关手动更改限制配置。

安全使用受限制的复制

使用受限制的复制时应小心。特别:

(1) 油门拆卸:

重新分配完成后,应及时删除限制(通过运行 kafka-reassign-partitions.sh --verify 的 intent 函数)。

(2) 确保进度:

如果 throttle 设置得太低,则与传入写入速率相比,复制可能会 捗。这在以下情况下发生:

max(BytesInPerSec) > throttle

其中 BytesInPerSec 是监控创建器对每个代理的写入吞吐量的指标。

管理员可以使用以下指标在再平衡期间监控复制是否正在进行:

kafka.server:type=FetcherLagMetrics,name=ConsumerLag,clientId=([-.\w]+),topic=([-.\w]+),partition=([0-9]+)

在复制过程中,滞后应不断减少。如果指标没有减少,管理员应该 增加 如上所述限制吞吐量。

设置配额

配额覆盖和默认值可以在 (user, client-id)、user 或 client-id 级别进行配置,如此所述。 默认情况下,客户端会收到无限制的配额。 可以为每个 (user, client-id)、user 或 client-id 组设置自定义配额。

为 (user=user1, client-id=clientA) 配置自定义配额:

  > bin/kafka-configs.sh  --bootstrap-server localhost:9092 --alter --add-config 'producer_byte_rate=1024,consumer_byte_rate=2048,request_percentage=200' --entity-type users --entity-name user1 --entity-type clients --entity-name clientA
  Updated config for entity: user-principal 'user1', client-id 'clientA'.
为 user=user1 配置自定义配额:为 client-id=clientA 配置自定义配额:可以通过指定 --entity-default 选项而不是 --entity-name 为每个(用户、client-id)、用户或 client-id 组设置默认配额。
  > bin/kafka-configs.sh  --bootstrap-server localhost:9092 --alter --add-config 'producer_byte_rate=1024,consumer_byte_rate=2048,request_percentage=200' --entity-type users --entity-name user1
  Updated config for entity: user-principal 'user1'.
  > bin/kafka-configs.sh  --bootstrap-server localhost:9092 --alter --add-config 'producer_byte_rate=1024,consumer_byte_rate=2048,request_percentage=200' --entity-type clients --entity-name clientA
  Updated config for entity: client-id 'clientA'.

为 user=userA 配置默认 client-id 配额:

  > bin/kafka-configs.sh  --bootstrap-server localhost:9092 --alter --add-config 'producer_byte_rate=1024,consumer_byte_rate=2048,request_percentage=200' --entity-type users --entity-name user1 --entity-type clients --entity-default
  Updated config for entity: user-principal 'user1', default client-id.
为用户配置默认配额:为 client-id 配置默认配额:下面介绍如何描述给定 (user, client-id) 的配额:描述给定用户的配额:描述给定 client-id 的配额:如果未指定实体名称,则描述指定类型的所有实体。例如,describe all users:类似地 for (user, client):
  > bin/kafka-configs.sh  --bootstrap-server localhost:9092 --alter --add-config 'producer_byte_rate=1024,consumer_byte_rate=2048,request_percentage=200' --entity-type users --entity-default
  Updated config for entity: default user-principal.
  > bin/kafka-configs.sh  --bootstrap-server localhost:9092 --alter --add-config 'producer_byte_rate=1024,consumer_byte_rate=2048,request_percentage=200' --entity-type clients --entity-default
  Updated config for entity: default client-id.
  > bin/kafka-configs.sh  --bootstrap-server localhost:9092 --describe --entity-type users --entity-name user1 --entity-type clients --entity-name clientA
  Configs for user-principal 'user1', client-id 'clientA' are producer_byte_rate=1024,consumer_byte_rate=2048,request_percentage=200
  > bin/kafka-configs.sh  --bootstrap-server localhost:9092 --describe --entity-type users --entity-name user1
  Configs for user-principal 'user1' are producer_byte_rate=1024,consumer_byte_rate=2048,request_percentage=200
  > bin/kafka-configs.sh  --bootstrap-server localhost:9092 --describe --entity-type clients --entity-name clientA
  Configs for client-id 'clientA' are producer_byte_rate=1024,consumer_byte_rate=2048,request_percentage=200
  > bin/kafka-configs.sh  --bootstrap-server localhost:9092 --describe --entity-type users
  Configs for user-principal 'user1' are producer_byte_rate=1024,consumer_byte_rate=2048,request_percentage=200
  Configs for default user-principal are producer_byte_rate=1024,consumer_byte_rate=2048,request_percentage=200
  > bin/kafka-configs.sh  --bootstrap-server localhost:9092 --describe --entity-type users --entity-type clients
  Configs for user-principal 'user1', default client-id are producer_byte_rate=1024,consumer_byte_rate=2048,request_percentage=200
  Configs for user-principal 'user1', client-id 'clientA' are producer_byte_rate=1024,consumer_byte_rate=2048,request_percentage=200

6.2 数据中心

某些部署需要管理跨多个数据中心的数据管道。我们推荐的方法是在每个数据中心部署一个本地 Kafka 集群,每个数据中心中的应用程序实例仅与其本地集群交互,并在集群之间镜像数据(有关如何执行此作,请参阅有关异地复制的文档)。

这种部署模式允许数据中心充当独立实体,并允许我们集中管理和调整数据中心间复制。这允许每个设施独立运行,即使数据中心间链路不可用:发生这种情况时,镜像会滞后,直到链路恢复,此时它会赶上来。

对于需要所有数据的全局视图的应用程序,您可以使用镜像来提供集群,这些集群具有从所有数据中心的本地集群镜像的聚合数据。这些聚合集群用于需要完整数据集的应用程序的读取。

这不是唯一可能的部署模式。可以通过 WAN 读取或写入远程 Kafka 集群,但显然这会增加获取集群所需的任何延迟。

Kafka 自然会在创建者和使用者中对数据进行批处理,因此即使在高延迟连接上也可以实现高吞吐量。但要允许这样做,可能需要使用socket.send.buffer.bytessocket.receive.buffer.bytes配置。此处记录了设置此项的适当方法。

通常不建议通过高延迟链接运行跨多个数据中心的单个 Kafka 集群。这将导致 Kafka 写入和 ZooKeeper 写入的复制延迟非常高,如果位置之间的网络不可用,Kafka 和 ZooKeeper 都不会在所有位置保持可用。

6.3 异地复制(跨集群数据镜像)

异地复制概述

Kafka 管理员可以定义跨越单个 Kafka 集群、数据中心或地理区域边界的数据流。组织、技术或法律要求通常需要此类事件流式处理设置。常见方案包括:

  • 异地复制
  • 灾难恢复
  • 将边缘集群馈送到一个中央聚合集群中
  • 集群的物理隔离(例如生产与测试)
  • 云迁移或混合云部署
  • 法律和合规性要求

管理员可以使用 Kafka 的 MirrorMaker(版本 2)设置此类集群间数据流,该工具以流方式在不同 Kafka 环境之间复制数据。MirrorMaker 构建在 Kafka Connect 框架之上,支持以下功能:

  • 复制主题(数据加配置)
  • 复制使用者组(包括偏移量),以在集群之间迁移应用程序
  • 复制 ACL
  • 保留分区
  • 自动检测新主题和分区
  • 提供广泛的指标,例如跨多个数据中心/集群的端到端复制延迟
  • 容错和水平可扩展的作

注意:使用 MirrorMaker 进行异地复制可跨 Kafka 集群复制数据。这种集群间复制不同于 Kafka 的集群内复制,后者在同一 Kafka 集群内复制数据。

什么是复制流

借助 MirrorMaker,Kafka 管理员可以将主题、主题配置、使用者组及其偏移量和 ACL 从一个或多个源 Kafka 集群复制到一个或多个目标 Kafka 集群,即跨集群环境。简而言之,MirrorMaker 使用 Connector 从源集群使用并生成到目标集群。

这些从源集群到目标集群的定向流称为复制流。它们是用{source_cluster}->{target_cluster}在 MirrorMaker 配置文件中,如下所述。管理员可以基于这些流创建复杂的复制拓扑。

以下是一些示例模式:

  • 主动/主动高可用性部署:A->B, B->A
  • 主动/被动或主动/备用高可用性部署:A->B
  • 聚合(例如,从多个集群到一个集群):A->K, B->K, C->K
  • 扇出(例如,从一个集群到多个集群):K->A, K->B, K->C
  • 转发:A->B, B->C, C->D

默认情况会复制所有主题和使用者组。但是,每个复制流都可以独立配置。例如,您可以定义仅将特定主题或使用者组从源集群复制到目标集群。

以下是有关如何从primarycluster 添加到secondary群集(主动/被动设置):

# Basic settings
clusters = primary, secondary
primary.bootstrap.servers = broker3-primary:9092
secondary.bootstrap.servers = broker5-secondary:9092

# Define replication flows
primary->secondary.enabled = true
primary->secondary.topics = foobar-topic, quux-.*

配置异地复制

以下部分介绍如何配置和运行专用 MirrorMaker 集群。如果要在现有 Kafka Connect 集群或其他支持的部署设置中运行 MirrorMaker,请参阅 KIP-382:MirrorMaker 2.0,并注意配置设置的名称可能因部署模式而异。

除了以下部分涵盖的内容之外,有关配置设置的更多示例和信息,请访问:

配置文件语法

MirrorMaker 配置文件通常命名为connect-mirror-maker.properties.您可以在此文件中配置各种组件:

  • MirrorMaker 设置:全局设置,包括群集定义(别名)以及每个复制流的自定义设置
  • Kafka Connect 和连接器设置
  • Kafka 生产者、使用者和管理客户端设置

示例:定义 MirrorMaker 设置(稍后将更详细地解释)。

# Global settings
clusters = us-west, us-east   # defines cluster aliases
us-west.bootstrap.servers = broker3-west:9092
us-east.bootstrap.servers = broker5-east:9092

topics = .*   # all topics to be replicated by default

# Specific replication flow settings (here: flow from us-west to us-east)
us-west->us-east.enabled = true
us-west->us.east.topics = foo.*, bar.*  # override the default above

MirrorMaker 基于 Kafka Connect 框架。有关 Kafka Connect 的文档章节中所述的任何 Kafka Connect、源连接器和接收器连接器设置都可以直接在 MirrorMaker 配置中使用,而无需更改配置设置的名称或为其添加前缀。

示例:定义 MirrorMaker 要使用的自定义 Kafka Connect 设置。

# Setting Kafka Connect defaults for MirrorMaker
tasks.max = 5

大多数默认的 Kafka Connect 设置都适用于开箱即用的 MirrorMaker,但tasks.max.为了在多个 MirrorMaker 进程之间均匀分配工作负载,建议将tasks.max至少达到2(最好更高),具体取决于可用的硬件资源和要复制的主题分区的总数。

您可以进一步自定义每个源或目标集群的 MirrorMaker 的 Kafka Connect 设置(更准确地说,您可以“每个连接器”指定 Kafka Connect 工作线程级配置设置)。使用{cluster}.{config_name}在 MirrorMaker 配置文件中。

示例:为us-west簇。

# us-west custom settings
us-west.offset.storage.topic = my-mirrormaker-offsets

MirrorMaker 在内部使用 Kafka 生产者、使用者和管理客户端。通常需要为这些客户端进行自定义设置。要覆盖默认值,请在 MirrorMaker 配置文件中使用以下格式:

  • {source}.consumer.{consumer_config_name}
  • {target}.producer.{producer_config_name}
  • {source_or_target}.admin.{admin_config_name}

示例:定义自定义生产者、使用者、管理员客户端设置。

# us-west cluster (from which to consume)
us-west.consumer.isolation.level = read_committed
us-west.admin.bootstrap.servers = broker57-primary:9092

# us-east cluster (to which to produce)
us-east.producer.compression.type = gzip
us-east.producer.buffer.memory = 32768
us-east.admin.bootstrap.servers = broker8-secondary:9092
创建和启用复制流

要定义复制流,您必须首先在 MirrorMaker 配置文件中定义相应的源和目标 Kafka 集群。

  • clusters(必需):以逗号分隔的 Kafka 集群“别名”列表
  • {clusterAlias}.bootstrap.servers(必需):特定集群的连接信息;以逗号分隔的 “bootstrap” Kafka 代理列表

示例:定义两个集群别名primarysecondary,包括其连接信息。

clusters = primary, secondary
primary.bootstrap.servers = broker10-primary:9092,broker-11-primary:9092
secondary.bootstrap.servers = broker5-secondary:9092,broker6-secondary:9092

其次,您必须使用{source}->{target}.enabled = true根据需要。请记住,流是定向的:如果需要双向(双向)复制,则必须在两个方向上启用流。

# Enable replication from primary to secondary
primary->secondary.enabled = true

默认情况下,复制流会将除少数特殊主题和使用者组之外的所有主题和使用者组从源集群复制到目标集群,并自动检测任何新创建的主题和组。目标集群中复制的主题名称将以源集群的名称为前缀(请参阅下面的部分)。例如,主题foo在源集群中us-west将复制到名为us-west.foo在目标集群中us-east.

后续部分将介绍如何根据需要自定义此基本设置。

配置复制流

复制流的配置是顶级默认设置(例如topics),除此之外,还会应用特定于流的设置(如果有)(例如us-west->us-east.topics).要更改顶级默认值,请将相应的顶级设置添加到 MirrorMaker 配置文件中。要仅覆盖特定复制流的默认值,请使用语法格式{source}->{target}.{config.name}.

最重要的设置是:

  • topics:主题列表或定义源集群中要复制的主题的正则表达式(默认值:topics = .*)
  • topics.exclude:主题列表或正则表达式,以随后排除与topics设置(默认值:topics.exclude = .*[\-\.]internal, .*\.replica, __.*)
  • groups:定义源集群中要复制的使用者组的主题或正则表达式列表(默认值:groups = .*)
  • groups.exclude:主题列表或正则表达式,以随后排除与groups设置(默认值:groups.exclude = console-consumer-.*, connect-.*, __.*)
  • {source}->{target}.enable:设置为true要启用复制流(默认:false)

例:

# Custom top-level defaults that apply to all replication flows
topics = .*
groups = consumer-group1, consumer-group2

# Don't forget to enable a flow!
us-west->us-east.enabled = true

# Custom settings for specific replication flows
us-west->us-east.topics = foo.*
us-west->us-east.groups = bar.*
us-west->us-east.emit.heartbeats = false

支持其他配置设置,下面列出了其中一些设置。在大多数情况下,您可以将这些设置保留为默认值。有关更多详细信息,请参阅 MirrorMakerConfigMirrorConnectorConfig

  • refresh.topics.enabled:是否定期检查源集群中的新主题(默认值:true)
  • refresh.topics.interval.seconds:在源集群中检查新主题的频率;低于默认值可能会导致性能下降(默认值:600,每 10 分钟一次)
  • refresh.groups.enabled:是否定期检查源集群中的新消费组(默认值:true)
  • refresh.groups.interval.seconds:检查源集群中新消费组的频率;低于默认值可能会导致性能下降(默认值:600,每 10 分钟一次)
  • sync.topic.configs.enabled:是否从源集群复制 Topic 配置(默认:true)
  • sync.topic.acls.enabled:是否从源集群同步 ACL(默认值:true)
  • emit.heartbeats.enabled:是否定期发出心跳(默认值:true)
  • emit.heartbeats.interval.seconds:发出检测信号的频率(默认值:1,每 1 秒)
  • heartbeats.topic.replication.factor:MirrorMaker 内部心跳主题的复制因子(默认值:3)
  • emit.checkpoints.enabled:是否定期发出 MirrorMaker 的 consumer offsets(默认:true)
  • emit.checkpoints.interval.seconds:发出 checkpoint 的频率(默认值:每分钟 60 次)
  • checkpoints.topic.replication.factor:MirrorMaker 内部检查点主题的复制因子(默认值:3)
  • sync.group.offsets.enabled:是否定期将复制的消费组(在源集群中)的翻译偏移量写入__consumer_offsetsTopic,只要该组中没有活动使用者连接到目标集群(默认值:false)
  • sync.group.offsets.interval.seconds:消费者组偏移量同步的频率(默认值:60,每分钟一次)
  • offset-syncs.topic.replication.factor:MirrorMaker 内部偏移同步主题的复制因子(默认值:3)
保护复制流

MirrorMaker 支持与 Kafka Connect 相同的安全设置,因此请参阅链接的部分以了解更多信息。

示例:加密 MirrorMaker 与us-east簇。

us-east.security.protocol=SSL
us-east.ssl.truststore.location=/path/to/truststore.jks
us-east.ssl.truststore.password=my-secret-password
us-east.ssl.keystore.location=/path/to/keystore.jks
us-east.ssl.keystore.password=my-secret-password
us-east.ssl.key.password=my-secret-password
目标集群中复制主题的自定义命名

目标集群中的复制主题(有时称为远程主题)将根据复制策略重命名。MirrorMaker 使用此策略来确保来自不同集群的事件(又名记录、消息)不会写入同一主题分区。默认情况下,根据 DefaultReplicationPolicy,目标集群中复制的主题名称的格式为{source}.{source_topic_name}:

us-west         us-east
=========       =================
                bar-topic
foo-topic  -->  us-west.foo-topic

您可以自定义分隔符(默认:.) 替换为replication.policy.separator设置:

# Defining a custom separator
us-west->us-east.replication.policy.separator = _

如果您需要进一步控制复制主题的命名方式,您可以实现自定义ReplicationPolicy并覆盖replication.policy.class(默认值为DefaultReplicationPolicy) 中的 MirrorMaker 配置。

防止配置冲突

MirrorMaker 进程通过其目标 Kafka 集群共享配置。当针对同一目标群集运行的 MirrorMaker 进程之间的配置不同时,此行为可能会导致冲突。

例如,以下两个 MirrorMaker 进程将是 racy 的:

# Configuration of process 1
A->B.enabled = true
A->B.topics = foo

# Configuration of process 2
A->B.enabled = true
A->B.topics = bar

在这种情况下,两个进程将通过集群共享配置B,这会导致冲突。根据两个进程中的哪一个是当选的 “领导者”,结果将是主题foo或主题bar被复制,但不能同时复制两者。

因此,在流向同一目标群集的复制流中保持 MirrorMaker 配置一致非常重要。例如,这可以通过自动化工具或为整个组织使用单个共享的 MirrorMaker 配置文件来实现。

最佳实践:从远程消费,从农产品到本地

为了最大限度地减少延迟(“生产者滞后”),建议将 MirrorMaker 进程放置在尽可能靠近其目标集群的位置,即它向其生成数据的集群。这是因为 Kafka 生产者通常比 Kafka 使用者更难以处理不可靠或高延迟的网络连接。

First DC          Second DC
==========        =========================
primary --------- MirrorMaker --> secondary
(remote)                           (local)

要运行这种“从远程使用,生产到本地”设置,请在目标集群附近运行MirrorMaker进程,最好在目标集群所在的位置运行,并在--clusters命令行参数(以空格分隔的集群别名列表):

# Run in secondary's data center, reading from the remote `primary` cluster
$ ./bin/connect-mirror-maker.sh connect-mirror-maker.properties --clusters secondary
--clusters secondary告诉 MirrorMaker 进程给定的集群就在附近,并防止它复制数据或将配置发送到其他远程位置的集群。
示例:主动/被动高可用性部署

以下示例显示了将主题从主 Kafka 环境复制到辅助 Kafka 环境的基本设置,而不是从辅助 Kafka 环境复制回主 Kafka 环境的基本设置。请注意,大多数生产设置都需要进一步配置,例如安全设置。

# Unidirectional flow (one-way) from primary to secondary cluster
primary.bootstrap.servers = broker1-primary:9092
secondary.bootstrap.servers = broker2-secondary:9092

primary->secondary.enabled = true
secondary->primary.enabled = false

primary->secondary.topics = foo.*  # only replicate some topics
示例:主动/主动高可用性部署

以下示例显示了以两种方式在两个集群之间复制主题的基本设置。请注意,大多数生产设置都需要进一步配置,例如安全设置。

# Bidirectional flow (two-way) between us-west and us-east clusters
clusters = us-west, us-east
us-west.bootstrap.servers = broker1-west:9092,broker2-west:9092
Us-east.bootstrap.servers = broker3-east:9092,broker4-east:9092

us-west->us-east.enabled = true
us-east->us-west.enabled = true

关于防止复制“循环”的注意事项(其中主题最初将从 A 复制到 B,然后复制的主题将再次从 B 复制到 A,依此类推):只要您在同一个 MirrorMaker 配置文件中定义上述流,就不需要显式添加topics.exclude设置以防止两个集群之间出现复制循环。

示例:多群集异地复制

让我们将前面部分的所有信息放在一个更大的示例中。假设有三个数据中心(西、东、北),每个数据中心有两个 Kafka 集群(例如,west-1,west-2).本节中的示例显示了如何配置 MirrorMaker (1) 在每个数据中心内进行主动/主动复制,以及 (2) 进行跨数据中心复制 (XDCR)。

首先,在配置中定义源集群和目标集群及其复制流:

# Basic settings
clusters: west-1, west-2, east-1, east-2, north-1, north-2
west-1.bootstrap.servers = ...
west-2.bootstrap.servers = ...
east-1.bootstrap.servers = ...
east-2.bootstrap.servers = ...
north-1.bootstrap.servers = ...
north-2.bootstrap.servers = ...

# Replication flows for Active/Active in West DC
west-1->west-2.enabled = true
west-2->west-1.enabled = true

# Replication flows for Active/Active in East DC
east-1->east-2.enabled = true
east-2->east-1.enabled = true

# Replication flows for Active/Active in North DC
north-1->north-2.enabled = true
north-2->north-1.enabled = true

# Replication flows for XDCR via west-1, east-1, north-1
west-1->east-1.enabled  = true
west-1->north-1.enabled = true
east-1->west-1.enabled  = true
east-1->north-1.enabled = true
north-1->west-1.enabled = true
north-1->east-1.enabled = true

然后,在每个数据中心中,启动一个或多个 MirrorMaker,如下所示:

# In West DC:
$ ./bin/connect-mirror-maker.sh connect-mirror-maker.properties --clusters west-1 west-2

# In East DC:
$ ./bin/connect-mirror-maker.sh connect-mirror-maker.properties --clusters east-1 east-2

# In North DC:
$ ./bin/connect-mirror-maker.sh connect-mirror-maker.properties --clusters north-1 north-2

使用此配置,生成到任何集群的记录将在数据中心内复制,并跨其他数据中心复制。通过提供--clusters参数,我们确保每个 MirrorMaker 进程仅向附近的集群生成数据。

注意:--clustersparameter 在这里不需要。没有它,MirrorMaker 会正常工作。但是,吞吐量可能会受到数据中心之间的“生产者滞后”的影响,并且您可能会产生不必要的数据传输成本。

启动异地复制

您可以根据需要运行尽可能少或尽可能多的 MirrorMaker 进程(想想:节点、服务器)。由于 MirrorMaker 基于 Kafka Connect,因此配置为复制相同 Kafka 集群的 MirrorMaker 进程在分布式设置中运行:它们将找到彼此、共享配置(请参阅下面的部分)、对其工作进行负载平衡等。例如,如果要提高复制流的吞吐量,则一个选项是并行运行其他 MirrorMaker 进程。

要启动 MirrorMaker 进程,请运行以下命令:

$ ./bin/connect-mirror-maker.sh connect-mirror-maker.properties

启动后,可能需要几分钟时间,MirrorMaker 进程才会首次开始复制数据。

(可选)如前所述,您可以设置参数--clusters以确保 MirrorMaker 进程仅向附近的集群生成数据。

# Note: The cluster alias us-west must be defined in the configuration file
$ ./bin/connect-mirror-maker.sh connect-mirror-maker.properties \
            --clusters us-west

测试消费组复制时的注意事项:默认情况下,MirrorMaker 不会复制由kafka-console-consumer.sh工具,您可以使用该工具在命令行上测试 MirrorMaker 设置。如果您也想复制这些使用者组,请将groups.exclude配置(默认值:groups.exclude = console-consumer-.*, connect-.*, __.*).请记住在完成测试后再次更新配置。

停止异地复制

您可以通过使用以下命令发送 SIGTERM 信号来停止正在运行的 MirrorMaker 进程:

$ kill <MirrorMaker pid>

应用配置更改

要使配置更改生效,必须重新启动 MirrorMaker 进程。

监视异地复制

建议监控 MirrorMaker 进程,以确保所有定义的复制流都已启动并正确运行。MirrorMaker 基于 Connect 框架构建,并继承了 Connect 的所有指标,例如source-record-poll-rate.此外,MirrorMaker 在kafka.connect.mirrormetric 组。指标使用以下属性进行标记:

  • source:源集群的别名(例如primary)
  • target:目标集群的别名(例如secondary)
  • topic:目标集群上的复制主题
  • partition:正在复制的分区

跟踪每个复制主题的指标。源集群可以从主题名称中推断出来。例如,复制topic1primary->secondary将产生如下指标:

  • target=secondary
  • topic=primary.topic1
  • partition=1

将发出以下指标:

# MBean: kafka.connect.mirror:type=MirrorSourceConnector,target=([-.w]+),topic=([-.w]+),partition=([0-9]+)

record-count            # number of records replicated source -> target
record-age-ms           # age of records when they are replicated
record-age-ms-min
record-age-ms-max
record-age-ms-avg
replication-latency-ms  # time it takes records to propagate source->target
replication-latency-ms-min
replication-latency-ms-max
replication-latency-ms-avg
byte-rate               # average number of bytes/sec in replicated records

# MBean: kafka.connect.mirror:type=MirrorCheckpointConnector,source=([-.w]+),target=([-.w]+)

checkpoint-latency-ms   # time it takes to replicate consumer offsets
checkpoint-latency-ms-min
checkpoint-latency-ms-max
checkpoint-latency-ms-avg

这些指标不区分 created-at 和 log-append 时间戳。

6.4 多租户

多租户概述

作为一个高度可扩展的事件流平台,Kafka 被许多用户用作他们的中枢神经系统,实时连接来自不同团队和业务线的各种不同系统和应用程序。这种多租户集群环境需要适当的控制和管理,以确保这些不同需求和平共存。本节重点介绍设置此类共享环境的功能和最佳实践,这些环境应该可以帮助您运行满足 SLA/OLA 的集群,并最大限度地减少“嘈杂邻居”造成的潜在附带损害。

多租户是一个多方面的主题,包括但不限于:

  • 为租户创建用户空间(有时称为命名空间)
  • 使用数据保留策略等配置主题
  • 通过加密、身份验证和授权保护主题和集群
  • 使用配额和速率限制隔离租户
  • 监控和计量
  • 集群间数据共享(参见异地复制)

使用 Topic 命名为 Tenants 创建用户空间(命名空间)

运行多租户集群的 Kafka 管理员通常需要为每个租户定义用户空间。在本部分中,“用户空间”是主题的集合,这些主题在单个实体或用户的管理下分组在一起。

在 Kafka 中,数据的主要单位是主题。用户可以创建和命名每个主题。他们也可以删除它们,但无法直接重命名主题。相反,要重命名主题,用户必须创建一个新主题,将消息从原始主题移动到新主题,然后删除原始主题。考虑到这一点,建议根据分层主题命名结构定义逻辑空间。然后,可以将此设置与安全功能(例如带前缀的 ACL)结合使用,以隔离不同的空间和租户,同时还可以最大限度地减少保护集群中数据的管理开销。

这些逻辑用户空间可以以不同的方式进行分组,具体选择取决于您的组织喜欢如何使用 Kafka 集群。最常见的分组如下。

按团队或组织单位:在这里,团队是主要的聚合器。在团队是 Kafka 基础架构的主要用户的组织中,这可能是最佳分组。

主题命名结构示例:

  • <organization>.<team>.<dataset>.<event-name>
    (例如,“acme.infosec.telemetry.logins”)

按项目或产品:在这里,一个团队管理多个项目。每个项目的凭据都不同,因此所有控件和设置将始终与项目相关。

主题命名结构示例:

  • <project>.<product>.<event-name>
    (例如,“mobility.payments.suspicious”)

某些信息通常不应放在主题名称中,例如可能会随时间变化的信息(例如,目标使用者的名称)或其他地方可用的技术细节或元数据(例如,主题的分区计数和其他配置设置)。

要强制实施主题命名结构,可以使用以下几个选项:

  • 使用前缀 ACL(参见 KIP-290)为主题名称强制实施通用前缀。例如,团队 A 可能只被允许创建名称以payments.teamA..
  • 定义自定义CreateTopicPolicy(参见 KIP-108 和设置 create.topic.policy.class.name)来强制实施严格的命名模式。这些策略提供了最大的灵活性,并且可以涵盖复杂的模式和规则以满足组织的需求。
  • 通过使用 ACL 拒绝为普通用户禁用主题创建,然后依靠外部进程代表用户创建主题(例如,脚本或您最喜欢的自动化工具包)。
  • 禁用 Kafka 功能以按需自动创建主题也可能很有用,方法是将auto.create.topics.enable=false在 Broker 配置中。请注意,您不应仅依赖此选项。

配置主题:数据保留等

Kafka 的配置由于其细粒度而非常灵活,并且它支持大量的每个主题的配置设置,以帮助管理员设置多租户集群。例如,管理员通常需要定义数据保留策略,以控制主题中存储的数据量和/或存储时间,包括 retention.bytes(大小)和 retention.ms(time)等设置。这限制了集群内的存储消耗,并有助于遵守 GDPR 等法律要求。

保护集群和主题:身份验证、授权、加密

由于该文档有一章专门介绍适用于任何 Kafka 部署的安全性,因此本节重点介绍多租户环境的其他注意事项。

Kafka 的安全设置分为三大类,类似于管理员保护其他客户端-服务器数据系统(如关系数据库和传统消息传递系统)的方式。

  1. 对 Kafka 代理和 Kafka 客户端之间、代理之间、代理和 ZooKeeper 节点之间以及代理和其他可选工具之间传输的数据进行加密
  2. 从 Kafka 客户端和应用程序到 Kafka 代理的连接,以及从 Kafka 代理到 ZooKeeper 节点的连接进行身份验证。
  3. 授权客户端作,例如创建、删除和更改主题的配置;将事件写入主题或从主题读取事件;创建和删除 ACL。管理员还可以定义自定义策略以实施其他限制,例如CreateTopicPolicyAlterConfigPolicy(请参阅 KIP-108 和设置 create.topic.policy.class.namealter.config.policy.class.name)。

在保护多租户 Kafka 环境时,最常见的管理任务是第三类(授权),即管理用户/客户端权限,这些权限授予或拒绝对某些主题的访问,从而授予或拒绝对集群中用户存储的数据的访问。此任务主要通过设置访问控制列表 (ACL) 来执行。在这里,多租户环境的管理员尤其受益于上一节所述的分层主题命名结构,因为他们可以通过带前缀的 ACL (--resource-pattern-type Prefixed).这大大减少了在多租户环境中保护主题的管理开销:管理员可以在更高的开发人员便利性(更宽松的权限、使用更少和更广泛的 ACL)和更严格的安全性(更严格的权限、使用更多和更窄的 ACL)之间做出权衡。

在以下示例中,用户 Alice(ACME 公司 InfoSec 团队的新成员)被授予对名称以“acme.infosec.”开头的所有主题的写入权限,例如“acme.infosec.telemetry.logins”和“acme.infosec.syslogs.events”。

# Grant permissions to user Alice
$ bin/kafka-acls.sh \
    --bootstrap-server broker1:9092 \
    --add --allow-principal User:Alice \
    --producer \
    --resource-pattern-type prefixed --topic acme.infosec.

同样,您可以使用此方法将不同客户隔离在同一个共享集群上。

隔离租户:配额、速率限制、限制

多租户集群通常应配置配额,以防止用户(租户)占用过多的集群资源,例如,当他们尝试写入或读取非常大量的数据时,或者以过高的速率向代理创建请求时。这可能会导致网络饱和、垄断代理资源并影响其他客户端 — 所有这些都是您希望在共享环境中避免的。

客户端配额:Kafka 支持不同类型的 (每用户主体) 客户端配额。由于无论客户端写入或读取哪个主题,客户端的配额都适用,因此它们是在多租户集群中分配资源的便捷有效的工具。例如,请求速率配额通过限制代理在该用户的请求处理路径上花费的时间来帮助限制用户对代理 CPU 使用率的影响,之后将开始限制。在许多情况下,在多租户集群中,使用请求速率配额隔离用户比设置传入/传出网络带宽配额的影响更大,因为处理请求时代理 CPU 使用率过高会减少代理可以提供的有效带宽。此外,管理员还可以定义主题作(例如 create、delete 和 alter)的配额,以防止 Kafka 集群被高度并发的主题作淹没(请参阅 KIP-599 和配额类型controller_mutation_rate).

服务器配额:Kafka 还支持不同类型的代理端配额。例如,管理员可以设置代理接受新连接的速率限制,设置每个代理的最大连接数,或设置允许来自特定 IP 地址的最大连接数。

有关更多信息,请参阅配额概述如何设置配额

监控和计量

监控是一个更广泛的主题,在文档的其他部分进行了介绍。任何 Kafka 环境(尤其是多租户环境)的管理员都应根据这些说明设置监控。Kafka 支持广泛的指标,例如身份验证尝试失败率、请求延迟、使用者滞后、使用者组总数、上一节中描述的配额指标等等。

例如,可以将监控配置为跟踪主题分区的大小(使用 JMX 指标kafka.log.Log.Size.<TOPIC-NAME>),从而计算主题中存储的数据的总大小。然后,您可以定义当共享集群上的租户即将使用过多存储空间时发出警报。

多租户和异地复制

Kafka 允许您在不同的集群之间共享数据,这些集群可能位于不同的地理区域、数据中心等。除了灾难恢复等使用案例外,当多租户设置需要集群间数据共享时,此功能也很有用。有关更多信息,请参阅异地复制(跨集群数据镜像)部分。

进一步的考虑

数据协定:您可能需要使用事件架构在集群中数据的创建者和使用者之间定义数据协定。这可确保始终可以再次正确读取写入 Kafka 的事件,并防止写入格式错误或损坏的事件。实现此目的的最佳方法是在集群旁边部署一个所谓的 schema registry。(Kafka 不包含架构注册表,但有可用的第三方实现。架构注册表管理事件架构并将架构映射到主题,以便创建者知道哪些主题正在接受哪些类型的事件(架构),并且使用者知道如何读取和解析主题中的事件。某些注册表实现提供更多功能,例如架构演变、存储所有架构的历史记录以及架构兼容性设置。

6.5 Kafka 配置

重要的客户端配置

最重要的生产者配置是:
  • ACK 系列
  • 压缩
  • 批量大小
最重要的 consumer 配置是 fetch size。

所有配置都记录在 configuration 部分。

生产服务器配置

下面是一个生产服务器配置示例:我们的客户端配置在不同用例之间有相当大的差异。
  # ZooKeeper
  zookeeper.connect=[list of ZooKeeper servers]

  # Log configuration
  num.partitions=8
  default.replication.factor=3
  log.dir=[List of directories. Kafka should have its own dedicated disk(s) or SSD(s).]

  # Other configurations
  broker.id=[An integer. Start with 0 and increment by 1 for each new broker.]
  listeners=[list of listeners]
  auto.create.topics.enable=false
  min.insync.replicas=2
  queued.max.requests=[number of concurrent requests]

6.6 Java 版本

支持 Java 8、Java 11 和 Java 17。请注意,Java 8 支持自 Apache Kafka 3.0 起已弃用,并将在 Apache Kafka 4.0 中删除。 如果启用了 TLS,Java 11 及更高版本的性能会明显更好,因此强烈建议使用它们(它们还包括许多其他 性能改进:G1GC、CRC32C、Compact Strings、Thread-Local Handshakes 等)。 从安全角度来看,我们建议使用最新发布的补丁版本,因为较旧的免费版本已披露安全漏洞。 使用基于 OpenJDK 的 Java 实现(包括 Oracle JDK)运行 Kafka 的典型参数是:作为参考,以下是使用上述 Java 参数的 LinkedIn 最繁忙的集群之一(高峰期)的统计数据:
  -Xmx6g -Xms6g -XX:MetaspaceSize=96m -XX:+UseG1GC
  -XX:MaxGCPauseMillis=20 -XX:InitiatingHeapOccupancyPercent=35 -XX:G1HeapRegionSize=16M
  -XX:MinMetaspaceFreeRatio=50 -XX:MaxMetaspaceFreeRatio=80 -XX:+ExplicitGCInvokesConcurrent
  • 60 个经纪人
  • 50k 个分区(复制因子 2)
  • 800k 消息/秒
  • 300 MB/秒入站,1 GB/秒 + 出站
该集群中的所有代理都有 90% 的 GC 暂停时间,约为 21 毫秒,每秒不到 1 个年轻的 GC。

6.7 硬件和作系统

我们使用的是具有 24GB 内存的双四核 Intel Xeon 计算机。

您需要足够的内存来缓冲活动的读取器和写入器。您可以对内存需求进行粗略估计,方法是假设您希望能够缓冲 30 秒,并将内存需求计算为 write_throughput*30。

磁盘吞吐量很重要。我们有 8x7200 rpm SATA 驱动器。一般来说,磁盘吞吐量是性能瓶颈,磁盘越多越好。根据您配置刷新行为的方式,您可能会也可能不会从更昂贵的磁盘中受益(如果您经常强制刷新,则 RPM 较高的 SAS 驱动器可能会更好)。

操作系统

Kafka 应该可以在任何 unix 系统上运行良好,并且已经在 Linux 和 Solaris 上进行了测试。

我们已经看到在 Windows 上运行时存在一些问题,而 Windows 目前不是一个得到良好支持的平台,但我们很乐意改变这种情况。

它不太可能需要太多的 OS 级调整,但有三种可能重要的 OS 级配置:

  • 文件描述符限制:Kafka 对日志段和打开的连接使用文件描述符。如果代理托管许多分区,则除了代理建立的连接数外,请考虑代理至少需要 (number_of_partitions)*(partition_size/segment_size) 来跟踪所有日志段。我们建议代理进程至少允许 100000 个文件描述符作为起点。注: mmap() 函数会添加一个额外的引用,该引用将与文件描述符 fildes 相关联,该文件描述符上的后续 close() 不会删除该引用。当没有更多到文件的映射时,将删除此引用。
  • 最大套接字缓冲区大小:可以增加以实现数据中心之间的高性能数据传输,如此处所述
  • 进程可以具有的最大内存映射区域数(也称为 vm.max_map_count)。请参阅 Linux 内核文档。在考虑 broker 可能具有的最大分区数时,您应该密切关注此 OS 级属性。默认情况下,在许多 Linux 系统上,vm.max_map_count 的值大约在 65535 左右。每个 log segment(按分区分配)需要一对 index/timeindex 文件,每个文件占用 1 个 map 区域。换句话说,每个日志段使用 2 个地图区域。因此,每个分区至少需要 2 个 map 区域,只要它托管一个日志段即可。也就是说,在代理上创建 50000 个分区将导致分配 100000 个映射区域,并可能导致代理崩溃,并在默认为 vm.max_map_count 的系统上出现 OutOfMemoryError(映射失败)。请记住,每个分区的日志段数因段大小、负载强度、保留策略而异,并且通常往往不止一个。

磁盘和文件系统

我们建议使用多个驱动器以获得良好的吞吐量,并且不要将用于 Kafka 数据的相同驱动器与应用程序日志或其他作系统文件系统活动共享,以确保良好的延迟。您可以将这些驱动器一起 RAID 到一个卷中,也可以将每个驱动器格式化并挂载为自己的目录。由于 Kafka 具有复制功能,因此 RAID 提供的冗余也可以在应用程序级别提供。此选择有几个权衡。

如果配置多个数据目录,则分区将按循环方式分配给数据目录。每个分区将完全位于其中一个数据目录中。如果数据在分区之间没有很好地平衡,这可能会导致磁盘之间的负载不平衡。

RAID 在平衡磁盘之间的负载方面可能做得更好(尽管它似乎并不总是这样),因为它在较低级别平衡负载。RAID 的主要缺点是它通常会对写入吞吐量造成很大的性能影响,并会减少可用磁盘空间。

RAID 的另一个潜在好处是能够容忍磁盘故障。然而,我们的经验是,重建 RAID 阵列是如此密集的 I/O ,以至于它实际上会禁用服务器,因此这并没有提供太多真正的可用性改进。

应用程序与作系统刷新管理

Kafka 始终立即将所有数据写入文件系统,并支持配置 flush 策略的功能,该策略控制何时使用 flush 将数据从作系统缓存中强制出并放到磁盘上。可以控制此 flush 策略,以在一段时间后或写入一定数量的消息后强制数据到磁盘。此配置中有多种选择。

Kafka 最终必须调用 fsync 才能知道数据已刷新。当从任何未知为 fsync 的日志段的崩溃中恢复时,Kafka 将通过检查其 CRC 来检查每条消息的完整性,并在启动时执行的恢复过程中重建随附的偏移索引文件。

请注意,Kafka 中的持久性不需要将数据同步到磁盘,因为故障节点将始终从其副本中恢复。

我们建议使用完全禁用应用程序 fsync 的默认 flush 设置。这意味着依赖于 OS 完成的后台 flush 和 Kafka 自己的后台 flush。这为大多数用途提供了最好的功能:无需调整旋钮、出色的吞吐量和延迟以及完整的恢复保证。我们通常认为复制提供的保证比同步到本地磁盘更强大,但是偏执狂可能仍然更喜欢两者兼而有之,并且仍然支持应用程序级别的 fsync 策略。

使用应用程序级 flush 设置的缺点是,它的磁盘使用模式效率较低(它给 OS 重新排序写入的余地较小),并且它可能会引入延迟,因为大多数 Linux 文件系统中的 fsync 会阻止对文件的写入,而后台 flush 会执行更精细的页面级锁定。

一般来说,你不需要对文件系统进行任何低级的调整,但在接下来的几节中,我们将介绍其中的一些内容,以防它有用。

了解 Linux OS 刷新行为

在 Linux 中,写入文件系统的数据将保留在页面缓存中,直到必须将其写出到磁盘(由于应用程序级 fsync 或作系统自己的 flush 策略)。数据的刷新由一组称为 pdflush 的后台线程完成(或在 2.6.32 之后的内核中称为“刷新线程”)。

Pdflush 有一个可配置的策略,该策略控制缓存中可以保留多少脏数据,以及必须将其写回磁盘之前保留多长时间。 此处介绍了此策略。 当 Pdflush 无法跟上写入数据的速度时,它最终会导致写入过程阻塞,从而在写入中产生延迟,从而减慢数据的积累。

您可以通过执行

 > cat /proc/meminfo 
这些值的含义在上面的链接中进行了描述。

与进程内高速缓存相比,使用 pagecache 存储将要写入磁盘的数据具有几个优点:

  • I/O 计划程序会将连续的小写入批处理到较大的物理写入中,从而提高吞吐量。
  • I/O 计划程序将尝试对写入重新排序,以最大限度地减少磁盘头的移动,从而提高吞吐量。
  • 它会自动使用计算机上的所有可用内存

文件系统选择

Kafka 使用磁盘上的常规文件,因此它对特定文件系统没有硬性依赖性。但是,使用率最高的两个文件系统是 EXT4 和 XFS。从历史上看,EXT4 的使用量更大,但最近对 XFS 文件系统的改进表明,它对 Kafka 的工作负载具有更好的性能特征,而不会影响稳定性。

使用各种文件系统创建和挂载选项,在具有大量消息负载的集群上执行比较测试。Kafka 中受监控的主要指标是“请求本地时间”,表示追加作所花费的时间。XFS 带来了更好的本地时间(160 毫秒,而最佳 EXT4 配置为 250 毫秒+),以及更短的平均等待时间。XFS 性能还显示磁盘性能的可变性较小。

一般文件系统说明
对于用于数据目录的任何文件系统,在 Linux 系统上,建议在挂载时使用以下选项:
  • noatime:此选项在读取文件时禁用文件的 atime(上次访问时间)属性的更新。这可以消除大量的文件系统写入,尤其是在引导使用者的情况下。Kafka 根本不依赖 atime 属性,因此禁用此功能是安全的。
XFS 笔记
XFS 文件系统具有大量的自动调整功能,因此无论是在创建文件系统时还是在挂载时,都不需要对默认设置进行任何更改。唯一值得考虑的优化参数是:
  • largeio:这会影响 stat 调用报告的首选 I/O 大小。虽然这可以在较大的磁盘写入上实现更高的性能,但实际上它对性能的影响很小或没有影响。
  • nobarrier:对于具有电池供电缓存的底层设备,此选项可以通过禁用定期写入刷新来提供更高的性能。但是,如果底层设备运行良好,它将向文件系统报告它不需要 flush,并且此选项将不起作用。
EXT4 注释
EXT4 是 Kafka 数据目录的文件系统的可用选择,但是要充分利用它,需要调整多个挂载选项。此外,这些选项在故障情况下通常是不安全的,并且会导致更多的数据丢失和损坏。对于单个代理故障,这并不是什么大问题,因为可以擦除磁盘并从集群重建副本。在多次故障的情况下,例如停电,这可能意味着底层文件系统(以及数据)损坏,不容易恢复。可以调整以下选项:
  • data=writeback:Ext4 默认为 data=ordered,这对某些写入有很强的排序。Kafka 不需要这种排序,因为它对所有未刷新的日志进行非常偏执的数据恢复。此设置消除了排序约束,并且似乎显著降低了延迟。
  • 禁用日记功能:日记功能是一种权衡:它可以在服务器崩溃后更快地重启,但它引入了大量额外的锁定,这增加了写入性能的差异。那些不关心重启时间并希望减少写入延迟峰值的主要来源的人可以完全关闭日志功能。
  • commit=num_secs:这将调整 ext4 提交到其元数据日志的频率。将此值设置为较低的值可以减少崩溃期间未刷新数据的丢失。将此值设置为较高的值将提高吞吐量。
  • nobh:此设置控制使用 data=writeback 模式时的其他 Sequences 保证。这对于 Kafka 来说应该是安全的,因为我们不依赖于写入顺序,并且提高了吞吐量和延迟。
  • delalloc:延迟分配意味着文件系统在物理写入发生之前避免分配任何块。这允许 ext4 分配较大的范围而不是较小的页面,并有助于确保按顺序写入数据。此功能非常适合吞吐量。它似乎确实涉及文件系统中的一些锁定,这增加了一些延迟变化。

更换 KRaft 控制器磁盘

当 Kafka 配置为使用 KRaft 时,控制器将集群元数据存储在metadata.log.dir-- 或第一个日志目录,如果metadata.log.dir未配置。请参阅以下文档metadata.log.dir了解详情。

如果 cluster metdata 目录中的数据由于硬件故障或需要更换硬件而丢失,则在配置新的 controller 节点时应小心。在大多数控制器具有所有提交的数据之前,不应格式化和启动新的 controller 节点。要确定大多数控制器是否具有提交的数据,请运行kafka-metadata-quorum.sh工具来描述复制状态:

 > bin/kafka-metadata-quorum.sh --bootstrap-server broker_host:port describe --replication
 NodeId  LogEndOffset    Lag     LastFetchTimestamp      LastCaughtUpTimestamp   Status
 1       25806           0       1662500992757           1662500992757           Leader
 ...     ...             ...     ...                     ...                     ...
  

检查并等待Lag对于大多数控制器来说都很小。如果导引的末端偏移量没有增加,则可以等到多数的滞后为 0;否则,您可以选择最新的 leader end offset 并等待所有副本都到达它。检查并等待LastFetchTimestampLastCaughtUpTimestamp对于大多数控制器来说,它们彼此靠近。此时,格式化控制器的元数据日志目录会更安全。这可以通过运行kafka-storage.sh命令。

 > bin/kafka-storage.sh format --cluster-id uuid --config server_properties

对于bin/kafka-storage.sh format命令失败,并显示类似Log directory ... is already formatted.当使用组合模式并且仅丢失元数据日志目录而其他目录未丢失时,可能会发生这种情况。在这种情况下,您才能运行kafka-storage.sh format命令与--ignore-formatted选择。

格式化日志目录后启动 KRaft 控制器。

 > /bin/kafka-server-start.sh server_properties

6.8 监控

Kafka 使用 Yammer Metrics 在服务器中报告指标。Java 客户端使用 Kafka Metrics,这是一个内置的指标注册表,可最大限度地减少提取到客户端应用程序中的传递依赖项。两者都通过 JMX 公开指标,并且可以配置为使用可插拔的统计报告器来报告统计数据,以连接到您的监控系统。

所有 Kafka 速率指标都有相应的 Cumulative count 指标,后缀为-total.例如records-consumed-rate具有相应的名为records-consumed-total.

查看可用指标的最简单方法是启动 jconsole 并将其指向正在运行的 kafka 客户端或服务器;这将允许使用 JMX 浏览所有指标。

使用 JMX 进行远程监控的安全注意事项

Apache Kafka 默认禁用远程 JMX。您可以通过设置环境变量JMX_PORT对于使用 CLI 或标准 Java 系统属性启动的进程,以编程方式启用远程 JMX。 在生产场景下开启远程 JMX 时,必须开启安全性,以确保未经授权的用户无法监控或 控制您的代理或应用程序以及运行它们的平台。请注意,对 默认情况下,Kafka 和安全配置必须通过设置环境变量来覆盖生产部署的安全配置KAFKA_JMX_OPTS对于使用 CLI 或通过设置适当的 Java 系统属性启动的进程。有关保护 JMX 的详细信息,请参阅使用 JMX 技术进行监控和管理

我们对以下指标进行绘图和警报:

描述 Mbean 名称 正常值
消息输入率 kafka.server:type=BrokerTopicMetrics,name=MessagesInPerSec,topic=([-.\w]+) 每个主题的传入消息速率。省略 'topic=(...)' 将产生全主题速率。
来自客户端的字节传入速率 kafka.server:type=BrokerTopicMetrics,name=BytesInPerSec,topic=([-.\w]+) 每个主题的字节输入(来自客户端)速率。省略 'topic=(...)' 将产生全主题速率。
来自其他经纪商的字节输入速率 kafka.server:type=BrokerTopicMetrics,name=ReplicationBytesInPerSec,topic=([-.\w]+) 每个主题的字节输入(来自其他代理)费率。省略 'topic=(...)' 将产生全主题速率。
来自 Broker 的 Controller Request rate kafka.controller:type=ControllerChannelManager,name=RequestRateAndQueueTimeMs,brokerId=([0-9]+) ControllerChannelManager 从 queue 的 broker 中。以及请求在此之前保持在此队列中所需的时间 它是从队列中获取的。
控制器事件队列大小 kafka.controller:type=ControllerEventManager,name=EventQueueSize ControllerEventManager 队列的大小。
控制器事件队列时间 kafka.controller:type=ControllerEventManager,name=EventQueueTimeMs 任何事件(Idle 事件除外)在 ControllerEventManager 的 queue before being processed
请求速率 kafka.network:type=RequestMetrics,name=RequestsPerSec,request={Produce|FetchConsumer|FetchFollower},版本=([0-9]+)
错误率 kafka.network:type=RequestMetrics,name=ErrorsPerSec,request=([-.\w]+),error=([-.\w]+) 按请求类型、每个错误代码计数的响应中的错误数。如果响应包含 多个错误,所有错误都被计算在内。error=NONE 表示响应成功。
产品请求率 kafka.server:type=BrokerTopicMetrics,name=TotalProduceRequestsPerSec,topic=([-.\w]+) 每个主题的生成请求速率。省略 'topic=(...)' 将产生全主题速率。
Fetch 请求速率 kafka.server:type=BrokerTopicMetrics,name=TotalFetchRequestsPerSec,topic=([-.\w]+) 每个主题的 Fetch request(来自客户或关注者)费率。省略 'topic=(...)' 将产生全主题速率。
失败的农产品请求率 kafka.server:type=BrokerTopicMetrics,name=FailedProduceRequestsPerSec,topic=([-.\w]+) 失败 每个主题的 Produce 请求速率。省略 'topic=(...)' 将产生全主题速率。
失败的获取请求速率 kafka.server:type=BrokerTopicMetrics,name=FailedFetchRequestsPerSec,topic=([-.\w]+) 每个主题的 Fetch 请求失败率(来自客户端或关注者)。省略 'topic=(...)' 将产生全主题速率。
请求大小(以字节为单位) kafka.network:type=RequestMetrics,name=RequestBytes,request=([-.\w]+) 每种请求类型的请求大小。
临时内存大小(以字节为单位) kafka.network:type=RequestMetrics,name=TemporaryMemoryBytes,request={Produce|获取} 用于消息格式转换和解压缩的临时内存。
消息转换时间 kafka.network:type=RequestMetrics,name=MessageConversionsTimeMs,request={Produce|获取} 消息格式转换所花费的时间(以毫秒为单位)。
消息转化率 kafka.server:type=BrokerTopicMetrics,name={生产|Fetch}MessageConversionsPerSec,topic=([-.\w]+) 每个主题的 Produce 或 Fetch 请求的消息格式转换率。省略 'topic=(...)' 将产生全主题速率。
请求队列大小 kafka.network:type=RequestChannel,name=RequestQueueSize 请求队列的大小。
客户端的字节输出速率 kafka.server:type=BrokerTopicMetrics,name=BytesOutPerSec,topic=([-.\w]+) 每个主题的字节输出(到客户端)速率。省略 'topic=(...)' 将产生全主题速率。
向其他代理发送字节输出速率 kafka.server:type=BrokerTopicMetrics,name=ReplicationBytesOutPerSec,topic=([-.\w]+) 每个主题的 Byte out(到其他 broker)速率。省略 'topic=(...)' 将产生全主题速率。
被拒绝的字节率 kafka.server:type=BrokerTopicMetrics,name=BytesRejectedPerSec,topic=([-.\w]+) 由于记录批处理大小大于 max.message.bytes 配置,每个主题的字节率被拒绝。省略 'topic=(...)' 将产生全主题速率。
由于没有为压缩主题指定 key 而导致的消息验证失败率 kafka.server:type=BrokerTopicMetrics,name=NoKeyCompactedTopicRecordsPerSec 0
由于幻数无效而导致的消息验证失败率 kafka.server:type=BrokerTopicMetrics,name=InvalidMagicNumberRecordsPerSec 0
由于 crc 校验和不正确而导致的消息验证失败率 kafka.server:type=BrokerTopicMetrics,name=InvalidMessageCrcRecordsPerSec 0
由于批量中的非连续偏移量或序列号而导致的消息验证失败率 kafka.server:type=BrokerTopicMetrics,name=InvalidOffsetOrSequenceRecordsPerSec 0
日志刷新率和时间 kafka.log:type=LogFlushStats,name=LogFlushRateAndTimeMs
# 离线日志目录 kafka.log:type=LogManager,name=OfflineLogDirectoryCount 0
领导选举率 kafka.controller:type=ControllerStats,name=LeaderElectionRateAndTimeMs 当存在 Broker 故障时为非零
不洁的领导人选举率 kafka.controller:type=ControllerStats,name=UncleanLeaderElectionsPerSec 0
控制器在 broker 上处于活动状态 kafka.controller:type=KafkaController,name=ActiveControllerCount 群集中只有一个代理应具有 1
待处理的主题删除 kafka.controller:type=KafkaController,name=TopicsToDeleteCount
待处理副本删除 kafka.controller:type=KafkaController,name=ReplicasToDeleteCount
不合格的待处理主题删除 kafka.controller:type=KafkaController,name=TopicsIneligibleToDeleteCount
不合格的待处理副本删除 kafka.controller:type=KafkaController,name=ReplicasIneligibleToDeleteCount
# 个复制的分区数 (|ISR|< 所有副本 kafka.server:type=ReplicaManager,name=UnderReplicatedPartitions 0
# of under minIsr 分区 (|ISR|< min.insync.replicas) kafka.server:type=ReplicaManager,name=UnderMinIsrPartitionCount 0
# of at minIsr 分区 (|ISR|= min.insync.replicas) kafka.server:type=ReplicaManager,name=AtMinIsrPartitionCount 0
生产者 ID 计数 kafka.server:type=ReplicaManager,name=ProducerIdCount 代理上每个副本中事务性和幂等生产者创建的所有生产者 ID 的计数
分区计数 kafka.server:type=ReplicaManager,name=PartitionCount 大多数经纪商
离线副本计数 kafka.server:type=ReplicaManager,name=OfflineReplicaCount 0
Leader 副本计数 kafka.server:type=ReplicaManager,name=LeaderCount 大多数经纪商
ISR 收缩率 kafka.server:type=ReplicaManager,name=IsrShrinksPerSec 如果代理宕机,某些分区的 ISR 将 收缩。当该代理再次启动时,ISR 将扩展 一旦副本完全赶上。除此之外, ISR 收缩率和扩展率的预期值为 0。
ISR 扩展率 kafka.server:type=ReplicaManager,name=IsrExpandsPerSec 见上文
失败的 ISR 更新速率 kafka.server:type=ReplicaManager,name=FailedIsrUpdatesPerSec 0
消息中的最大滞后时间 btw follower 和 leader 副本 kafka.server:type=ReplicaFetcherManager,name=MaxLag,clientId=Replica LAG 应与 produce 请求的最大批量大小成正比。
每个关注者副本的消息滞后 kafka.server:type=FetcherLagMetrics,name=ConsumerLag,clientId=([-.\w]+),topic=([-.\w]+),partition=([0-9]+) LAG 应与 produce 请求的最大批量大小成正比。
在生产者炼狱中等待的请求 kafka.server:type=DelayedOperationPurgatory,name=PurgatorySize,delayedOperation=Produce 如果使用 ack=-1,则为非零
在 fetch 炼狱中等待的请求 kafka.server:type=DelayedOperationPurgatory,name=PurgatorySize,delayedOperation=Fetch 大小取决于使用者中的 fetch.wait.max.ms
请求总时间 kafka.network:type=RequestMetrics,name=TotalTimeMs,request={Produce|FetchConsumer|FetchFollower} 分为队列、本地、远程和响应发送时间
请求在请求队列中等待的时间 kafka.network:type=RequestMetrics,name=RequestQueueTimeMs,request={Produce|FetchConsumer|FetchFollower}
在 leader 处处理请求的时间 kafka.network:type=RequestMetrics,name=LocalTimeMs,request={Produce|FetchConsumer|FetchFollower}
请求等待 follower 的时间 kafka.network:type=RequestMetrics,name=RemoteTimeMs,request={Produce|FetchConsumer|FetchFollower} 当 ack=-1 时,produce 请求为非零
请求在响应队列中等待的时间 kafka.network:type=RequestMetrics,name=ResponseQueueTimeMs,request={Produce|FetchConsumer|FetchFollower}
发送响应的时间 kafka.network:type=RequestMetrics,name=ResponseSendTimeMs,request={Produce|FetchConsumer|FetchFollower}
使用者落后于生成者的消息数。由使用者发布,而不是代理发布。 kafka.consumer:type=consumer-fetch-manager-metrics,client-id={client-id} 属性:records-lag-max
网络处理器空闲的平均时间分数 kafka.network:type=SocketServer,name=NetworkProcessorAvgIdlePercent 介于 0 和 1 之间,理想情况下> 0.3
由于客户端未重新验证,然后在过期时间之后将连接用于除重新验证以外的任何作而在处理器上断开连接的连接数 kafka.server:type=socket-server-metrics,listener=[SASL_PLAINTEXT|SASL_SSL],networkProcessor=<#>,name=expired-connections-killed-count 理想情况下,当启用重新身份验证时为 0,这意味着不再有任何较旧的 2.2.0 之前的客户端连接到此(侦听器、处理器)组合
由于客户端未重新验证,然后在过期时间之后将连接用于除重新验证以外的任何作而在所有处理器中断开连接的连接总数 kafka.network:type=SocketServer,name=ExpiredConnectionsKilledCount 理想情况下,当启用重新身份验证时为 0,这意味着不再有任何较旧的 2.2.0 之前的客户端连接到此代理
请求处理程序线程空闲的平均时间分数 kafka.server:type=KafkaRequestHandlerPool,name=RequestHandlerAvgIdlePercent 介于 0 和 1 之间,理想情况下> 0.3
每个 (user, client-id)、user 或 client-id 的带宽配额指标 kafka.server:type={生产|获取},user=([-.\w]+),client-id=([-.\w]+) 两个属性。throttle-time 指示客户端受到限制的时间量(以毫秒为单位)。理想情况下 = 0。 byte-rate 表示客户端的数据生成/消耗速率(以字节/秒为单位)。 对于 (user, client-id) 配额,同时指定了 user 和 client-id。如果将 per-client-id 配额应用于客户端,则不会指定 user。如果应用了每用户配额,则不指定 client-id。
每个 (user, client-id)、user 或 client-id 的请求配额指标 kafka.server:type=Request,user=([-.\w]+),client-id=([-.\w]+) 两个属性。throttle-time 指示客户端受到限制的时间量(以毫秒为单位)。理想情况下 = 0。 request-time 表示在 broker 网络和 I/O 线程中处理来自客户端组的请求所花费的时间百分比。 对于 (user, client-id) 配额,同时指定了 user 和 client-id。如果将 per-client-id 配额应用于客户端,则不会指定 user。如果应用了每用户配额,则不指定 client-id。
免于限制的请求 kafka.server:type=请求 exempt-throttle-time 表示 broker 网络和 I/O 线程处理请求所花费的时间百分比 不受限制。
ZooKeeper 客户端请求延迟 kafka.server:type=ZooKeeperClientMetrics,name=ZooKeeperRequestLatencyMs 来自代理的 ZooKeeper 请求的延迟(以毫秒为单位)。
ZooKeeper 连接状态 kafka.server:type=SessionExpireListener,name=SessionState 代理的 ZooKeeper 会话的连接状态,可能是以下之一 已断开连接 |SyncConnected|AuthFailed|ConnectedReadOnly|SaslAuthenticated|过期。
加载组元数据的最大时间 kafka.server:type=group-coordinator-metrics,name=partition-load-time-max 在过去 30 秒内加载的使用者偏移分区中加载偏移量和组元数据所用的最长时间(以毫秒为单位)(包括等待计划加载任务所花费的时间)
加载组元数据的平均时间 kafka.server:type=group-coordinator-metrics,name=partition-load-time-avg 在过去 30 秒内加载的使用者偏移分区中加载偏移量和组元数据所花费的平均时间(以毫秒为单位)(包括等待计划加载任务所花费的时间)
加载事务元数据的最大时间 kafka.server:type=transaction-coordinator-metrics,name=partition-load-time-max 从过去 30 秒内加载的使用者偏移分区加载事务元数据所花费的最长时间(以毫秒为单位)(包括等待计划加载任务所花费的时间)
加载交易元数据的平均时间 kafka.server:类型=事务协调器指标,名称=分区加载时间-avg 从过去 30 秒内加载的使用者偏移分区加载事务元数据所花费的平均时间(以毫秒为单位)(包括等待计划加载任务所花费的时间)
Consumer Group 偏移计数 kafka.server:type=GroupMetadataManager,name=NumOffsets 使用者组的已提交偏移量总数
使用者组计数 kafka.server:type=GroupMetadataManager,name=NumGroups 消费组总数
每个状态的使用者组计数 kafka.server:type=GroupMetadataManager,name=NumGroups[PreparingRebalance,CompletingRebalance,Empty,Stable,Dead] 每种状态下的 Consumer Group 数量:PreparingRebalance、CompletingRebalance、Empty、Stable、Dead
重新分配分区的数量 kafka.server:type=ReplicaManager,name=重新分配分区 代理上重新分配领导分区的数量。
重新分配流量的传出字节速率 kafka.server:type=BrokerTopicMetrics,name=ReassignmentBytesOutPerSec 0;当分区重新分配正在进行时,为非零。
重新分配流量的传入字节速率 kafka.server:type=BrokerTopicMetrics,name=ReassignmentBytesInPerSec 0;当分区重新分配正在进行时,为非零。
磁盘上分区的大小(以字节为单位) kafka.log:type=Log,name=大小,topic=([-.\w]+),partition=([0-9]+) 磁盘上分区的大小,以字节为单位。
分区中的日志段数 kafka.log:type=Log,name=NumLogSegments,topic=([-.\w]+),partition=([0-9]+) 分区中的日志段数。
分区中的第一个偏移量 kafka.log:type=Log,name=LogStartOffset,topic=([-.\w]+),partition=([0-9]+) 分区中的第一个偏移量。
分区中的最后一个偏移量 kafka.log:type=Log,name=LogEndOffset,topic=([-.\w]+),partition=([0-9]+) 分区中的最后一个偏移量。

KRaft 监控指标

允许监控 KRaft 仲裁和元数据日志的指标集。
请注意,某些公开的指标取决于节点的角色,如
process.roles
KRaft Quorum 监控指标
这些指标在 KRaft 集群中的 Controller 和 Broker 上报告
量度/属性名称 描述 Mbean 名称
当前状态 此成员的当前状态;可能的值为 leader、candidate、voted、follower、unattached、observer。 kafka.server:type=raft-metrics,name=当前状态
现任领导者 当前 quorum leader 的 id;-1 表示未知。 kafka.server:type=raft-metrics,name=current-leader
当前投票 当前投票领导的 ID;-1 表示未投票给任何人。 kafka.server:type=raft-metrics,name=当前投票
当前纪元 当前 quorum 纪元。 kafka.server:type=raft-metrics,name=当前纪元
高水位线 此成员上维护的高水印;如果未知,则为 -1。 kafka.server:type=raft-metrics,name=高水印
Log End Offset 当前 raft log end offset。 kafka.server:type=raft-metrics,name=log-end-offset
未知选民连接数 连接信息未缓存的未知选民数。此指标的此值始终为 0。 kafka.server:type=raft-metrics,name=number-unknown-voter-connections
平均提交延迟 在 raft log 中提交条目的平均时间(以毫秒为单位)。 kafka.server:type=raft-metrics,name=commit-latency-avg
最大提交延迟 在 raft log 中提交条目的最长时间(以毫秒为单位)。 kafka.server:type=raft-metrics,name=commit-latency-max
平均选举延迟 选举新领导者所花费的平均时间(以毫秒为单位)。 kafka.server:type=raft-metrics,name=election-latency-avg
最大选择延迟 选举新领导者所花费的最长时间(以毫秒为单位)。 kafka.server:type=raft-metrics,name=election-latency-max
获取记录速率 从 raft 仲裁的领导层获取的平均记录数。 kafka.server:type=raft-metrics,name=fetch-records-rate
追加记录率 raft 仲裁的领导者每秒附加的平均记录数。 kafka.server:type=raft-metrics,name=append-records-rate
平均轮询空闲比率 客户端的 poll() 处于空闲状态的平均时间,而不是等待用户代码处理记录的时间。 kafka.server:type=raft-metrics,name=poll-idle-ratio-avg
KRaft 控制器监控指标
量度/属性名称 描述 Mbean 名称
主动控制器计数 此节点上的 Active Controller 数量。有效值为 '0' 或 '1'。 kafka.controller:type=KafkaController,name=ActiveControllerCount
事件队列时间 Ms 请求在 Controller Event Queue 中等待所花费的时间(以毫秒为单位)的 Histogram。 kafka.controller:type=ControllerEventManager,name=EventQueueTimeMs
事件队列处理时间 Ms 控制器事件队列中处理请求所花费的时间(以毫秒为单位)的 Histogram。 kafka.controller:type=ControllerEventManager,name=EventQueueProcessingTimeMs
受防护的代理计数 此 Controller 观察到的受防护的 broker 的数量。 kafka.controller:type=KafkaController,name=FencedBrokerCount
活跃代理计数 此 Controller 观察到的活跃 broker 数量。 kafka.controller:type=KafkaController,name=ActiveBrokerCount
全局主题计数 此 Controller 观察到的全局主题数。 kafka.controller:type=KafkaController,name=GlobalTopicCount
全局分区计数 此 Controller 观察到的全局分区数。 kafka.controller:type=KafkaController,name=GlobalPartitionCount
脱机分区计数 此 Controller 观察到的离线主题分区 (非内部) 的数量。 kafka.controller:type=KafkaController,name=OfflinePartitionCount
首选副本不平衡计数 领导者不是首选领导者的主题分区的计数。 kafka.controller:type=KafkaController,name=PreferredReplicaImbalanceCount
元数据错误计数 此控制器节点在元数据日志处理期间遇到错误的次数。 kafka.controller:type=KafkaController,name=MetadataErrorCount
上次应用的记录偏移量 Controller 应用的集群元数据分区中的最后一条记录的偏移量。 kafka.controller:type=KafkaController,name=LastAppliedRecordOffset
上次提交的记录偏移量 提交到此 Controller 的最后一条记录的偏移量。 kafka.controller:type=KafkaController,name=LastCommittedRecordOffset
上次应用的记录时间戳 控制器应用的集群元数据分区中最后一条记录的时间戳。 kafka.controller:type=KafkaController,name=LastAppliedRecordTimestamp
上次应用的记录滞后 ms now 与控制器应用的集群元数据分区中最后一条记录的时间戳之间的差值。 对于主动控制器,此滞后的值始终为零。 kafka.controller:type=KafkaController,name=LastAppliedRecordLagMs
KRaft Broker 监控指标
量度/属性名称 描述 Mbean 名称
上次应用的记录偏移量 代理应用的集群元数据分区中的最后一条记录的偏移量 kafka.server:type=broker-metadata-metrics,name=last-applied-record-offset
上次应用的记录时间戳 代理应用的集群元数据分区中最后一条记录的时间戳。 kafka.server:type=broker-metadata-metrics,name=last-applied-record-timestamp
上次应用的记录滞后 ms now 与代理应用的集群元数据分区中最后一条记录的时间戳之间的差值 kafka.server:type=broker-metadata-metrics,name=last-applied-record-lag-ms
元数据加载错误计数 BrokerMetadataListener 在加载元数据日志并基于它生成新的 MetadataDelta 时遇到的错误数。 kafka.server:type=broker-metadata-metrics,name=metadata-load-error-count
元数据应用错误计数 BrokerMetadataPublisher 在基于最新 MetadataDelta 应用新 MetadataImage 时遇到的错误数。 kafka.server:type=broker-metadata-metrics,name=metadata-apply-error-count

创建者/使用者/连接/流的常见监控指标

以下指标在创建者/使用者/连接器/流实例上可用。有关具体指标,请参阅以下部分。
量度/属性名称 描述 Mbean 名称
connection-close-rate (连接关闭率) 在窗口中每秒关闭的连接数。 kafka.[producer|consumer|connect]:type=[producer|consumer|connect]-metrics,client-id=([-.\w]+)
连接-关闭-总计 窗口中关闭的连接总数。 kafka.[producer|consumer|connect]:type=[producer|consumer|connect]-metrics,client-id=([-.\w]+)
连接创建速率 在窗口中每秒建立的新连接数。 kafka.[producer|consumer|connect]:type=[producer|consumer|connect]-metrics,client-id=([-.\w]+)
连接创建总计 在窗口中建立的新连接总数。 kafka.[producer|consumer|connect]:type=[producer|consumer|connect]-metrics,client-id=([-.\w]+)
网络 IO 速率 每秒对所有连接执行网络作 (读取或写入) 的平均次数。 kafka.[producer|consumer|connect]:type=[producer|consumer|connect]-metrics,client-id=([-.\w]+)
网络 io-total 所有连接上的网络作(读取或写入)总数。 kafka.[producer|consumer|connect]:type=[producer|consumer|connect]-metrics,client-id=([-.\w]+)
传出字节率 每秒发送到所有服务器的平均传出字节数。 kafka.[producer|consumer|connect]:type=[producer|consumer|connect]-metrics,client-id=([-.\w]+)
传出字节总计 发送到所有服务器的传出字节总数。 kafka.[producer|consumer|connect]:type=[producer|consumer|connect]-metrics,client-id=([-.\w]+)
请求速率 每秒发送的平均请求数。 kafka.[producer|consumer|connect]:type=[producer|consumer|connect]-metrics,client-id=([-.\w]+)
请求总计 发送的请求总数。 kafka.[producer|consumer|connect]:type=[producer|consumer|connect]-metrics,client-id=([-.\w]+)
请求大小平均值 窗口中所有请求的平均大小。 kafka.[producer|consumer|connect]:type=[producer|consumer|connect]-metrics,client-id=([-.\w]+)
请求大小最大 窗口中发送的任何请求的最大大小。 kafka.[producer|consumer|connect]:type=[producer|consumer|connect]-metrics,client-id=([-.\w]+)
传入字节率 字节/秒读取所有套接字。 kafka.[producer|consumer|connect]:type=[producer|consumer|connect]-metrics,client-id=([-.\w]+)
传入字节总计 从所有套接字读取的总字节数。 kafka.[producer|consumer|connect]:type=[producer|consumer|connect]-metrics,client-id=([-.\w]+)
响应率 每秒收到的响应数。 kafka.[producer|consumer|connect]:type=[producer|consumer|connect]-metrics,client-id=([-.\w]+)
response-total 响应 收到的回复总数。 kafka.[producer|consumer|connect]:type=[producer|consumer|connect]-metrics,client-id=([-.\w]+)
选择速率 I/O 层每秒检查要执行的新 I/O 的次数。 kafka.[producer|consumer|connect]:type=[producer|consumer|connect]-metrics,client-id=([-.\w]+)
选择总计 I/O 层检查新 I/O 以执行的总次数。 kafka.[producer|consumer|connect]:type=[producer|consumer|connect]-metrics,client-id=([-.\w]+)
io-等待时间-ns-avg I/O 线程等待套接字准备好进行读取或写入所花费的平均时间长度(以纳秒为单位)。 kafka.[producer|consumer|connect]:type=[producer|consumer|connect]-metrics,client-id=([-.\w]+)
io-等待时间-ns-total I/O 线程等待所花费的总时间(以纳秒为单位)。 kafka.[producer|consumer|connect]:type=[producer|consumer|connect]-metrics,client-id=([-.\w]+)
io-waittime-total *荒废的*I/O 线程等待所花费的总时间(以纳秒为单位)。替换是io-wait-time-ns-total. kafka.[producer|consumer|connect]:type=[producer|consumer|connect]-metrics,client-id=([-.\w]+)
io-wait-ratio (io-等待比率) I/O 线程等待所用的时间的分数。 kafka.[producer|consumer|connect]:type=[producer|consumer|connect]-metrics,client-id=([-.\w]+)
io-时间-ns-avg 每次 select 调用的 I/O 平均时间长度(以纳秒为单位)。 kafka.[producer|consumer|connect]:type=[producer|consumer|connect]-metrics,client-id=([-.\w]+)
io-time-ns-total I/O 线程执行 I/O 所花费的总时间(以纳秒为单位)。 kafka.[producer|consumer|connect]:type=[producer|consumer|connect]-metrics,client-id=([-.\w]+)
iotime-total *荒废的*I/O 线程执行 I/O 所花费的总时间(以纳秒为单位)。替换是io-time-ns-total. kafka.[producer|consumer|connect]:type=[producer|consumer|connect]-metrics,client-id=([-.\w]+)
io-ratio I/O 线程执行 I/O 所花费的时间的分数。 kafka.[producer|consumer|connect]:type=[producer|consumer|connect]-metrics,client-id=([-.\w]+)
连接计数 当前活动连接数。 kafka.[producer|consumer|connect]:type=[producer|consumer|connect]-metrics,client-id=([-.\w]+)
成功身份验证率 使用 SASL 或 SSL 成功进行身份验证的每秒连接数。 kafka.[producer|consumer|connect]:type=[producer|consumer|connect]-metrics,client-id=([-.\w]+)
成功身份验证总数 使用 SASL 或 SSL 成功进行身份验证的连接总数。 kafka.[producer|consumer|connect]:type=[producer|consumer|connect]-metrics,client-id=([-.\w]+)
失败的身份验证速率 身份验证失败的每秒连接数。 kafka.[producer|consumer|connect]:type=[producer|consumer|connect]-metrics,client-id=([-.\w]+)
失败的身份验证总数 身份验证失败的连接总数。 kafka.[producer|consumer|connect]:type=[producer|consumer|connect]-metrics,client-id=([-.\w]+)
成功重新身份验证率 使用 SASL 成功重新进行身份验证的每秒连接数。 kafka.[producer|consumer|connect]:type=[producer|consumer|connect]-metrics,client-id=([-.\w]+)
成功重新验证总计 使用 SASL 成功重新进行身份验证的连接总数。 kafka.[producer|consumer|connect]:type=[producer|consumer|connect]-metrics,client-id=([-.\w]+)
reauthentication-latency-max (重新验证延迟最大值) 由于重新身份验证而观察到的最大延迟(以毫秒为单位)。 kafka.[producer|consumer|connect]:type=[producer|consumer|connect]-metrics,client-id=([-.\w]+)
reauthentication-latency-avg (重新验证延迟平均值) 由于重新身份验证而观察到的平均延迟(以毫秒为单位)。 kafka.[producer|consumer|connect]:type=[producer|consumer|connect]-metrics,client-id=([-.\w]+)
失败的重新身份验证率 重新身份验证失败的每秒连接数。 kafka.[producer|consumer|connect]:type=[producer|consumer|connect]-metrics,client-id=([-.\w]+)
失败的重新身份验证总计 重新身份验证失败的连接总数。 kafka.[producer|consumer|connect]:type=[producer|consumer|connect]-metrics,client-id=([-.\w]+)
成功身份验证 no-reauth-total 由不支持重新身份验证的较旧的 2.2.0 之前的 SASL 客户端成功验证的连接总数。只能为非零值。 kafka.[producer|consumer|connect]:type=[producer|consumer|connect]-metrics,client-id=([-.\w]+)

producer/consumer/connect/streams 的常见 Per-broker 指标

以下指标在创建者/使用者/连接器/流实例上可用。有关具体指标,请参阅以下部分。
量度/属性名称 描述 Mbean 名称
传出字节率 节点每秒发送的平均传出字节数。 kafka.[producer|consumer|connect]:type=[消费者|生产者|连接]-node-metrics,client-id=([-.\w]+),node-id=([0-9]+)
传出字节总计 为节点发送的传出字节总数。 kafka.[producer|consumer|connect]:type=[消费者|生产者|连接]-node-metrics,client-id=([-.\w]+),node-id=([0-9]+)
请求速率 节点每秒发送的平均请求数。 kafka.[producer|consumer|connect]:type=[消费者|生产者|连接]-node-metrics,client-id=([-.\w]+),node-id=([0-9]+)
请求总计 为节点发送的请求总数。 kafka.[producer|consumer|connect]:type=[消费者|生产者|连接]-node-metrics,client-id=([-.\w]+),node-id=([0-9]+)
请求大小平均值 节点的窗口中所有请求的平均大小。 kafka.[producer|consumer|connect]:type=[消费者|生产者|连接]-node-metrics,client-id=([-.\w]+),node-id=([0-9]+)
请求大小最大 在窗口中为节点发送的任何请求的最大大小。 kafka.[producer|consumer|connect]:type=[消费者|生产者|连接]-node-metrics,client-id=([-.\w]+),node-id=([0-9]+)
传入字节率 节点每秒接收的平均字节数。 kafka.[producer|consumer|connect]:type=[消费者|生产者|连接]-node-metrics,client-id=([-.\w]+),node-id=([0-9]+)
传入字节总计 节点接收的总字节数。 kafka.[producer|consumer|connect]:type=[消费者|生产者|连接]-node-metrics,client-id=([-.\w]+),node-id=([0-9]+)
请求延迟平均值 节点的平均请求延迟(以毫秒为单位)。 kafka.[producer|consumer|connect]:type=[消费者|生产者|连接]-node-metrics,client-id=([-.\w]+),node-id=([0-9]+)
请求延迟最大 节点的最大请求延迟(以毫秒为单位)。 kafka.[producer|consumer|connect]:type=[消费者|生产者|连接]-node-metrics,client-id=([-.\w]+),node-id=([0-9]+)
响应率 节点每秒收到的响应数。 kafka.[producer|consumer|connect]:type=[消费者|生产者|连接]-node-metrics,client-id=([-.\w]+),node-id=([0-9]+)
response-total 响应 节点收到的响应总数。 kafka.[producer|consumer|connect]:type=[消费者|生产者|连接]-node-metrics,client-id=([-.\w]+),node-id=([0-9]+)

生产者监控

以下指标在创建者实例上可用。
量度/属性名称 描述 Mbean 名称
等待线程 阻塞等待缓冲区内存将其记录排入队列的用户线程数。 kafka.producer:type=producer-metrics,client-id=([-.\w]+)
缓冲区总字节数 客户端可以使用的最大缓冲区内存量(无论当前是否使用)。 kafka.producer:type=producer-metrics,client-id=([-.\w]+)
缓冲区可用字节 未使用的缓冲区内存总量(未分配或在可用列表中)。 kafka.producer:type=producer-metrics,client-id=([-.\w]+)
缓冲池等待时间 appender 等待空间分配的时间分数。 kafka.producer:type=producer-metrics,client-id=([-.\w]+)
缓冲池等待时间总计 *荒废的*appender 等待空间分配的总时间,以纳秒为单位。替换是bufferpool-wait-time-ns-total kafka.producer:type=producer-metrics,client-id=([-.\w]+)
缓冲池等待时间 ns-总计 appender 等待空间分配的总时间,以纳秒为单位。 kafka.producer:type=producer-metrics,client-id=([-.\w]+)
flush-time-ns-total (刷新时间 ns-总计) Producer 在 Producer.flush 中花费的总时间(以纳秒为单位)。 kafka.producer:type=producer-metrics,client-id=([-.\w]+)
txn-init-time-ns-total 创建者初始化交易所花费的总时间,以纳秒为单位(对于 EOS)。 kafka.producer:type=producer-metrics,client-id=([-.\w]+)
txn-开始时间-ns-总计 创建者在 beginTransaction 中花费的总时间,以纳秒为单位(对于 EOS)。 kafka.producer:type=producer-metrics,client-id=([-.\w]+)
txn-send-offsets-time-ns-total 创建者向交易发送偏移量所花费的总时间,以纳秒为单位(对于 EOS)。 kafka.producer:type=producer-metrics,client-id=([-.\w]+)
txn-commit-time-ns-total 创建者提交事务所花费的总时间,以纳秒为单位(对于 EOS)。 kafka.producer:type=producer-metrics,client-id=([-.\w]+)
txn-abort-time-ns-total 创建者中止事务所花费的总时间,以纳秒为单位(对于 EOS)。 kafka.producer:type=producer-metrics,client-id=([-.\w]+)
Producer Sender 指标
kafka.producer:type=producer-metrics,client-id=“{client-id}”
属性名称 描述
批量大小平均每个请求每个分区发送的平均字节数。
最大批量大小每个请求每个分区发送的最大字节数。
批量拆分速率每秒平均批量拆分数
批处理-拆分-总计批量拆分的总数
压缩率平均值记录批处理的平均压缩率,定义为压缩的批处理大小与未压缩大小的平均比率。
元数据年龄正在使用的当前创建者元数据的期限(以秒为单位)。
生产节流时间平均代理限制请求的平均时间(以毫秒为单位)
生产节流时间最大代理限制请求的最长时间(以毫秒为单位)
记录错误率导致错误的每秒平均记录发送数
记录错误总计导致错误的记录发送总数
记录队列时间平均值在发送缓冲区中花费的平均记录批次时间(以毫秒为单位)。
记录队列时间最大值在发送缓冲区中花费的最长时间(以毫秒为单位)。
记录重试率每秒重试记录发送的平均次数
记录重试总数重试记录发送的总数
记录发送速率每秒发送的平均记录数。
记录发送总计发送的记录总数。
记录大小平均值平均记录大小
记录大小最大值最大记录大小
每个请求平均记录数每个请求的平均记录数。
请求延迟平均值平均请求延迟(毫秒)
请求延迟最大最大请求延迟(毫秒)
请求中当前等待响应的正在进行的请求数。
kafka.producer:type=producer-topic-metrics,client-id=“{client-id}”,topic=“{topic}”
属性名称 描述
字节率主题每秒发送的平均字节数。
总字节数为主题发送的总字节数。
compression-rate 压缩率主题的记录批次的平均压缩率,定义为压缩的批次大小与未压缩大小的平均比率。
记录错误率导致主题出错的平均每秒记录发送数
记录错误总计导致主题出错的记录发送总数
记录重试率为主题发送的平均每秒重试记录数
记录重试总数主题发送的重试记录总数
记录发送速率主题每秒发送的平均记录数。
记录发送总计为主题发送的记录总数。

消费者监控

以下指标可用于使用者实例。
量度/属性名称 描述 Mbean 名称
轮询平均值 poll() 调用之间的平均延迟。 kafka.consumer:type=consumer-metrics,client-id=([-.\w]+)
轮询最大值之间的时间 调用 poll() 之间的最大延迟。 kafka.consumer:type=consumer-metrics,client-id=([-.\w]+)
上次轮询秒前 自上次 poll() 调用以来的秒数。 kafka.consumer:type=consumer-metrics,client-id=([-.\w]+)
poll-idle-ratio-avg (平均轮询空闲比率) 消费者的 poll() 处于空闲状态的平均时间分数,而不是等待用户代码处理记录的时间。 kafka.consumer:type=consumer-metrics,client-id=([-.\w]+)
提交时间 ns-total Consumer 提交所花费的总时间(以纳秒为单位)。 kafka.consumer:type=consumer-metrics,client-id=([-.\w]+)
提交同步时间 ns-total Consumer 提交偏移量所花费的总时间,以纳秒为单位(对于 AOS)。 kafka.consumer:type=consumer-metrics,client-id=([-.\w]+)
Consumer Group 指标
量度/属性名称 描述 Mbean 名称
提交延迟平均值 提交请求所用的平均时间 kafka.consumer:type=consumer-coordinator-metrics,client-id=([-.\w]+)
提交延迟最大 提交请求所花费的最大时间 kafka.consumer:type=consumer-coordinator-metrics,client-id=([-.\w]+)
提交率 每秒提交调用数 kafka.consumer:type=consumer-coordinator-metrics,client-id=([-.\w]+)
提交总计 提交调用的总数 kafka.consumer:type=consumer-coordinator-metrics,client-id=([-.\w]+)
已分配分区 当前分配给此使用者的分区数 kafka.consumer:type=consumer-coordinator-metrics,client-id=([-.\w]+)
心跳响应时间最大值 接收检测信号请求的响应所用的最长时间 kafka.consumer:type=consumer-coordinator-metrics,client-id=([-.\w]+)
心跳率 每秒的平均检测信号数 kafka.consumer:type=consumer-coordinator-metrics,client-id=([-.\w]+)
心跳总 检测信号总数 kafka.consumer:type=consumer-coordinator-metrics,client-id=([-.\w]+)
加入时间平均 组重新加入所用的平均时间 kafka.consumer:type=consumer-coordinator-metrics,client-id=([-.\w]+)
加入时间最大值 组重新加入所用的最长时间 kafka.consumer:type=consumer-coordinator-metrics,client-id=([-.\w]+)
加入率 每秒加入组的次数 kafka.consumer:type=consumer-coordinator-metrics,client-id=([-.\w]+)
join-total 组加入总数 kafka.consumer:type=consumer-coordinator-metrics,client-id=([-.\w]+)
同步时间平均值 组同步所用的平均时间 kafka.consumer:type=consumer-coordinator-metrics,client-id=([-.\w]+)
sync-time-max (同步时间最大值) 组同步所用的最长时间 kafka.consumer:type=consumer-coordinator-metrics,client-id=([-.\w]+)
sync-rate 同步速率 每秒的组同步数 kafka.consumer:type=consumer-coordinator-metrics,client-id=([-.\w]+)
sync-total 同步总计 组同步的总数 kafka.consumer:type=consumer-coordinator-metrics,client-id=([-.\w]+)
rebalance-latency-avg (重新平衡延迟平均值) 组再平衡所用的平均时间 kafka.consumer:type=consumer-coordinator-metrics,client-id=([-.\w]+)
最大再平衡延迟 组再平衡所用的最长时间 kafka.consumer:type=consumer-coordinator-metrics,client-id=([-.\w]+)
rebalance-latency-total (总延迟) 到目前为止,组再平衡所花费的总时间 kafka.consumer:type=consumer-coordinator-metrics,client-id=([-.\w]+)
再平衡总计 参与的组再平衡总数 kafka.consumer:type=consumer-coordinator-metrics,client-id=([-.\w]+)
每小时再平衡率 每小时参与的组再平衡数 kafka.consumer:type=consumer-coordinator-metrics,client-id=([-.\w]+)
失败的再平衡总计 失败的组重新平衡的总数 kafka.consumer:type=consumer-coordinator-metrics,client-id=([-.\w]+)
每小时 failed-rebalance-rate-per -hour 每小时失败的组再平衡事件数 kafka.consumer:type=consumer-coordinator-metrics,client-id=([-.\w]+)
上次再平衡秒前 自上次再平衡事件以来的秒数 kafka.consumer:type=consumer-coordinator-metrics,client-id=([-.\w]+)
上次心跳秒前 自上次控制器检测信号以来的秒数 kafka.consumer:type=consumer-coordinator-metrics,client-id=([-.\w]+)
partitions-revoked-latency-avg on-partitions-revoked 再平衡侦听器回调所用的平均时间 kafka.consumer:type=consumer-coordinator-metrics,client-id=([-.\w]+)
partitions-revoked-latency-max (分区撤销延迟最大值) on-partitions-revoked 再平衡侦听器回调所用的最大时间 kafka.consumer:type=consumer-coordinator-metrics,client-id=([-.\w]+)
分区分配延迟平均值 on-partitions-assigned rebalance 侦听器回调所用的平均时间 kafka.consumer:type=consumer-coordinator-metrics,client-id=([-.\w]+)
分区分配延迟最大值 on-partitions-assigned 再平衡侦听器回调所用的最大时间 kafka.consumer:type=consumer-coordinator-metrics,client-id=([-.\w]+)
分区丢失延迟平均值 on-partitions-lost 再平衡监听器回调的平均耗时 kafka.consumer:type=consumer-coordinator-metrics,client-id=([-.\w]+)
分区丢失延迟最大值 on-partitions-lost 再平衡监听器回调所用的最大时间 kafka.consumer:type=consumer-coordinator-metrics,client-id=([-.\w]+)
Consumer Fetch 指标
kafka.consumer:type=consumer-fetch-manager-metrics,client-id=“{client-id}”
属性名称 描述
字节消耗率每秒消耗的平均字节数
总消耗的字节数消耗的总字节数
fetch-latency-avg获取请求所用的平均时间。
fetch-latency-max (获取延迟最大值)任何 fetch 请求所用的最长时间。
fetch-rate 获取速率每秒的 fetch 请求数。
获取大小平均值每个请求提取的平均字节数
获取大小最大每个请求提取的最大字节数
获取节流时间平均值平均限制时间(以毫秒为单位)
获取节流时间最大值最大限制时间(毫秒)
fetch-total (获取总计)获取请求的总数。
记录消耗率每秒消耗的平均记录数
已消耗的记录总数消耗的记录总数
记录滞后最大此窗口中任何分区的记录数的最大滞后。注意:这是基于当前偏移量,而不是提交的偏移量
记录-潜在客户-分钟此窗口中任何分区的记录数的最小领先优势
每个请求平均记录数每个请求中的平均记录数
kafka.consumer:type=consumer-fetch-manager-metrics,client-id=“{client-id}”,topic=“{topic}”
属性名称 描述
字节消耗率主题每秒消耗的平均字节数
总消耗的字节数主题消耗的总字节数
获取大小平均值主题的每个请求提取的平均字节数
获取大小最大主题的每个请求提取的最大字节数
记录消耗率主题每秒消耗的平均记录数
已消耗的记录总数主题消耗的记录总数
每个请求平均记录数主题的每个请求中的平均记录数
kafka.consumer:type=consumer-fetch-manager-metrics,partition=“{partition}”,topic=“{topic}”,client-id=“{client-id}”
属性名称 描述
首选只读副本分区的当前只读副本,如果从 leader 读取,则为 -1
记录滞后分区的最新滞后
记录-滞后-平均值分区的平均滞后
记录滞后最大分区的最大滞后
记录潜在客户分区的最新线索
记录-潜在客户-平均值分区的平均导联
记录-潜在客户-分钟分区的最小导引

连接监控

Connect 工作进程包含所有生产者和使用者指标以及特定于 Connect 的指标。 工作进程本身具有许多指标,而每个连接器和任务都有其他指标。 [2023-12-08 16:42:35,588]INFO Metrics 计划程序已关闭 (org.apache.kafka.common.metrics.Metrics:693) [2023-12-08 16:42:35,589]INFO Metrics Reporters 已关闭 (org.apache.kafka.common.metrics.Metrics:703)
kafka.connect:type=connect-worker-metrics
属性名称 描述
连接器计数此工作程序中运行的连接器数量。
连接器启动尝试总数此 worker 尝试的连接器启动总数。
连接器启动失败百分比此工作线程的连接器启动失败的平均百分比。
连接器启动失败总数失败的连接器启动总数。
连接器启动成功百分比此工作线程的连接器启动成功的平均百分比。
连接器-启动-成功-总计成功的连接器启动总数。
任务计数此 worker 中运行的任务数。
任务启动尝试总数此工作程序尝试的任务启动总数。
任务启动失败百分比此工作程序的失败任务启动的平均百分比。
任务启动失败总数失败的任务启动总数。
任务启动成功百分比此工作人员的任务开始中成功的平均百分比。
任务-启动-成功-总计成功的任务启动总数。
kafka.connect:type=connect-worker-metrics,connector=“{connector}”
属性名称 描述
连接器销毁任务计数worker 上 connector 的已销毁任务数。
连接器失败任务计数工作线程上连接器的失败任务数。
连接器暂停任务计数worker 上连接器的暂停任务数。
连接器重启任务计数worker 上 connector 的重启任务数。
连接器运行任务计数worker 上连接器的运行任务数。
连接器总任务计数worker 上连接器的任务数。
连接器未分配任务计数工作程序上连接器的未分配任务数。
kafka.connect:type=connect-worker-rebalance-metrics
属性名称 描述
completed-rebalances-total此工作程序完成的再平衡总数。
连接协议此集群使用的 Connect 协议
时代此 worker 的 epoch 或代号。
leader-name (领导名称)组长的姓名。
再平衡平均时间 ms此工作程序重新平衡所花费的平均时间(以毫秒为单位)。
重新平衡最大时间 ms此工作程序重新平衡所花费的最长时间(以毫秒为单位)。
平衡此 worker 当前是否正在重新平衡。
自上次再平衡毫秒以来的时间自此 worker 完成最近一次再平衡以来的时间(以毫秒为单位)。
kafka.connect:type=connector-metrics,connector=“{connector}”
属性名称 描述
连接器类连接器类的名称。
连接器类型连接器的类型。“source”或“sink”之一。
连接器版本连接器报告的连接器类的版本。
地位连接器的状态。“unassigned”、“running”、“paused”、“failed”或“restarting”之一。
kafka.connect:type=connector-task-metrics,connector=“{connector}”,task=“{task}”
属性名称 描述
批量大小平均任务到目前为止已处理的批次中的平均记录数。
最大批量大小到目前为止,任务已处理的最大批次中的记录数。
偏移提交平均时间毫秒此任务提交偏移量所用的平均时间(以毫秒为单位)。
偏移提交失败百分比此任务的偏移提交尝试失败的平均百分比。
偏移提交最大时间毫秒此任务提交偏移量所用的最长时间(以毫秒为单位)。
offset-commit-success-percentage (偏移提交成功百分比)此任务的偏移提交尝试成功的平均百分比。
暂停比率此任务处于暂停状态的时间分数。
运行比率此任务处于 running 状态的时间分数。
地位连接器任务的状态。“unassigned”、“running”、“paused”、“failed”或“restarting”之一。
kafka.connect:type=sink-task-metrics,connector=“{connector}”,task=“{task}”
属性名称 描述
offset-commit-completion-rate (偏移提交完成率)成功完成的每秒偏移提交完成的平均数量。
offset-commit-completion-total已成功完成的偏移提交完成总数。
偏移提交 seq-nooffset 提交的当前序列号。
偏移提交跳过率每秒收到时间过晚并跳过/忽略的偏移提交完成的平均数量。
偏移提交跳过总计接收时间过晚并跳过/忽略的偏移提交完成总数。
分区计数分配给此任务的主题分区数,属于此工作程序中的命名接收器连接器。
放置批次平均时间毫秒此任务放置一批 sink 记录所用的平均时间。
放置批处理最大时间毫秒此任务放置一批 sink 记录所用的最长时间。
sink-record-active-count (接收记录主动计数)已从 Kafka 读取但尚未被 sink 任务完全提交/刷新/确认的记录数。
sink-record-active-count-avg已从 Kafka 读取但尚未被 sink 任务完全提交/刷新/确认的平均记录数。
接收器记录活动计数最大值已从 Kafka 读取但尚未被 sink 任务完全提交/刷新/确认的最大记录数。
sink-record-lag-max (接收记录滞后最大值)对于任何主题分区,sink 任务落后于使用者位置的记录数的最大滞后。
接收记录读取速率对于属于此工作程序中命名接收器连接器的此任务,每秒从 Kafka 读取的平均记录数。这是在应用转换之前。
接收器记录读取总数自上次重新启动任务以来,此任务属于此工作程序中命名接收器连接器的从 Kafka 读取的记录总数。
sink-record-send-rate 发送速率从转换输出和发送/放置到此任务的平均每秒记录数,属于此工作程序中的命名接收器连接器。这是在应用转换之后,不包括由转换筛选出的任何记录。
sink-record-send-total (接收记录发送总计)自上次重新启动任务以来,从转换输出并发送/放入此任务的记录总数,属于此工作程序中的命名接收器连接器。
kafka.connect:type=source-task-metrics,connector=“{connector}”,task=“{task}”
属性名称 描述
轮询批处理平均时间毫秒此任务轮询一批源记录所用的平均时间(以毫秒为单位)。
轮询批处理最大时间毫秒此任务轮询一批源记录所用的最长时间(以毫秒为单位)。
源记录活动计数此任务已生成但尚未完全写入 Kafka 的记录数。
源记录有效计数平均值此任务已生成但尚未完全写入 Kafka 的平均记录数。
源记录活动计数最大值此任务已生成但尚未完全写入 Kafka 的最大记录数。
源记录轮询率此任务生成/轮询的平均每秒记录数(转换前),属于此工作程序中的指定源连接器。
源记录轮询总数此任务生成/轮询的记录总数(转换前),属于此工作程序中的指定源连接器。
源记录写入速率自上次重新启动任务以来,对于属于此工作程序中指定源连接器的此任务,每秒写入 Kafka 的平均记录数。这是在应用转换之后,不包括由转换筛选出的任何记录。
源记录写入总计自上次重新启动任务以来,此任务的写入 Kafka 的记录数,属于此工作程序中的指定源连接器。这是在应用转换之后,不包括由转换筛选出的任何记录。
transaction-size-avg (交易大小平均)到目前为止,任务已提交的事务中的平均记录数。
事务大小最大到目前为止,任务已提交的最大事务中的记录数。
事务大小最小到目前为止,任务已提交的最小事务中的记录数。
kafka.connect:type=task-error-metrics,connector=“{connector}”,task=“{task}”
属性名称 描述
deadletterqueue-produce-failures对死信队列的失败写入次数。
deadletterqueue-生产请求尝试写入死信队列的次数。
上次错误时间戳此任务上次遇到错误时的纪元时间戳。
总计错误记录记录的错误数。
总记录错误此任务中的记录处理错误数。
总记录失败数此任务中记录处理失败的次数。
总跳过记录数由于错误而跳过的记录数。
总重试次数重试的作数。

流监控

Kafka Streams 实例包含所有创建者和使用者指标以及特定于 Streams 的其他指标。 指标有三个记录级别:info,debugtrace.

请注意,这些指标具有 4 层层次结构。在顶层,每个 started 都有 client 级别的指标 Kafka Streams 客户端。每个客户端都有流线程,具有自己的指标。每个流线程都有任务,它们的 自己的指标。每个任务都有许多处理器节点,它们都有自己的指标。每个任务还具有许多状态存储 和记录缓存,它们都有自己的指标。

使用以下配置选项指定哪些指标 您希望收集:
metrics.recording.level="info"
客户端指标
以下所有指标的记录级别均为info:
量度/属性名称 描述 Mbean 名称
版本 Kafka Streams 客户端的版本。 kafka.streams:type=stream-metrics,client-id=([-.\w]+)
提交 ID Kafka Streams 客户端的版本控制提交 ID。 kafka.streams:type=stream-metrics,client-id=([-.\w]+)
应用程序 ID Kafka Streams 客户端的应用程序 ID。 kafka.streams:type=stream-metrics,client-id=([-.\w]+)
拓扑描述 在 Kafka Streams 客户端中执行的拓扑的描述。 kafka.streams:type=stream-metrics,client-id=([-.\w]+)
Kafka Streams 客户端的状态。 kafka.streams:type=stream-metrics,client-id=([-.\w]+)
失败的流线程 自 Kafka Streams 客户端启动以来失败的流线程数。 kafka.streams:type=stream-metrics,client-id=([-.\w]+)
线程指标
以下所有指标的记录级别均为info:
量度/属性名称 描述 Mbean 名称
提交延迟平均值 此线程的所有正在运行的任务之间的提交平均执行时间(以毫秒为单位)。 kafka.streams:type=stream-thread-metrics,thread-id=([-.\w]+)
提交延迟最大 此线程的所有正在运行的任务中提交的最大执行时间(以毫秒为单位)。 kafka.streams:type=stream-thread-metrics,thread-id=([-.\w]+)
poll-latency-avg 使用者轮询的平均执行时间(以毫秒为单位)。 kafka.streams:type=stream-thread-metrics,thread-id=([-.\w]+)
轮询延迟最大值 使用者轮询的最大执行时间(以毫秒为单位)。 kafka.streams:type=stream-thread-metrics,thread-id=([-.\w]+)
进程延迟平均值 用于处理的平均执行时间(以毫秒为单位)。 kafka.streams:type=stream-thread-metrics,thread-id=([-.\w]+)
进程延迟最大 用于处理的最长执行时间(以毫秒为单位)。 kafka.streams:type=stream-thread-metrics,thread-id=([-.\w]+)
punctuate-latency-avg 标点符号的平均执行时间(以毫秒为单位)。 kafka.streams:type=stream-thread-metrics,thread-id=([-.\w]+)
punctuate-latency-max (最大延迟) 标点符号的最长执行时间(以毫秒为单位)。 kafka.streams:type=stream-thread-metrics,thread-id=([-.\w]+)
提交率 每秒的平均提交数。 kafka.streams:type=stream-thread-metrics,thread-id=([-.\w]+)
提交总计 提交调用的总数。 kafka.streams:type=stream-thread-metrics,thread-id=([-.\w]+)
poll-rate 轮询率 每秒使用者轮询调用的平均次数。 kafka.streams:type=stream-thread-metrics,thread-id=([-.\w]+)
轮询总数 使用者轮询调用的总数。 kafka.streams:type=stream-thread-metrics,thread-id=([-.\w]+)
处理速率 每秒处理的平均记录数。 kafka.streams:type=stream-thread-metrics,thread-id=([-.\w]+)
process-total (进程总计) 已处理记录的总数。 kafka.streams:type=stream-thread-metrics,thread-id=([-.\w]+)
punctuate-rate (点点率) 每秒的平均标点符号调用数。 kafka.streams:type=stream-thread-metrics,thread-id=([-.\w]+)
punctuate-total 标点点调用的总数。 kafka.streams:type=stream-thread-metrics,thread-id=([-.\w]+)
任务创建速率 每秒创建的平均任务数。 kafka.streams:type=stream-thread-metrics,thread-id=([-.\w]+)
任务创建总计 创建的任务总数。 kafka.streams:type=stream-thread-metrics,thread-id=([-.\w]+)
任务关闭率 每秒关闭的平均任务数。 kafka.streams:type=stream-thread-metrics,thread-id=([-.\w]+)
任务已关闭总计 已关闭的任务总数。 kafka.streams:type=stream-thread-metrics,thread-id=([-.\w]+)
阻止时间 ns-总计 线程在 Kafka 上阻塞所用的总时间。 kafka.streams:type=stream-thread-metrics,thread-id=([-.\w]+)
线程启动时间 线程的启动时间。 kafka.streams:type=stream-thread-metrics,thread-id=([-.\w]+)
任务指标
以下所有指标的记录级别均为debug,但 dropped-records-* 和 active-process-ratio 指标,其记录级别为info:
量度/属性名称 描述 Mbean 名称
进程延迟平均值 用于处理的平均执行时间(以 ns 为单位)。 kafka.streams:type=stream-task-metrics,thread-id=([-.\w]+),task-id=([-.\w]+)
进程延迟最大 用于处理的最长执行时间(以 ns 为单位)。 kafka.streams:type=stream-task-metrics,thread-id=([-.\w]+),task-id=([-.\w]+)
处理速率 此任务的所有源处理器节点中每秒处理的平均记录数。 kafka.streams:type=stream-task-metrics,thread-id=([-.\w]+),task-id=([-.\w]+)
process-total (进程总计) 此任务的所有源处理器节点中已处理的记录总数。 kafka.streams:type=stream-task-metrics,thread-id=([-.\w]+),task-id=([-.\w]+)
提交延迟平均值 提交的平均执行时间(以 ns 为单位)。 kafka.streams:type=stream-task-metrics,thread-id=([-.\w]+),task-id=([-.\w]+)
提交延迟最大 提交的最长执行时间(以 ns 为单位)。 kafka.streams:type=stream-task-metrics,thread-id=([-.\w]+),task-id=([-.\w]+)
提交率 每秒平均提交调用数。 kafka.streams:type=stream-task-metrics,thread-id=([-.\w]+),task-id=([-.\w]+)
提交总计 提交调用的总数。 kafka.streams:type=stream-task-metrics,thread-id=([-.\w]+),task-id=([-.\w]+)
记录迟到平均 观察到的平均记录延迟时间 (流时间 - 记录时间戳)。 kafka.streams:type=stream-task-metrics,thread-id=([-.\w]+),task-id=([-.\w]+)
记录延迟最大值 观察到的最大记录延迟时间(流时间 - 记录时间戳)。 kafka.streams:type=stream-task-metrics,thread-id=([-.\w]+),task-id=([-.\w]+)
强制处理速率 每秒强制处理的平均数量。 kafka.streams:type=stream-task-metrics,thread-id=([-.\w]+),task-id=([-.\w]+)
强制处理总计 强制处理的总数。 kafka.streams:type=stream-task-metrics,thread-id=([-.\w]+),task-id=([-.\w]+)
丢弃记录率 此任务中丢弃的平均记录数。 kafka.streams:type=stream-task-metrics,thread-id=([-.\w]+),task-id=([-.\w]+)
丢弃的记录总数 此任务中丢弃的记录总数。 kafka.streams:type=stream-task-metrics,thread-id=([-.\w]+),task-id=([-.\w]+)
主动进程比率 流线程在所有已分配的活动任务中处理此任务所花费的时间的分数。 kafka.streams:type=stream-task-metrics,thread-id=([-.\w]+),task-id=([-.\w]+)
输入缓冲区字节总数 此任务累积的总字节数 kafka.streams:type=stream-task-metrics,thread-id=([-.\w]+),task-id=([-.\w]+)
缓存大小字节总数 此任务累积的缓存大小(以字节为单位)。 kafka.streams:type=stream-task-metrics,thread-id=([-.\w]+),task-id=([-.\w]+)
处理器节点指标
以下指标仅适用于某些类型的节点,即 process-* 指标仅适用于 源处理器节点、suppression-emit-*指标仅适用于 Suppression Operation 节点,emit-final-*指标仅适用于窗口化聚合节点,record-e2e-latency-*度量仅适用于源处理器节点和终端节点(没有后续节点的节点 节点)。 所有指标的记录级别均为debug,除了record-e2e-latency-*具有 记录级别info:
量度/属性名称 描述 Mbean 名称
总消耗的字节数 源处理器节点占用的总字节数。 kafka.streams:type=stream-topic-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),processor-node-id=([-.\w]+),topic=([-.\w]+)
总生成字节数 接收器处理器节点生成的字节总数。 kafka.streams:type=stream-topic-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),processor-node-id=([-.\w]+),topic=([-.\w]+)
处理速率 源处理器节点每秒处理的平均记录数。 kafka.streams:type=stream-processor-node-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),processor-node-id=([-.\w]+)
process-total (进程总计) 源处理器节点每秒处理的记录总数。 kafka.streams:type=stream-processor-node-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),processor-node-id=([-.\w]+)
抑制发出率 从隐藏作节点向下游发出的记录的速率。 kafka.streams:type=stream-processor-node-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),processor-node-id=([-.\w]+)
抑制 - 发出-总计 已从隐藏作节点下游发出的记录总数。 kafka.streams:type=stream-processor-node-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),processor-node-id=([-.\w]+)
emit-final-latency-max (发出最终延迟最大) 当可以发出记录时,发出最终记录的最大延迟。 kafka.streams:type=stream-processor-node-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),processor-node-id=([-.\w]+)
emit-final-latency-avg 当可以发出记录时,发出最终记录的平均延迟。 kafka.streams:type=stream-processor-node-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),processor-node-id=([-.\w]+)
发出最终记录速率 可以发出记录时的记录发出速率。 kafka.streams:type=stream-processor-node-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),processor-node-id=([-.\w]+)
发出最终记录总数 发出的记录总数。 kafka.streams:type=stream-processor-node-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),processor-node-id=([-.\w]+)
记录 e2e-延迟-avg 记录的平均端到端延迟,通过将记录时间戳与节点完全处理记录的系统时间进行比较来衡量。 kafka.streams:type=stream-processor-node-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),processor-node-id=([-.\w]+)
记录 e2e-延迟-max 记录的最大端到端延迟,通过将记录时间戳与节点完全处理记录的系统时间进行比较来衡量。 kafka.streams:type=stream-processor-node-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),processor-node-id=([-.\w]+)
record-e2e-latency-min 记录的最小端到端延迟,通过将记录时间戳与节点完全处理记录的系统时间进行比较来衡量。 kafka.streams:type=stream-processor-node-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),processor-node-id=([-.\w]+)
已消耗的记录总数 源处理器节点使用的记录总数。 kafka.streams:type=stream-topic-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),processor-node-id=([-.\w]+),topic=([-.\w]+)
已生成记录总数 接收器处理器节点生成的记录总数。 kafka.streams:type=stream-topic-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),processor-node-id=([-.\w]+),topic=([-.\w]+)
状态存储指标
以下所有指标的记录级别均为debug,但 record-e2e-latency-* 指标除外,该指标的记录级别trace. 请注意,store-scope值在StoreSupplier#metricsScope()用于用户的自定义状态存储; 对于内置的 State Store,目前我们有:
  • in-memory-state
  • in-memory-lru-state
  • in-memory-window-state
  • in-memory-suppression(用于抑制缓冲液)
  • rocksdb-state(用于 RocksDB 支持的键值存储)
  • rocksdb-window-state(适用于 RocksDB 支持的窗口存储)
  • rocksdb-session-state(适用于 RocksDB 支持的会话存储)
指标 suppression-buffer-size-avg、suppression-buffer-size-max、suppression-buffer-count-avg 和 suppression-buffer-count-max 仅适用于 Suppression Buffers。所有其他指标都不适用于 Suppression Buffer。
量度/属性名称 描述 Mbean 名称
放置延迟平均值 平均看跌执行时间(以 ns 为单位)。 kafka.streams:type=stream-state-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),[store-scope]-id=([-.\w]+)
放置延迟最大 最大 put 执行时间(以 ns 为单位)。 kafka.streams:type=stream-state-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),[store-scope]-id=([-.\w]+)
放置如果不存在延迟平均值 平均 put-if-absence 执行时间(以 ns 为单位)。 kafka.streams:type=stream-state-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),[store-scope]-id=([-.\w]+)
如果不存在延迟最大 最大 put-if-absence 执行时间(以 ns 为单位)。 kafka.streams:type=stream-state-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),[store-scope]-id=([-.\w]+)
获取延迟平均值 平均 get 执行时间(以 ns 为单位)。 kafka.streams:type=stream-state-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),[store-scope]-id=([-.\w]+)
获取延迟最大值 最大 get 执行时间(以 ns 为单位)。 kafka.streams:type=stream-state-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),[store-scope]-id=([-.\w]+)
删除延迟平均值 平均删除执行时间(以 ns 为单位)。 kafka.streams:type=stream-state-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),[store-scope]-id=([-.\w]+)
删除延迟最大值 最大删除执行时间(以 ns 为单位)。 kafka.streams:type=stream-state-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),[store-scope]-id=([-.\w]+)
放置所有延迟平均值 平均 put-all 执行时间(以 ns 为单位)。 kafka.streams:type=stream-state-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),[store-scope]-id=([-.\w]+)
放置所有延迟最大 最大 put-all 执行时间(以 ns 为单位)。 kafka.streams:type=stream-state-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),[store-scope]-id=([-.\w]+)
所有延迟平均值 所有作的平均执行时间(以 ns 为单位)。 kafka.streams:type=stream-state-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),[store-scope]-id=([-.\w]+)
所有延迟最大 最大 all operation 执行时间(以 ns 为单位)。 kafka.streams:type=stream-state-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),[store-scope]-id=([-.\w]+)
range-latency-avg (平均延迟) 平均范围执行时间(以 ns 为单位)。 kafka.streams:type=stream-state-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),[store-scope]-id=([-.\w]+)
最大范围延迟 最大范围执行时间(以 ns 为单位)。 kafka.streams:type=stream-state-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),[store-scope]-id=([-.\w]+)
flush-latency-avg (刷新延迟平均值) 平均 flush 执行时间(以 ns 为单位)。 kafka.streams:type=stream-state-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),[store-scope]-id=([-.\w]+)
flush-latency-max (刷新延迟最大) 最大 flush 执行时间(以 ns 为单位)。 kafka.streams:type=stream-state-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),[store-scope]-id=([-.\w]+)
恢复延迟平均值 平均还原执行时间(以 ns 为单位)。 kafka.streams:type=stream-state-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),[store-scope]-id=([-.\w]+)
恢复延迟最大 最大还原执行时间(以 ns 为单位)。 kafka.streams:type=stream-state-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),[store-scope]-id=([-.\w]+)
put-rate (放价) 此商店的平均看跌汇率。 kafka.streams:type=stream-state-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),[store-scope]-id=([-.\w]+)
如果不存在 RATE,则放置 此商店的平均 put-if-present 率。 kafka.streams:type=stream-state-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),[store-scope]-id=([-.\w]+)
get-rate 此商店的平均 get rate。 kafka.streams:type=stream-state-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),[store-scope]-id=([-.\w]+)
删除率 此存储的平均删除率。 kafka.streams:type=stream-state-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),[store-scope]-id=([-.\w]+)
全部放率 此商店的平均 put-all 费率。 kafka.streams:type=stream-state-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),[store-scope]-id=([-.\w]+)
全速 此商店的平均 all 运营率。 kafka.streams:type=stream-state-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),[store-scope]-id=([-.\w]+)
range-rate (距离速率) 此商店的平均范围比率。 kafka.streams:type=stream-state-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),[store-scope]-id=([-.\w]+)
flush-rate 刷新率 此商店的平均冲水率。 kafka.streams:type=stream-state-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),[store-scope]-id=([-.\w]+)
恢复速率 此存储的平均还原速率。 kafka.streams:type=stream-state-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),[store-scope]-id=([-.\w]+)
suppression-buffer-size-avg 采样窗口内缓冲数据的平均总大小(以字节为单位)。 kafka.streams:type=stream-state-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),in-memory-suppression-id=([-.\w]+)
suppression-buffer-size-max (最大缓冲区大小) 采样窗口内缓冲数据的最大总大小(以字节为单位)。 kafka.streams:type=stream-state-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),in-memory-suppression-id=([-.\w]+)
抑制缓冲区计数平均值 在采样时段内缓冲的平均记录数。 kafka.streams:type=stream-state-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),in-memory-suppression-id=([-.\w]+)
suppression-buffer-count-max (抑制缓冲区计数最大值) 在采样时段内缓冲的最大记录数。 kafka.streams:type=stream-state-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),in-memory-suppression-id=([-.\w]+)
记录 e2e-延迟-avg 记录的平均端到端延迟,通过将记录时间戳与节点完全处理记录的系统时间进行比较来衡量。 kafka.streams:type=stream-state-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),[store-scope]-id=([-.\w]+)
记录 e2e-延迟-max 记录的最大端到端延迟,通过将记录时间戳与节点完全处理记录的系统时间进行比较来衡量。 kafka.streams:type=stream-state-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),[store-scope]-id=([-.\w]+)
record-e2e-latency-min 记录的最小端到端延迟,通过将记录时间戳与节点完全处理记录的系统时间进行比较来衡量。 kafka.streams:type=stream-state-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),[store-scope]-id=([-.\w]+)
RocksDB 指标
RocksDB 指标分为基于统计信息的指标和基于属性的指标。 前者记录自 RocksDB 状态存储收集的统计信息,而后者记录自 RocksDB 公开的属性。 RocksDB 收集的统计数据提供了随时间推移的累积测量值,例如写入状态存储的字节数。 RocksDB 公开的属性提供当前测量值,例如当前使用的内存量。 请注意,store-scope对于内置的 RocksDB 状态存储,目前如下:
  • rocksdb-state(用于 RocksDB 支持的键值存储)
  • rocksdb-window-state(适用于 RocksDB 支持的窗口存储)
  • rocksdb-session-state(适用于 RocksDB 支持的会话存储)
RocksDB 基于统计的指标:以下所有基于统计数据的指标的记录级别均为debug因为收集 RocksDB 中的统计信息 可能会影响性能。 每分钟从 RocksDB 状态存储中收集一次基于统计数据的指标。 如果一个状态存储由多个 RocksDB 实例组成,就像 WindowStores 和 SessionStores 一样, 每个指标都报告了状态存储的 RocksDB 实例的聚合。
量度/属性名称 描述 Mbean 名称
字节写入速率 每秒写入 RocksDB 状态存储的平均字节数。 kafka.streams:type=stream-state-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),[store-scope]-id=([-.\w]+)
总写入字节数 写入 RocksDB 状态存储的总字节数。 kafka.streams:type=stream-state-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),[store-scope]-id=([-.\w]+)
字节读取速率 每秒从 RocksDB 状态存储读取的平均字节数。 kafka.streams:type=stream-state-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),[store-scope]-id=([-.\w]+)
字节读取总计 从 RocksDB 状态存储读取的总字节数。 kafka.streams:type=stream-state-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),[store-scope]-id=([-.\w]+)
memtable 字节刷新率 每秒从 memtable 刷新到磁盘的平均字节数。 kafka.streams:type=stream-state-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),[store-scope]-id=([-.\w]+)
memtable 字节刷新总计 从 memtable 刷新到磁盘的总字节数。 kafka.streams:type=stream-state-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),[store-scope]-id=([-.\w]+)
memtable-hit-ratio (内存匹配比率) memtable 命中数相对于 memtable 的所有查找的比率。 kafka.streams:type=stream-state-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),[store-scope]-id=([-.\w]+)
memtable-flush-time-avg memtable 刷新到磁盘的平均持续时间(以毫秒为单位)。 kafka.streams:type=stream-state-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),[store-scope]-id=([-.\w]+)
memtable 刷新时间分钟 memtable 刷新到磁盘的最短持续时间(以毫秒为单位)。 kafka.streams:type=stream-state-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),[store-scope]-id=([-.\w]+)
memtable 刷新时间最大值 memtable 刷新到磁盘的最长持续时间(以毫秒为单位)。 kafka.streams:type=stream-state-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),[store-scope]-id=([-.\w]+)
块缓存数据命中率 数据块的块缓存命中数相对于数据块的所有查找到块缓存的比率。 kafka.streams:type=stream-state-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),[store-scope]-id=([-.\w]+)
块缓存索引命中率 索引块的块缓存命中数相对于索引块到块缓存的所有查找的比率。 kafka.streams:type=stream-state-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),[store-scope]-id=([-.\w]+)
块缓存过滤器命中率 filter blocks 的块缓存命中数相对于 filter blocks 的所有查找到块缓存的比率。 kafka.streams:type=stream-state-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),[store-scope]-id=([-.\w]+)
写入停顿持续时间平均值 写入停顿的平均持续时间(以毫秒为单位)。 kafka.streams:type=stream-state-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),[store-scope]-id=([-.\w]+)
写入停顿持续时间总计 写入停顿的总持续时间(以毫秒为单位)。 kafka.streams:type=stream-state-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),[store-scope]-id=([-.\w]+)
字节读取压缩率 压缩期间每秒读取的平均字节数。 kafka.streams:type=stream-state-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),[store-scope]-id=([-.\w]+)
字节写入压缩率 压缩期间每秒写入的平均字节数。 kafka.streams:type=stream-state-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),[store-scope]-id=([-.\w]+)
压缩时间平均 光盘压缩的平均持续时间(以毫秒为单位)。 kafka.streams:type=stream-state-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),[store-scope]-id=([-.\w]+)
压缩时间-min 光盘压缩的最短持续时间(以毫秒为单位)。 kafka.streams:type=stream-state-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),[store-scope]-id=([-.\w]+)
压缩时间最大值 光盘压缩的最长持续时间(以毫秒为单位)。 kafka.streams:type=stream-state-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),[store-scope]-id=([-.\w]+)
number-open-files 文件 当前打开的文件数。 kafka.streams:type=stream-state-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),[store-scope]-id=([-.\w]+)
number-file-errors-total 文件错误总数 发生的文件错误总数。 kafka.streams:type=stream-state-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),[store-scope]-id=([-.\w]+)
基于 RocksDB Properties 的指标:以下所有基于属性的量度的记录级别均为info并在 指标。 如果一个状态存储由多个 RocksDB 实例组成,就像 WindowStores 和 SessionStores 一样, 每个指标报告状态存储的所有 RocksDB 实例的总和,但块缓存指标除外block-cache-*.如果每个实例都使用其 拥有块缓存,如果共享单个块缓存,则它们仅报告来自一个实例的记录值 在所有实例中。
量度/属性名称 描述 Mbean 名称
num-immutable-mem-table (不可变内存表) 尚未刷新的不可变 memtable 的数量。 kafka.streams:type=stream-state-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),[store-scope]-id=([-.\w]+)
当前大小活动内存表 活动 memtable 的近似大小(以字节为单位)。 kafka.streams:type=stream-state-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),[store-scope]-id=([-.\w]+)
当前大小所有内存表 活动和未刷新的不可变 memtable 的近似大小(以字节为单位)。 kafka.streams:type=stream-state-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),[store-scope]-id=([-.\w]+)
大小所有内存表 活动、未刷新的不可变和固定的不可变 memtable 的近似大小(以字节为单位)。 kafka.streams:type=stream-state-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),[store-scope]-id=([-.\w]+)
num-entries-active-mem-table (数字条目活动内存表) 活动 memtable 中的条目数。 kafka.streams:type=stream-state-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),[store-scope]-id=([-.\w]+)
num-entries-imm-mem-tables 未刷新的不可变 memtable 中的条目数。 kafka.streams:type=stream-state-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),[store-scope]-id=([-.\w]+)
num-deletes-active-mem-table 活动 memtable 中的 delete 条目数。 kafka.streams:type=stream-state-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),[store-scope]-id=([-.\w]+)
num-deletes-imm-mem-tables 未刷新的不可变 memtable 中的 delete 条目数。 kafka.streams:type=stream-state-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),[store-scope]-id=([-.\w]+)
mem-table-flush-pending 内存 如果 memtable flush 处于待处理状态,则此指标报告 1,否则报告 0。 kafka.streams:type=stream-state-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),[store-scope]-id=([-.\w]+)
运行刷新的 num 个 当前正在运行的 flush 的数量。 kafka.streams:type=stream-state-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),[store-scope]-id=([-.\w]+)
压缩待定 如果至少有一个压缩处于待处理状态,则此指标报告 1,否则报告 0。 kafka.streams:type=stream-state-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),[store-scope]-id=([-.\w]+)
num-running-comp作 当前正在运行的压缩数。 kafka.streams:type=stream-state-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),[store-scope]-id=([-.\w]+)
estimate-pending-compaction-bytes (估计待处理压缩字节数) 压缩需要在磁盘上重写以将所有级别降至以下的估计总字节数 目标大小 (仅对关卡压缩有效)。 kafka.streams:type=stream-state-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),[store-scope]-id=([-.\w]+)
总 SST 文件大小 所有 SST 文件的总大小(以字节为单位)。 kafka.streams:type=stream-state-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),[store-scope]-id=([-.\w]+)
实时 sst 文件大小 属于最新 LSM 树的所有 SST 文件的总大小(以字节为单位)。 kafka.streams:type=stream-state-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),[store-scope]-id=([-.\w]+)
实时版本数 LSM 树的实时版本数。 kafka.streams:type=stream-state-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),[store-scope]-id=([-.\w]+)
块缓存容量 块缓存的容量(以字节为单位)。 kafka.streams:type=stream-state-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),[store-scope]-id=([-.\w]+)
块缓存使用 驻留在块缓存中的条目的内存大小(以字节为单位)。 kafka.streams:type=stream-state-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),[store-scope]-id=([-.\w]+)
块缓存固定使用 被固定在块缓存中的条目的内存大小(以字节为单位)。 kafka.streams:type=stream-state-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),[store-scope]-id=([-.\w]+)
估计 num 键 活动和未刷新的不可变 memtable 和存储中的估计键数。 kafka.streams:type=stream-state-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),[store-scope]-id=([-.\w]+)
估计表读取者 mem 用于读取 SST 表的估计内存(以字节为单位),不包括块缓存中使用的内存。 kafka.streams:type=stream-state-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),[store-scope]-id=([-.\w]+)
背景错误 后台错误的总数。 kafka.streams:type=stream-state-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),[store-scope]-id=([-.\w]+)
记录缓存指标
以下所有指标的记录级别均为debug:
量度/属性名称 描述 Mbean 名称
平均命中率 平均缓存命中率定义为缓存读取命中数与总缓存读取请求的比率。 kafka.streams:type=stream-record-cache-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),record-cache-id=([-.\w]+)
命中率-最小值 最小缓存命中率。 kafka.streams:type=stream-record-cache-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),record-cache-id=([-.\w]+)
命中率最大值 最大缓存命中率。 kafka.streams:type=stream-record-cache-metrics,thread-id=([-.\w]+),task-id=([-.\w]+),record-cache-id=([-.\w]+)

别人

我们建议监控 GC 时间和其他统计信息以及各种服务器统计信息,例如 CPU 利用率、I/O 服务时间等。 在客户端,我们建议监控消息/字节速率(全局和每个主题)、请求速率/大小/时间,在消费者端,监控所有分区中消息的最大滞后和最小获取请求速率。为了让消费者跟上,最大滞后需要小于阈值,最小获取速率需要大于 0。

6.9 动物园守护者

稳定版

目前的稳定分支是 3.5。Kafka 会定期更新,以包含 3.5 系列中的最新版本。

ZooKeeper 弃用

随着 Apache Kafka 3.5 的发布,Zookeeper 现在被标记为已弃用。计划在 Apache Kafka 的下一个主要版本(版本 4.0)中删除 ZooKeeper, 计划不早于 2024 年 4 月进行。在弃用阶段,Kafka 集群的元数据管理仍然支持 ZooKeeper, 但不建议用于新部署。还有一小部分功能有待在 KRaft 中实现 有关详细信息,请参阅当前缺失的功能

迁移

将现有的基于 ZooKeeper 的 Kafka 集群迁移到 KRaft 目前是预览版,我们预计它将在 3.6 版本中准备好用于生产。建议用户开始规划迁移到 KRaft 并开始测试以提供任何反馈。有关如何执行从 ZooKeeper 到 KRaft 的实时迁移和当前限制的详细信息,请参阅 ZooKeeper 到 KRaft 的迁移。

3.x 和 ZooKeeper 支持

支持 ZooKeeper 模式的最终 3.x 次要版本将在发布后的 12 个月内收到关键错误修复和安全修复。

ZooKeeper 和 KRaft 时间线

有关 ZooKeeper 删除暂定时间表和计划发布的 KRaft 功能的详细信息和更新,请参阅 KIP-833

实施 ZooKeeper

在作上,我们为健康的 ZooKeeper 安装执行以下作:
  • 物理/硬件/网络布局中的冗余:尽量不要把它们都放在同一个机架上,体面的(但不要发疯)硬件,尽量保持冗余的电源和网络路径等。典型的 ZooKeeper ensemble 有 5 或 7 台服务器,分别可以容忍 2 台和 3 台服务器宕机。如果您的部署规模较小,则使用 3 台服务器是可以接受的,但请记住,在这种情况下,您只能容忍 1 台服务器停机。
  • I/O 隔离:如果您执行大量写入类型的流量,您几乎肯定会希望事务日志位于专用磁盘组上。对事务日志的写入是同步的(但为了提高性能而进行批处理),因此,并发写入会显著影响性能。ZooKeeper 快照可以是这样一个并发写入源,理想情况下应该写入与事务日志分开的磁盘组。快照以异步方式写入磁盘,因此通常可以与作系统和消息日志文件共享。您可以通过 dataLogDir 参数将服务器配置为使用单独的磁盘组。
  • 应用程序隔离:除非您真正了解要安装在同一机器上的其他应用程序的应用程序模式,否则最好单独运行 ZooKeeper(尽管这可能是与硬件功能的平衡行为)。
  • 小心虚拟化:它可以工作,具体取决于您的集群布局、读/写模式和 SLA,但虚拟化层引入的微小开销可能会累积并丢弃 ZooKeeper,因为它可能对时间非常敏感
  • ZooKeeper 配置:它是 java,确保给它“足够”的堆空间(我们通常用 3-5G 运行它们,但这主要是由于我们这里的数据集大小)。遗憾的是,我们没有一个好的公式,但请记住,允许更多的 ZooKeeper 状态意味着快照可能会变得很大,而大型快照会影响恢复时间。事实上,如果快照变得太大(几 GB),则可能需要增加 initLimit 参数,以便为服务器提供足够的时间来恢复和加入 ensemble。
  • 监控:JMX 和 4 个字母的单词 (4lw) 命令都非常有用,它们在某些情况下确实会重叠(在这些情况下,我们更喜欢 4 个字母的命令,它们似乎更可预测,或者至少,它们与 LI 监控基础设施配合得更好)
  • 不要过度构建集群:大型集群,尤其是在写入密集型使用模式下,意味着大量的集群内通信(写入和后续集群成员更新的仲裁),但不要构建不足(否则可能会淹没集群)。拥有更多服务器会增加您的读取容量。
总的来说,我们尽量使 ZooKeeper 系统尽可能小,以处理负载(加上标准的增长容量规划)并尽可能简单。与正式版本相比,我们尽量不对配置或应用程序布局做任何花哨的事情,并尽可能保持其自包含。由于这些原因,我们倾向于跳过 OS 打包版本,因为它倾向于尝试将内容放在 OS 标准层次结构中,这可能会“混乱”,因为缺乏更好的措辞方式。

6.10 KRaft

配置

进程角色

在 KRaft 模式下,每个 Kafka 服务器都可以配置为控制器、代理或两者兼而有之,使用process.roles财产。此属性可以具有以下值:

  • 如果process.roles设置为broker,则服务器充当代理。
  • 如果process.roles设置为controller,服务器充当控制器。
  • 如果process.roles设置为broker,controller,服务器同时充当 Broker 和 Controller。
  • 如果process.roles根本没有设置,则假定它处于 ZooKeeper 模式。

同时充当代理和控制器的 Kafka 服务器称为“组合”服务器。组合服务器更易于作,适用于开发环境等小型使用案例。主要缺点是控制器与系统其余部分的隔离程度较低。例如,在组合模式下,无法独立于 broker 滚动或扩展 controller。不建议在关键部署环境中使用组合模式。

控制器

在 KRaft 模式下,选择特定的 Kafka 服务器作为控制器(与基于 ZooKeeper 的模式不同,在基于 ZooKeeper 的模式下,任何服务器都可以成为 Controller)。被选为控制器的服务器将参与元数据仲裁。每个控制器都是当前活动控制器的活动或热备用控制器。

Kafka 管理员通常会为此角色选择 3 或 5 台服务器,具体取决于成本和系统应承受的并发故障数量等因素,而不会影响可用性。大多数 Controller 必须处于活动状态才能保持可用性。使用 3 个控制器时,集群可以容忍 1 个控制器故障;如果集群有 5 个控制器,则集群可以容忍 2 个控制器故障。

Kafka 集群中的所有服务器都使用controller.quorum.voters财产。这将标识应使用的 quorum controller 服务器。必须枚举所有控制器。每个控制器都用他们的id,hostport信息。例如:

controller.quorum.voters=id1@host1:port1,id2@host2:port2,id3@host3:port3

如果 Kafka 集群有 3 个名为 controller1、controller2 和 controller3 的控制器,则 controller1 可能具有以下配置:


process.roles=controller
node.id=1
listeners=CONTROLLER://controller1.example.com:9093
controller.quorum.voters=1@controller1.example.com:9093,2@controller2.example.com:9093,3@controller3.example.com:9093

每个 broker 和 controller 都必须设置controller.quorum.voters财产。在controller.quorum.voters属性必须与 Controller 服务器上的相应 ID 匹配。例如,在 controller1 上,node.id 必须设置为 1,依此类推。每个节点 ID 在特定集群中的所有服务器中必须是唯一的。任何两台服务器都不能具有相同的节点 ID,无论其process.roles值。

存储工具

kafka-storage.sh random-uuid命令可用于为新集群生成集群 ID。当使用kafka-storage.sh format命令。

这与 Kafka 过去的运作方式不同。以前,Kafka 会自动格式化空白存储目录,并自动生成新的集群 ID。更改的一个原因是自动格式化有时会掩盖错误情况。这对于控制器和代理服务器维护的元数据日志尤其重要。如果大多数控制器能够从空日志目录开始,则可能能够在缺少提交数据的情况下选举 leader。

调试

元数据仲裁工具

kafka-metadata-quorum工具可用于描述集群元数据分区的运行时状态。例如,以下命令显示元数据仲裁的摘要:

  > bin/kafka-metadata-quorum.sh --bootstrap-server  broker_host:port describe --status
ClusterId:              fMCL8kv1SWm87L_Md-I2hg
LeaderId:               3002
LeaderEpoch:            2
HighWatermark:          10
MaxFollowerLag:         0
MaxFollowerLagTimeMs:   -1
CurrentVoters:          [3000,3001,3002]
CurrentObservers:       [0,1,2]
转储日志工具

kafka-dump-log工具可用于调试集群元数据目录的日志分段和快照。该工具将扫描提供的文件并解码元数据记录。例如,此命令解码并打印第一个日志段中的记录:

  > bin/kafka-dump-log.sh --cluster-metadata-decoder --files metadata_log_dir/__cluster_metadata-0/00000000000000000000.log

此命令解码并打印集群元数据快照中的 recrods:

  > bin/kafka-dump-log.sh --cluster-metadata-decoder --files metadata_log_dir/__cluster_metadata-0/00000000000000000100-0000000001.checkpoint
元数据 Shell

kafka-metadata-shell工具可用于交互式检查集群元数据分区的状态:


  > bin/kafka-metadata-shell.sh  --snapshot metadata_log_dir/__cluster_metadata-0/00000000000000000000.log
>> ls /
brokers  local  metadataQuorum  topicIds  topics
>> ls /topics
foo
>> cat /topics/foo/0/data
{
  "partitionId" : 0,
  "topicId" : "5zoAlv-xEh9xRANKXt1Lbg",
  "replicas" : [ 1 ],
  "isr" : [ 1 ],
  "removingReplicas" : null,
  "addingReplicas" : null,
  "leader" : 1,
  "leaderEpoch" : 0,
  "partitionEpoch" : 0
}
>> exit
  

部署注意事项

  • Kafka 服务器的process.role应设置为brokercontroller但不能两者兼而有之。组合模式可以在开发环境中使用,但应避免在关键部署环境中使用。
  • 为了实现冗余,Kafka 集群应使用 3 个控制器。在关键环境中,不建议使用 3 个以上的控制器。在极少数情况下,部分网络故障时,群集元数据仲裁可能会变得不可用。此限制将在 Kafka 的未来版本中得到解决。
  • Kafka 控制器将集群的所有元数据存储在内存和磁盘上。我们认为,对于典型的 Kafka 集群,元数据日志控制器上的 5GB 主内存和 5GB 磁盘空间就足够了。

缺失的功能

以下功能在 KRaft 模式下未完全实现:

  • 支持具有多个存储目录的 JBOD 配置
  • 修改独立 KRaft 控制器上的某些动态配置
  • 委托令牌

ZooKeeper 到 KRaft 的迁移

ZooKeeper 到 KRaft 的迁移被视为早期访问功能,不建议用于生产集群。

从 ZK 到 KRaft 的迁移尚不支持以下功能:

请使用 JIRA 项目和 “kraft” 组件将 ZooKeeper 迁移到 KRaft 的问题。

术语

我们在这里使用术语 “迁移” 来指代更改 Kafka 集群元数据的过程 系统从 ZooKeeper 迁移到 KRaft 并迁移现有元数据。“升级”是指安装较新版本的 Kafka。不建议 在执行元数据迁移的同时升级软件。

我们还使用术语“ZK 模式”来指代使用 ZooKeeper 作为其元数据的 Kafka 代理 系统。“KRaft 模式”是指使用 KRaft 控制器仲裁作为其元数据系统的 Kafka 代理。

准备迁移

在开始迁移之前,Kafka 代理必须升级到软件版本 3.5.0 并具有 “inter.broker.protocol.version” 配置设置为 “3.5”。请参阅升级到 3.5.0 以了解 升级说明。

建议在迁移处于活动状态时为迁移组件启用 TRACE 级别日志记录。这可以 通过将以下 log4j 配置添加到每个 KRaft 控制器的 “log4j.properties” 文件中来完成。

log4j.logger.org.apache.kafka.metadata.migration=TRACE

在迁移期间,在 KRaft 控制器和 ZK 代理上启用 DEBUG 日志记录通常很有用。

预置 KRaft 控制器仲裁

在开始迁移之前,需要做两件事。首先,必须将 broker 配置为支持迁移,其次, 必须部署 KRaft 控制器 quorum。KRaft 控制器应使用与 现有的 Kafka 集群。这可以通过检查数据目录中的 “meta.properties” 文件之一来找到 中,或者通过运行以下命令。

./bin/zookeeper-shell.sh localhost:2181 get /cluster/id

KRaft 控制器仲裁还应预置最新的metadata.version. 当您使用kafka-storage.sh工具。 有关 KRaft 部署的更多说明,请参阅上述文档

除了标准的 KRaft 配置外,KRaft 控制器还需要启用对迁移的支持 以及提供 ZooKeeper 连接配置。

以下是已准备好迁移的 KRaft 控制器的示例配置:

# Sample KRaft cluster controller.properties listening on 9093
process.roles=controller
node.id=3000
controller.quorum.voters=3000@localhost:9093
controller.listener.names=CONTROLLER
listeners=CONTROLLER://:9093

# Enable the migration
zookeeper.metadata.migration.enable=true

# ZooKeeper client configuration
zookeeper.connect=localhost:2181

# Other configs ...

注意:KRaft 集群node.id值必须与任何现有的 ZK broker 不同broker.id. 在 KRaft 模式下,broker 和 controller 共享相同的 Node ID 命名空间。

在代理上启用迁移

一旦 KRaft 控制器 quorum 启动,就需要重新配置并重新启动 broker。经纪人 可以滚动方式重新启动,以避免影响集群可用性。每个代理都需要 以下配置与 KRaft 控制器通信并启用迁移。

以下是已准备好迁移的代理的示例配置:

# Sample ZK broker server.properties listening on 9092
broker.id=0
listeners=PLAINTEXT://:9092
advertised.listeners=PLAINTEXT://localhost:9092
listener.security.protocol.map=PLAINTEXT:PLAINTEXT,CONTROLLER:PLAINTEXT

# Set the IBP
inter.broker.protocol.version=3.5

# Enable the migration
zookeeper.metadata.migration.enable=true

# ZooKeeper client configuration
zookeeper.connect=localhost:2181

# KRaft controller quorum configuration
controller.quorum.voters=3000@localhost:9093
controller.listener.names=CONTROLLER

注意:使用必要的配置重新启动最终的 ZK broker 后,迁移将自动开始。迁移完成后,可以在活动控制器上观察到 INFO 级别日志:

Completed migration of metadata from Zookeeper to KRaft

将 broker 迁移到 KRaft

一旦 KRaft 控制器完成元数据迁移,代理仍将以 ZK 模式运行。虽然 KRaft 控制器处于迁移模式,它将继续向 ZK 模式代理发送控制器 RPC。这包括 RPC,如 UpdateMetadata 和 LeaderAndIsr。

要将 broker 迁移到 KRaft,只需将它们重新配置为 KRaft brokers 并重新启动即可。使用上述 broker 配置为例,我们将broker.idnode.id并添加process.roles=broker.代理在重新启动时保持相同的 Broker/Node ID 非常重要。 此时应删除 zookeeper 配置。

# Sample KRaft broker server.properties listening on 9092
process.roles=broker
node.id=0
listeners=PLAINTEXT://:9092
advertised.listeners=PLAINTEXT://localhost:9092
listener.security.protocol.map=PLAINTEXT:PLAINTEXT,CONTROLLER:PLAINTEXT

# Don't set the IBP, KRaft uses "metadata.version" feature flag
# inter.broker.protocol.version=3.5

# Remove the migration enabled flag
# zookeeper.metadata.migration.enable=true

# Remove ZooKeeper client configuration
# zookeeper.connect=localhost:2181

# Keep the KRaft controller quorum configuration
controller.quorum.voters=3000@localhost:9093
controller.listener.names=CONTROLLER

每个代理都使用 KRaft 配置重新启动,直到整个集群在 KRaft 模式下运行。

完成迁移

一旦所有 broker 都以 KRaft 模式重新启动,完成迁移的最后一步是执行 KRaft 控制器退出迁移模式。这是通过删除 “zookeeper.metadata.migration.enable” 来完成的 属性,然后一次重新启动一个。

# Sample KRaft cluster controller.properties listening on 9093
process.roles=controller
node.id=3000
controller.quorum.voters=3000@localhost:9093
controller.listener.names=CONTROLLER
listeners=CONTROLLER://:9093

# Disable the migration
# zookeeper.metadata.migration.enable=true

# Remove ZooKeeper client configuration
# zookeeper.connect=localhost:2181

# Other configs ...

7. 安全性

7.1 Security Overview

In release 0.9.0.0, the Kafka community added a number of features that, used either separately or together, increases security in a Kafka cluster. The following security measures are currently supported:
  1. Authentication of connections to brokers from clients (producers and consumers), other brokers and tools, using either SSL or SASL. Kafka supports the following SASL mechanisms:
    • SASL/GSSAPI (Kerberos) - starting at version 0.9.0.0
    • SASL/PLAIN - starting at version 0.10.0.0
    • SASL/SCRAM-SHA-256 and SASL/SCRAM-SHA-512 - starting at version 0.10.2.0
    • SASL/OAUTHBEARER - starting at version 2.0
  2. Authentication of connections from brokers to ZooKeeper
  3. Encryption of data transferred between brokers and clients, between brokers, or between brokers and tools using SSL (Note that there is a performance degradation when SSL is enabled, the magnitude of which depends on the CPU type and the JVM implementation.)
  4. Authorization of read / write operations by clients
  5. Authorization is pluggable and integration with external authorization services is supported
It's worth noting that security is optional - non-secured clusters are supported, as well as a mix of authenticated, unauthenticated, encrypted and non-encrypted clients. The guides below explain how to configure and use the security features in both clients and brokers.

7.2 Listener Configuration

In order to secure a Kafka cluster, it is necessary to secure the channels that are used to communicate with the servers. Each server must define the set of listeners that are used to receive requests from clients as well as other servers. Each listener may be configured to authenticate clients using various mechanisms and to ensure traffic between the server and the client is encrypted. This section provides a primer for the configuration of listeners.

Kafka servers support listening for connections on multiple ports. This is configured through the property in the server configuration, which accepts a comma-separated list of the listeners to enable. At least one listener must be defined on each server. The format of each listener defined in is given below:listenerslisteners

{LISTENER_NAME}://{hostname}:{port}

The is usually a descriptive name which defines the purpose of the listener. For example, many configurations use a separate listener for client traffic, so they might refer to the corresponding listener as in the configuration:LISTENER_NAMECLIENT

listeners=CLIENT://localhost:9092

The security protocol of each listener is defined in a separate configuration: . The value is a comma-separated list of each listener mapped to its security protocol. For example, the follow value configuration specifies that the listener will use SSL while the listener will use plaintext.listener.security.protocol.mapCLIENTBROKER

listener.security.protocol.map=CLIENT:SSL,BROKER:PLAINTEXT

Possible options (case-insensitive) for the security protocol are given below:

  1. PLAINTEXT
  2. SSL
  3. SASL_PLAINTEXT
  4. SASL_SSL

The plaintext protocol provides no security and does not require any additional configuration. In the following sections, this document covers how to configure the remaining protocols.

If each required listener uses a separate security protocol, it is also possible to use the security protocol name as the listener name in . Using the example above, we could skip the definition of the and listeners using the following definition:listenersCLIENTBROKER

listeners=SSL://localhost:9092,PLAINTEXT://localhost:9093

However, we recommend users to provide explicit names for the listeners since it makes the intended usage of each listener clearer.

Among the listeners in this list, it is possible to declare the listener to be used for inter-broker communication by setting the configuration to the name of the listener. The primary purpose of the inter-broker listener is partition replication. If not defined, then the inter-broker listener is determined by the security protocol defined by , which defaults to .inter.broker.listener.namesecurity.inter.broker.protocolPLAINTEXT

For legacy clusters which rely on Zookeeper to store cluster metadata, it is possible to declare a separate listener to be used for metadata propagation from the active controller to the brokers. This is defined by . The active controller will use this listener when it needs to push metadata updates to the brokers in the cluster. The benefit of using a control plane listener is that it uses a separate processing thread, which makes it less likely for application traffic to impede timely propagation of metadata changes (such as partition leader and ISR updates). Note that the default value is null, which means that the controller will use the same listener defined by control.plane.listener.nameinter.broker.listener

In a KRaft cluster, a broker is any server which has the role enabled in and a controller is any server which has the role enabled. Listener configuration depends on the role. The listener defined by is used exclusively for requests between brokers. Controllers, on the other hand, must use separate listener which is defined by the configuration. This cannot be set to the same value as the inter-broker listener.brokerprocess.rolescontrollerinter.broker.listener.namecontroller.listener.names

Controllers receive requests both from other controllers and from brokers. For this reason, even if a server does not have the role enabled (i.e. it is just a broker), it must still define the controller listener along with any security properties that are needed to configure it. For example, we might use the following configuration on a standalone broker:controller

process.roles=broker
listeners=BROKER://localhost:9092
inter.broker.listener.name=BROKER
controller.quorum.voters=0@localhost:9093
controller.listener.names=CONTROLLER
listener.security.protocol.map=BROKER:SASL_SSL,CONTROLLER:SASL_SSL

The controller listener is still configured in this example to use the security protocol, but it is not included in since the broker does not expose the controller listener itself. The port that will be used in this case comes from the configuration, which defines the complete list of controllers.SASL_SSLlistenerscontroller.quorum.voters

For KRaft servers which have both the broker and controller role enabled, the configuration is similar. The only difference is that the controller listener must be included in :listeners

process.roles=broker,controller
listeners=BROKER://localhost:9092,CONTROLLER://localhost:9093
inter.broker.listener.name=BROKER
controller.quorum.voters=0@localhost:9093
controller.listener.names=CONTROLLER
listener.security.protocol.map=BROKER:SASL_SSL,CONTROLLER:SASL_SSL

It is a requirement for the port defined in to exactly match one of the exposed controller listeners. For example, here the listener is bound to port 9093. The connection string defined by must then also use port 9093, as it does here.controller.quorum.votersCONTROLLERcontroller.quorum.voters

The controller will accept requests on all listeners defined by . Typically there would be just one controller listener, but it is possible to have more. For example, this provides a way to change the active listener from one port or security protocol to another through a roll of the cluster (one roll to expose the new listener, and one roll to remove the old listener). When multiple controller listeners are defined, the first one in the list will be used for outbound requests.controller.listener.names

It is conventional in Kafka to use a separate listener for clients. This allows the inter-cluster listeners to be isolated at the network level. In the case of the controller listener in KRaft, the listener should be isolated since clients do not work with it anyway. Clients are expected to connect to any other listener configured on a broker. Any requests that are bound for the controller will be forwarded as described below

In the following section, this document covers how to enable SSL on a listener for encryption as well as authentication. The subsequent section will then cover additional authentication mechanisms using SASL.

7.3 Encryption and Authentication using SSL

Apache Kafka allows clients to use SSL for encryption of traffic as well as authentication. By default, SSL is disabled but can be turned on if needed. The following paragraphs explain in detail how to set up your own PKI infrastructure, use it to create certificates and configure Kafka to use these.
  1. Generate SSL key and certificate for each Kafka broker

    The first step of deploying one or more brokers with SSL support is to generate a public/private keypair for every server. Since Kafka expects all keys and certificates to be stored in keystores we will use Java's keytool command for this task. The tool supports two different keystore formats, the Java specific jks format which has been deprecated by now, as well as PKCS12. PKCS12 is the default format as of Java version 9, to ensure this format is being used regardless of the Java version in use all following commands explicitly specify the PKCS12 format. You need to specify two parameters in the above command:
    > keytool -keystore {keystorefile} -alias localhost -validity {validity} -genkey -keyalg RSA -storetype pkcs12
    1. keystorefile: the keystore file that stores the keys (and later the certificate) for this broker. The keystore file contains the private and public keys of this broker, therefore it needs to be kept safe. Ideally this step is run on the Kafka broker that the key will be used on, as this key should never be transmitted/leave the server that it is intended for.
    2. validity: the valid time of the key in days. Please note that this differs from the validity period for the certificate, which will be determined in Signing the certificate. You can use the same key to request multiple certificates: if your key has a validity of 10 years, but your CA will only sign certificates that are valid for one year, you can use the same key with 10 certificates over time.

    To obtain a certificate that can be used with the private key that was just created a certificate signing request needs to be created. This signing request, when signed by a trusted CA results in the actual certificate which can then be installed in the keystore and used for authentication purposes.
    To generate certificate signing requests run the following command for all server keystores created so far. This command assumes that you want to add hostname information to the certificate, if this is not the case, you can omit the extension parameter . Please see below for more information on this.
    > keytool -keystore server.keystore.jks -alias localhost -validity {validity} -genkey -keyalg RSA -destkeystoretype pkcs12 -ext SAN=DNS:{FQDN},IP:{IPADDRESS1}
    -ext SAN=DNS:{FQDN},IP:{IPADDRESS1}
    Host Name Verification
    Host name verification, when enabled, is the process of checking attributes from the certificate that is presented by the server you are connecting to against the actual hostname or ip address of that server to ensure that you are indeed connecting to the correct server.
    The main reason for this check is to prevent man-in-the-middle attacks. For Kafka, this check has been disabled by default for a long time, but as of Kafka 2.0.0 host name verification of servers is enabled by default for client connections as well as inter-broker connections.
    Server host name verification may be disabled by setting to an empty string.
    For dynamically configured broker listeners, hostname verification may be disabled using :
    ssl.endpoint.identification.algorithmkafka-configs.sh
    > bin/kafka-configs.sh --bootstrap-server localhost:9093 --entity-type brokers --entity-name 0 --alter --add-config "listener.name.internal.ssl.endpoint.identification.algorithm="

    Note:

    Normally there is no good reason to disable hostname verification apart from being the quickest way to "just get it to work" followed by the promise to "fix it later when there is more time"!
    Getting hostname verification right is not that hard when done at the right time, but gets much harder once the cluster is up and running - do yourself a favor and do it now!

    If host name verification is enabled, clients will verify the server's fully qualified domain name (FQDN) or ip address against one of the following two fields:

    1. Common Name (CN)
    2. Subject Alternative Name (SAN)

    While Kafka checks both fields, usage of the common name field for hostname verification has been deprecated since 2000 and should be avoided if possible. In addition the SAN field is much more flexible, allowing for multiple DNS and IP entries to be declared in a certificate.
    Another advantage is that if the SAN field is used for hostname verification the common name can be set to a more meaningful value for authorization purposes. Since we need the SAN field to be contained in the signed certificate, it will be specified when generating the signing request. It can also be specified when generating the keypair, but this will not automatically be copied into the signing request.
    To add a SAN field append the following argument to the keytool command:
    -ext SAN=DNS:{FQDN},IP:{IPADDRESS}
    > keytool -keystore server.keystore.jks -alias localhost -validity {validity} -genkey -keyalg RSA -destkeystoretype pkcs12 -ext SAN=DNS:{FQDN},IP:{IPADDRESS1}
  2. Creating your own CA

    After this step each machine in the cluster has a public/private key pair which can already be used to encrypt traffic and a certificate signing request, which is the basis for creating a certificate. To add authentication capabilities this signing request needs to be signed by a trusted authority, which will be created in this step.

    A certificate authority (CA) is responsible for signing certificates. CAs works likes a government that issues passports - the government stamps (signs) each passport so that the passport becomes difficult to forge. Other governments verify the stamps to ensure the passport is authentic. Similarly, the CA signs the certificates, and the cryptography guarantees that a signed certificate is computationally difficult to forge. Thus, as long as the CA is a genuine and trusted authority, the clients have a strong assurance that they are connecting to the authentic machines.

    For this guide we will be our own Certificate Authority. When setting up a production cluster in a corporate environment these certificates would usually be signed by a corporate CA that is trusted throughout the company. Please see Common Pitfalls in Production for some things to consider for this case.

    Due to a bug in OpenSSL, the x509 module will not copy requested extension fields from CSRs into the final certificate. Since we want the SAN extension to be present in our certificate to enable hostname verification, we'll use the ca module instead. This requires some additional configuration to be in place before we generate our CA keypair.
    Save the following listing into a file called openssl-ca.cnf and adjust the values for validity and common attributes as necessary.

    HOME            = .
    RANDFILE        = $ENV::HOME/.rnd
    
    ####################################################################
    [ ca ]
    default_ca    = CA_default      # The default ca section
    
    [ CA_default ]
    
    base_dir      = .
    certificate   = $base_dir/cacert.pem   # The CA certifcate
    private_key   = $base_dir/cakey.pem    # The CA private key
    new_certs_dir = $base_dir              # Location for new certs after signing
    database      = $base_dir/index.txt    # Database index file
    serial        = $base_dir/serial.txt   # The current serial number
    
    default_days     = 1000         # How long to certify for
    default_crl_days = 30           # How long before next CRL
    default_md       = sha256       # Use public key default MD
    preserve         = no           # Keep passed DN ordering
    
    x509_extensions = ca_extensions # The extensions to add to the cert
    
    email_in_dn     = no            # Don't concat the email in the DN
    copy_extensions = copy          # Required to copy SANs from CSR to cert
    
    ####################################################################
    [ req ]
    default_bits       = 4096
    default_keyfile    = cakey.pem
    distinguished_name = ca_distinguished_name
    x509_extensions    = ca_extensions
    string_mask        = utf8only
    
    ####################################################################
    [ ca_distinguished_name ]
    countryName         = Country Name (2 letter code)
    countryName_default = DE
    
    stateOrProvinceName         = State or Province Name (full name)
    stateOrProvinceName_default = Test Province
    
    localityName                = Locality Name (eg, city)
    localityName_default        = Test Town
    
    organizationName            = Organization Name (eg, company)
    organizationName_default    = Test Company
    
    organizationalUnitName         = Organizational Unit (eg, division)
    organizationalUnitName_default = Test Unit
    
    commonName         = Common Name (e.g. server FQDN or YOUR name)
    commonName_default = Test Name
    
    emailAddress         = Email Address
    emailAddress_default = test@test.com
    
    ####################################################################
    [ ca_extensions ]
    
    subjectKeyIdentifier   = hash
    authorityKeyIdentifier = keyid:always, issuer
    basicConstraints       = critical, CA:true
    keyUsage               = keyCertSign, cRLSign
    
    ####################################################################
    [ signing_policy ]
    countryName            = optional
    stateOrProvinceName    = optional
    localityName           = optional
    organizationName       = optional
    organizationalUnitName = optional
    commonName             = supplied
    emailAddress           = optional
    
    ####################################################################
    [ signing_req ]
    subjectKeyIdentifier   = hash
    authorityKeyIdentifier = keyid,issuer
    basicConstraints       = CA:FALSE
    keyUsage               = digitalSignature, keyEncipherment
    Then create a database and serial number file, these will be used to keep track of which certificates were signed with this CA. Both of these are simply text files that reside in the same directory as your CA keys. With these steps done you are now ready to generate your CA that will be used to sign certificates later. The CA is simply a public/private key pair and certificate that is signed by itself, and is only intended to sign other certificates.
    This keypair should be kept very safe, if someone gains access to it, they can create and sign certificates that will be trusted by your infrastructure, which means they will be able to impersonate anybody when connecting to any service that trusts this CA.
    The next step is to add the generated CA to the **clients' truststore** so that the clients can trust this CA: Note: If you configure the Kafka brokers to require client authentication by setting ssl.client.auth to be "requested" or "required" in the Kafka brokers config then you must provide a truststore for the Kafka brokers as well and it should have all the CA certificates that clients' keys were signed by. In contrast to the keystore in step 1 that stores each machine's own identity, the truststore of a client stores all the certificates that the client should trust. Importing a certificate into one's truststore also means trusting all certificates that are signed by that certificate. As the analogy above, trusting the government (CA) also means trusting all passports (certificates) that it has issued. This attribute is called the chain of trust, and it is particularly useful when deploying SSL on a large Kafka cluster. You can sign all certificates in the cluster with a single CA, and have all machines share the same truststore that trusts the CA. That way all machines can authenticate all other machines.
    > echo 01 > serial.txt
    > touch index.txt
    > openssl req -x509 -config openssl-ca.cnf -newkey rsa:4096 -sha256 -nodes -out cacert.pem -outform PEM
    > keytool -keystore client.truststore.jks -alias CARoot -import -file ca-cert
    > keytool -keystore server.truststore.jks -alias CARoot -import -file ca-cert
  3. Signing the certificate

    Then sign it with the CA: Finally, you need to import both the certificate of the CA and the signed certificate into the keystore: The definitions of the parameters are the following:
    > openssl ca -config openssl-ca.cnf -policy signing_policy -extensions signing_req -out {server certificate} -infiles {certificate signing request}
    > keytool -keystore {keystore} -alias CARoot -import -file {CA certificate}
    > keytool -keystore {keystore} -alias localhost -import -file cert-signed
    1. keystore: the location of the keystore
    2. CA certificate: the certificate of the CA
    3. certificate signing request: the csr created with the server key
    4. server certificate: the file to write the signed certificate of the server to
    This will leave you with one truststore called truststore.jks - this can be the same for all clients and brokers and does not contain any sensitive information, so there is no need to secure this.
    Additionally you will have one server.keystore.jks file per node which contains that nodes keys, certificate and your CAs certificate, please refer to Configuring Kafka Brokers and Configuring Kafka Clients for information on how to use these files.

    For some tooling assistance on this topic, please check out the easyRSA project which has extensive scripting in place to help with these steps.

    SSL key and certificates in PEM format
    From 2.7.0 onwards, SSL key and trust stores can be configured for Kafka brokers and clients directly in the configuration in PEM format. This avoids the need to store separate files on the file system and benefits from password protection features of Kafka configuration. PEM may also be used as the store type for file-based key and trust stores in addition to JKS and PKCS12. To configure PEM key store directly in the broker or client configuration, private key in PEM format should be provided in and the certificate chain in PEM format should be provided in . To configure trust store, trust certificates, e.g. public certificate of CA, should be provided in . Since PEM is typically stored as multi-line base-64 strings, the configuration value can be included in Kafka configuration as multi-line strings with lines terminating in backslash ('\') for line continuation. ssl.keystore.keyssl.keystore.certificate.chainssl.truststore.certificates

    Store password configs and are not used for PEM. If private key is encrypted using a password, the key password must be provided in . Private keys may be provided in unencrypted form without a password. In production deployments, configs should be encrypted or externalized using password protection feature in Kafka in this case. Note that the default SSL engine factory has limited capabilities for decryption of encrypted private keys when external tools like OpenSSL are used for encryption. Third party libraries like BouncyCastle may be integrated with a custom to support a wider range of encrypted private keys.ssl.keystore.passwordssl.truststore.passwordssl.key.passwordSslEngineFactory

  4. Common Pitfalls in Production

    The above paragraphs show the process to create your own CA and use it to sign certificates for your cluster. While very useful for sandbox, dev, test, and similar systems, this is usually not the correct process to create certificates for a production cluster in a corporate environment. Enterprises will normally operate their own CA and users can send in CSRs to be signed with this CA, which has the benefit of users not being responsible to keep the CA secure as well as a central authority that everybody can trust. However it also takes away a lot of control over the process of signing certificates from the user. Quite often the persons operating corporate CAs will apply tight restrictions on certificates that can cause issues when trying to use these certificates with Kafka.
    1. Extended Key Usage
      Certificates may contain an extension field that controls the purpose for which the certificate can be used. If this field is empty, there are no restrictions on the usage, but if any usage is specified in here, valid SSL implementations have to enforce these usages.
      Relevant usages for Kafka are:
      • Client authentication
      • Server authentication
      Kafka brokers need both these usages to be allowed, as for intra-cluster communication every broker will behave as both the client and the server towards other brokers. It is not uncommon for corporate CAs to have a signing profile for webservers and use this for Kafka as well, which will only contain the serverAuth usage value and cause the SSL handshake to fail.
    2. Intermediate Certificates
      Corporate Root CAs are often kept offline for security reasons. To enable day-to-day usage, so called intermediate CAs are created, which are then used to sign the final certificates. When importing a certificate into the keystore that was signed by an intermediate CA it is necessary to provide the entire chain of trust up to the root CA. This can be done by simply cating the certificate files into one combined certificate file and then importing this with keytool.
    3. Failure to copy extension fields
      CA operators are often hesitant to copy and requested extension fields from CSRs and prefer to specify these themselves as this makes it harder for a malicious party to obtain certificates with potentially misleading or fraudulent values. It is adviseable to double check signed certificates, whether these contain all requested SAN fields to enable proper hostname verification. The following command can be used to print certificate details to the console, which should be compared with what was originally requested:
      > openssl x509 -in certificate.crt -text -noout
  5. Configuring Kafka Brokers

    If SSL is not enabled for inter-broker communication (see below for how to enable it), both PLAINTEXT and SSL ports will be necessary. Following SSL configs are needed on the broker side Note: ssl.truststore.password is technically optional but highly recommended. If a password is not set access to the truststore is still available, but integrity checking is disabled. Optional settings that are worth considering:
    listeners=PLAINTEXT://host.name:port,SSL://host.name:port
    ssl.keystore.location=/var/private/ssl/server.keystore.jks
    ssl.keystore.password=test1234
    ssl.key.password=test1234
    ssl.truststore.location=/var/private/ssl/server.truststore.jks
    ssl.truststore.password=test1234
    1. ssl.client.auth=none ("required" => client authentication is required, "requested" => client authentication is requested and client without certs can still connect. The usage of "requested" is discouraged as it provides a false sense of security and misconfigured clients will still connect successfully.)
    2. ssl.cipher.suites (Optional). A cipher suite is a named combination of authentication, encryption, MAC and key exchange algorithm used to negotiate the security settings for a network connection using TLS or SSL network protocol. (Default is an empty list)
    3. ssl.enabled.protocols=TLSv1.2,TLSv1.1,TLSv1 (list out the SSL protocols that you are going to accept from clients. Do note that SSL is deprecated in favor of TLS and using SSL in production is not recommended)
    4. ssl.keystore.type=JKS
    5. ssl.truststore.type=JKS
    6. ssl.secure.random.implementation=SHA1PRNG
    If you want to enable SSL for inter-broker communication, add the following to the server.properties file (it defaults to PLAINTEXT)
    security.inter.broker.protocol=SSL

    Due to import regulations in some countries, the Oracle implementation limits the strength of cryptographic algorithms available by default. If stronger algorithms are needed (for example, AES with 256-bit keys), the JCE Unlimited Strength Jurisdiction Policy Files must be obtained and installed in the JDK/JRE. See the JCA Providers Documentation for more information.

    The JRE/JDK will have a default pseudo-random number generator (PRNG) that is used for cryptography operations, so it is not required to configure the implementation used with the . However, there are performance issues with some implementations (notably, the default chosen on Linux systems, , utilizes a global lock). In cases where performance of SSL connections becomes an issue, consider explicitly setting the implementation to be used. The implementation is non-blocking, and has shown very good performance characteristics under heavy load (50 MB/sec of produced messages, plus replication traffic, per-broker). ssl.secure.random.implementationNativePRNGSHA1PRNG

    Once you start the broker you should be able to see in the server.log To check quickly if the server keystore and truststore are setup properly you can run the following command (Note: TLSv1 should be listed under ssl.enabled.protocols)
    In the output of this command you should see server's certificate: If the certificate does not show up or if there are any other error messages then your keystore is not setup properly.
    with addresses: PLAINTEXT -> EndPoint(192.168.64.1,9092,PLAINTEXT),SSL -> EndPoint(192.168.64.1,9093,SSL)
    > openssl s_client -debug -connect localhost:9093 -tls1
    -----BEGIN CERTIFICATE-----
    {variable sized random bytes}
    -----END CERTIFICATE-----
    subject=/C=US/ST=CA/L=Santa Clara/O=org/OU=org/CN=Sriharsha Chintalapani
    issuer=/C=US/ST=CA/L=Santa Clara/O=org/OU=org/CN=kafka/emailAddress=test@test.com
  6. Configuring Kafka Clients

    SSL is supported only for the new Kafka Producer and Consumer, the older API is not supported. The configs for SSL will be the same for both producer and consumer.
    If client authentication is not required in the broker, then the following is a minimal configuration example: Note: ssl.truststore.password is technically optional but highly recommended. If a password is not set access to the truststore is still available, but integrity checking is disabled. If client authentication is required, then a keystore must be created like in step 1 and the following must also be configured: Other configuration settings that may also be needed depending on our requirements and the broker configuration:
    security.protocol=SSL
    ssl.truststore.location=/var/private/ssl/client.truststore.jks
    ssl.truststore.password=test1234
    ssl.keystore.location=/var/private/ssl/client.keystore.jks
    ssl.keystore.password=test1234
    ssl.key.password=test1234
    1. ssl.provider (Optional). The name of the security provider used for SSL connections. Default value is the default security provider of the JVM.
    2. ssl.cipher.suites (Optional). A cipher suite is a named combination of authentication, encryption, MAC and key exchange algorithm used to negotiate the security settings for a network connection using TLS or SSL network protocol.
    3. ssl.enabled.protocols=TLSv1.2,TLSv1.1,TLSv1. It should list at least one of the protocols configured on the broker side
    4. ssl.truststore.type=JKS
    5. ssl.keystore.type=JKS

    Examples using console-producer and console-consumer:
    > kafka-console-producer.sh --bootstrap-server localhost:9093 --topic test --producer.config client-ssl.properties
    > kafka-console-consumer.sh --bootstrap-server localhost:9093 --topic test --consumer.config client-ssl.properties

7.4 Authentication using SASL

  1. JAAS configuration

    Kafka uses the Java Authentication and Authorization Service (JAAS) for SASL configuration.

    1. JAAS configuration for Kafka brokers

      KafkaServer is the section name in the JAAS file used by each KafkaServer/Broker. This section provides SASL configuration options for the broker including any SASL client connections made by the broker for inter-broker communication. If multiple listeners are configured to use SASL, the section name may be prefixed with the listener name in lower-case followed by a period, e.g. sasl_ssl.KafkaServer.

      Client section is used to authenticate a SASL connection with zookeeper. It also allows the brokers to set SASL ACL on zookeeper nodes which locks these nodes down so that only the brokers can modify it. It is necessary to have the same principal name across all brokers. If you want to use a section name other than Client, set the system property zookeeper.sasl.clientconfig to the appropriate name (e.g., -Dzookeeper.sasl.clientconfig=ZkClient).

      ZooKeeper uses "zookeeper" as the service name by default. If you want to change this, set the system property zookeeper.sasl.client.username to the appropriate name (e.g., -Dzookeeper.sasl.client.username=zk).

      Brokers may also configure JAAS using the broker configuration property . The property name must be prefixed with the listener prefix including the SASL mechanism, i.e. . Only one login module may be specified in the config value. If multiple mechanisms are configured on a listener, configs must be provided for each mechanism using the listener and mechanism prefix. For example,sasl.jaas.configlistener.name.{listenerName}.{saslMechanism}.sasl.jaas.config

      listener.name.sasl_ssl.scram-sha-256.sasl.jaas.config=org.apache.kafka.common.security.scram.ScramLoginModule required \
          username="admin" \
          password="admin-secret";
      listener.name.sasl_ssl.plain.sasl.jaas.config=org.apache.kafka.common.security.plain.PlainLoginModule required \
          username="admin" \
          password="admin-secret" \
          user_admin="admin-secret" \
          user_alice="alice-secret";
      If JAAS configuration is defined at different levels, the order of precedence used is:
      • Broker configuration property listener.name.{listenerName}.{saslMechanism}.sasl.jaas.config
      • {listenerName}.KafkaServer section of static JAAS configuration
      • KafkaServer section of static JAAS configuration
      Note that ZooKeeper JAAS config may only be configured using static JAAS configuration.

      See GSSAPI (Kerberos), PLAIN, SCRAM or OAUTHBEARER for example broker configurations.

    2. JAAS configuration for Kafka clients

      Clients may configure JAAS using the client configuration property sasl.jaas.config or using the static JAAS config file similar to brokers.

      1. JAAS configuration using client configuration property

        Clients may specify JAAS configuration as a producer or consumer property without creating a physical configuration file. This mode also enables different producers and consumers within the same JVM to use different credentials by specifying different properties for each client. If both static JAAS configuration system property and client property are specified, the client property will be used.java.security.auth.login.configsasl.jaas.config

        See GSSAPI (Kerberos), PLAIN, SCRAM or OAUTHBEARER for example configurations.

      2. JAAS configuration using static config file
        To configure SASL authentication on the clients using static JAAS config file:
        1. Add a JAAS config file with a client login section named KafkaClient. Configure a login module in KafkaClient for the selected mechanism as described in the examples for setting up GSSAPI (Kerberos), PLAIN, SCRAM or OAUTHBEARER. For example, GSSAPI credentials may be configured as:
          KafkaClient {
              com.sun.security.auth.module.Krb5LoginModule required
              useKeyTab=true
              storeKey=true
              keyTab="/etc/security/keytabs/kafka_client.keytab"
              principal="kafka-client-1@EXAMPLE.COM";
          };
        2. Pass the JAAS config file location as JVM parameter to each client JVM. For example:
          -Djava.security.auth.login.config=/etc/kafka/kafka_client_jaas.conf
  2. SASL configuration

    SASL may be used with PLAINTEXT or SSL as the transport layer using the security protocol SASL_PLAINTEXT or SASL_SSL respectively. If SASL_SSL is used, then SSL must also be configured.

    1. SASL mechanisms
      Kafka supports the following SASL mechanisms:
    2. SASL configuration for Kafka brokers
      1. Configure a SASL port in server.properties, by adding at least one of SASL_PLAINTEXT or SASL_SSL to the listeners parameter, which contains one or more comma-separated values: If you are only configuring a SASL port (or if you want the Kafka brokers to authenticate each other using SASL) then make sure you set the same SASL protocol for inter-broker communication:
        listeners=SASL_PLAINTEXT://host.name:port
        security.inter.broker.protocol=SASL_PLAINTEXT (or SASL_SSL)
      2. Select one or more supported mechanisms to enable in the broker and follow the steps to configure SASL for the mechanism. To enable multiple mechanisms in the broker, follow the steps here.
    3. SASL configuration for Kafka clients

      SASL authentication is only supported for the new Java Kafka producer and consumer, the older API is not supported.

      To configure SASL authentication on the clients, select a SASL mechanism that is enabled in the broker for client authentication and follow the steps to configure SASL for the selected mechanism.

      Note: When establishing connections to brokers via SASL, clients may perform a reverse DNS lookup of the broker address. Due to how the JRE implements reverse DNS lookups, clients may observe slow SASL handshakes if fully qualified domain names are not used, for both the client's and a broker's .bootstrap.serversadvertised.listeners

  3. Authentication using SASL/Kerberos

    1. Prerequisites
      1. Kerberos
        If your organization is already using a Kerberos server (for example, by using Active Directory), there is no need to install a new server just for Kafka. Otherwise you will need to install one, your Linux vendor likely has packages for Kerberos and a short guide on how to install and configure it (Ubuntu, Redhat). Note that if you are using Oracle Java, you will need to download JCE policy files for your Java version and copy them to $JAVA_HOME/jre/lib/security.
      2. Create Kerberos Principals
        If you are using the organization's Kerberos or Active Directory server, ask your Kerberos administrator for a principal for each Kafka broker in your cluster and for every operating system user that will access Kafka with Kerberos authentication (via clients and tools).
        If you have installed your own Kerberos, you will need to create these principals yourself using the following commands:
        > sudo /usr/sbin/kadmin.local -q 'addprinc -randkey kafka/{hostname}@{REALM}'
        > sudo /usr/sbin/kadmin.local -q "ktadd -k /etc/security/keytabs/{keytabname}.keytab kafka/{hostname}@{REALM}"
      3. Make sure all hosts can be reachable using hostnames - it is a Kerberos requirement that all your hosts can be resolved with their FQDNs.
    2. Configuring Kafka Brokers
      1. Add a suitably modified JAAS file similar to the one below to each Kafka broker's config directory, let's call it kafka_server_jaas.conf for this example (note that each broker should have its own keytab): KafkaServer section in the JAAS file tells the broker which principal to use and the location of the keytab where this principal is stored. It allows the broker to login using the keytab specified in this section. See notes for more details on Zookeeper SASL configuration.
        KafkaServer {
            com.sun.security.auth.module.Krb5LoginModule required
            useKeyTab=true
            storeKey=true
            keyTab="/etc/security/keytabs/kafka_server.keytab"
            principal="kafka/kafka1.hostname.com@EXAMPLE.COM";
        };
        
        // Zookeeper client authentication
        Client {
            com.sun.security.auth.module.Krb5LoginModule required
            useKeyTab=true
            storeKey=true
            keyTab="/etc/security/keytabs/kafka_server.keytab"
            principal="kafka/kafka1.hostname.com@EXAMPLE.COM";
        };
      2. Pass the JAAS and optionally the krb5 file locations as JVM parameters to each Kafka broker (see here for more details):
        -Djava.security.krb5.conf=/etc/kafka/krb5.conf
        -Djava.security.auth.login.config=/etc/kafka/kafka_server_jaas.conf
      3. Make sure the keytabs configured in the JAAS file are readable by the operating system user who is starting kafka broker.
      4. Configure SASL port and SASL mechanisms in server.properties as described here. For example: We must also configure the service name in server.properties, which should match the principal name of the kafka brokers. In the above example, principal is "kafka/kafka1.hostname.com@EXAMPLE.com", so:
        listeners=SASL_PLAINTEXT://host.name:port
        security.inter.broker.protocol=SASL_PLAINTEXT
        sasl.mechanism.inter.broker.protocol=GSSAPI
        sasl.enabled.mechanisms=GSSAPI
        sasl.kerberos.service.name=kafka
    3. Configuring Kafka Clients
      To configure SASL authentication on the clients:
      1. Clients (producers, consumers, connect workers, etc) will authenticate to the cluster with their own principal (usually with the same name as the user running the client), so obtain or create these principals as needed. Then configure the JAAS configuration property for each client. Different clients within a JVM may run as different users by specifying different principals. The property in producer.properties or consumer.properties describes how clients like producer and consumer can connect to the Kafka Broker. The following is an example configuration for a client using a keytab (recommended for long-running processes): For command-line utilities like kafka-console-consumer or kafka-console-producer, kinit can be used along with "useTicketCache=true" as in: JAAS configuration for clients may alternatively be specified as a JVM parameter similar to brokers as described here. Clients use the login section named KafkaClient. This option allows only one user for all client connections from a JVM.sasl.jaas.config
        sasl.jaas.config=com.sun.security.auth.module.Krb5LoginModule required \
            useKeyTab=true \
            storeKey=true  \
            keyTab="/etc/security/keytabs/kafka_client.keytab" \
            principal="kafka-client-1@EXAMPLE.COM";
        sasl.jaas.config=com.sun.security.auth.module.Krb5LoginModule required \
            useTicketCache=true;
      2. Make sure the keytabs configured in the JAAS configuration are readable by the operating system user who is starting kafka client.
      3. Optionally pass the krb5 file locations as JVM parameters to each client JVM (see here for more details):
        -Djava.security.krb5.conf=/etc/kafka/krb5.conf
      4. Configure the following properties in producer.properties or consumer.properties:
        security.protocol=SASL_PLAINTEXT (or SASL_SSL)
        sasl.mechanism=GSSAPI
        sasl.kerberos.service.name=kafka
  4. Authentication using SASL/PLAIN

    SASL/PLAIN is a simple username/password authentication mechanism that is typically used with TLS for encryption to implement secure authentication. Kafka supports a default implementation for SASL/PLAIN which can be extended for production use as described here.

    Under the default implementation of , the username is used as the authenticated for configuration of ACLs etc. principal.builder.classPrincipal
    1. Configuring Kafka Brokers
      1. Add a suitably modified JAAS file similar to the one below to each Kafka broker's config directory, let's call it kafka_server_jaas.conf for this example: This configuration defines two users (admin and alice). The properties username and password in the KafkaServer section are used by the broker to initiate connections to other brokers. In this example, admin is the user for inter-broker communication. The set of properties user_userName defines the passwords for all users that connect to the broker and the broker validates all client connections including those from other brokers using these properties.
        KafkaServer {
            org.apache.kafka.common.security.plain.PlainLoginModule required
            username="admin"
            password="admin-secret"
            user_admin="admin-secret"
            user_alice="alice-secret";
        };
      2. Pass the JAAS config file location as JVM parameter to each Kafka broker:
        -Djava.security.auth.login.config=/etc/kafka/kafka_server_jaas.conf
      3. Configure SASL port and SASL mechanisms in server.properties as described here. For example:
        listeners=SASL_SSL://host.name:port
        security.inter.broker.protocol=SASL_SSL
        sasl.mechanism.inter.broker.protocol=PLAIN
        sasl.enabled.mechanisms=PLAIN
    2. Configuring Kafka Clients
      To configure SASL authentication on the clients:
      1. Configure the JAAS configuration property for each client in producer.properties or consumer.properties. The login module describes how the clients like producer and consumer can connect to the Kafka Broker. The following is an example configuration for a client for the PLAIN mechanism:
        sasl.jaas.config=org.apache.kafka.common.security.plain.PlainLoginModule required \
            username="alice" \
            password="alice-secret";

        The options username and password are used by clients to configure the user for client connections. In this example, clients connect to the broker as user alice. Different clients within a JVM may connect as different users by specifying different user names and passwords in .sasl.jaas.config

        JAAS configuration for clients may alternatively be specified as a JVM parameter similar to brokers as described here. Clients use the login section named KafkaClient. This option allows only one user for all client connections from a JVM.

      2. Configure the following properties in producer.properties or consumer.properties:
        security.protocol=SASL_SSL
        sasl.mechanism=PLAIN
    3. Use of SASL/PLAIN in production
      • SASL/PLAIN should be used only with SSL as transport layer to ensure that clear passwords are not transmitted on the wire without encryption.
      • The default implementation of SASL/PLAIN in Kafka specifies usernames and passwords in the JAAS configuration file as shown here. From Kafka version 2.0 onwards, you can avoid storing clear passwords on disk by configuring your own callback handlers that obtain username and password from an external source using the configuration options and .sasl.server.callback.handler.classsasl.client.callback.handler.class
      • In production systems, external authentication servers may implement password authentication. From Kafka version 2.0 onwards, you can plug in your own callback handlers that use external authentication servers for password verification by configuring .sasl.server.callback.handler.class
  5. Authentication using SASL/SCRAM

    Salted Challenge Response Authentication Mechanism (SCRAM) is a family of SASL mechanisms that addresses the security concerns with traditional mechanisms that perform username/password authentication like PLAIN and DIGEST-MD5. The mechanism is defined in RFC 5802. Kafka supports SCRAM-SHA-256 and SCRAM-SHA-512 which can be used with TLS to perform secure authentication. Under the default implementation of , the username is used as the authenticated for configuration of ACLs etc. The default SCRAM implementation in Kafka stores SCRAM credentials in Zookeeper and is suitable for use in Kafka installations where Zookeeper is on a private network. Refer to Security Considerations for more details.principal.builder.classPrincipal

    1. Creating SCRAM Credentials

      The SCRAM implementation in Kafka uses Zookeeper as credential store. Credentials can be created in Zookeeper using kafka-configs.sh. For each SCRAM mechanism enabled, credentials must be created by adding a config with the mechanism name. Credentials for inter-broker communication must be created before Kafka brokers are started. Client credentials may be created and updated dynamically and updated credentials will be used to authenticate new connections.

      Create SCRAM credentials for user alice with password alice-secret:

      > bin/kafka-configs.sh --zookeeper localhost:2182 --zk-tls-config-file zk_tls_config.properties --alter --add-config 'SCRAM-SHA-256=[iterations=8192,password=alice-secret],SCRAM-SHA-512=[password=alice-secret]' --entity-type users --entity-name alice

      The default iteration count of 4096 is used if iterations are not specified. A random salt is created and the SCRAM identity consisting of salt, iterations, StoredKey and ServerKey are stored in Zookeeper. See RFC 5802 for details on SCRAM identity and the individual fields.

      The following examples also require a user admin for inter-broker communication which can be created using:

      > bin/kafka-configs.sh --zookeeper localhost:2182 --zk-tls-config-file zk_tls_config.properties --alter --add-config 'SCRAM-SHA-256=[password=admin-secret],SCRAM-SHA-512=[password=admin-secret]' --entity-type users --entity-name admin

      Existing credentials may be listed using the --describe option:

      > bin/kafka-configs.sh --zookeeper localhost:2182 --zk-tls-config-file zk_tls_config.properties --describe --entity-type users --entity-name alice

      Credentials may be deleted for one or more SCRAM mechanisms using the --alter --delete-config option:

      > bin/kafka-configs.sh --zookeeper localhost:2182 --zk-tls-config-file zk_tls_config.properties --alter --delete-config 'SCRAM-SHA-512' --entity-type users --entity-name alice
    2. Configuring Kafka Brokers
      1. Add a suitably modified JAAS file similar to the one below to each Kafka broker's config directory, let's call it kafka_server_jaas.conf for this example: The properties username and password in the KafkaServer section are used by the broker to initiate connections to other brokers. In this example, admin is the user for inter-broker communication.
        KafkaServer {
            org.apache.kafka.common.security.scram.ScramLoginModule required
            username="admin"
            password="admin-secret";
        };
      2. Pass the JAAS config file location as JVM parameter to each Kafka broker:
        -Djava.security.auth.login.config=/etc/kafka/kafka_server_jaas.conf
      3. Configure SASL port and SASL mechanisms in server.properties as described here. For example:
        listeners=SASL_SSL://host.name:port
        security.inter.broker.protocol=SASL_SSL
        sasl.mechanism.inter.broker.protocol=SCRAM-SHA-256 (or SCRAM-SHA-512)
        sasl.enabled.mechanisms=SCRAM-SHA-256 (or SCRAM-SHA-512)
    3. Configuring Kafka Clients
      To configure SASL authentication on the clients:
      1. Configure the JAAS configuration property for each client in producer.properties or consumer.properties. The login module describes how the clients like producer and consumer can connect to the Kafka Broker. The following is an example configuration for a client for the SCRAM mechanisms:
        sasl.jaas.config=org.apache.kafka.common.security.scram.ScramLoginModule required \
            username="alice" \
            password="alice-secret";

        The options username and password are used by clients to configure the user for client connections. In this example, clients connect to the broker as user alice. Different clients within a JVM may connect as different users by specifying different user names and passwords in .sasl.jaas.config

        JAAS configuration for clients may alternatively be specified as a JVM parameter similar to brokers as described here. Clients use the login section named KafkaClient. This option allows only one user for all client connections from a JVM.

      2. Configure the following properties in producer.properties or consumer.properties:
        security.protocol=SASL_SSL
        sasl.mechanism=SCRAM-SHA-256 (or SCRAM-SHA-512)
    4. Security Considerations for SASL/SCRAM
      • The default implementation of SASL/SCRAM in Kafka stores SCRAM credentials in Zookeeper. This is suitable for production use in installations where Zookeeper is secure and on a private network.
      • Kafka supports only the strong hash functions SHA-256 and SHA-512 with a minimum iteration count of 4096. Strong hash functions combined with strong passwords and high iteration counts protect against brute force attacks if Zookeeper security is compromised.
      • SCRAM should be used only with TLS-encryption to prevent interception of SCRAM exchanges. This protects against dictionary or brute force attacks and against impersonation if Zookeeper is compromised.
      • From Kafka version 2.0 onwards, the default SASL/SCRAM credential store may be overridden using custom callback handlers by configuring in installations where Zookeeper is not secure.sasl.server.callback.handler.class
      • For more details on security considerations, refer to RFC 5802.
  6. Authentication using SASL/OAUTHBEARER

    The OAuth 2 Authorization Framework "enables a third-party application to obtain limited access to an HTTP service, either on behalf of a resource owner by orchestrating an approval interaction between the resource owner and the HTTP service, or by allowing the third-party application to obtain access on its own behalf." The SASL OAUTHBEARER mechanism enables the use of the framework in a SASL (i.e. a non-HTTP) context; it is defined in RFC 7628. The default OAUTHBEARER implementation in Kafka creates and validates Unsecured JSON Web Tokens and is only suitable for use in non-production Kafka installations. Refer to Security Considerations for more details.

    Under the default implementation of , the principalName of OAuthBearerToken is used as the authenticated for configuration of ACLs etc. principal.builder.classPrincipal
    1. Configuring Kafka Brokers
      1. Add a suitably modified JAAS file similar to the one below to each Kafka broker's config directory, let's call it kafka_server_jaas.conf for this example: The property unsecuredLoginStringClaim_sub in the KafkaServer section is used by the broker when it initiates connections to other brokers. In this example, admin will appear in the subject (sub) claim and will be the user for inter-broker communication.
        KafkaServer {
            org.apache.kafka.common.security.oauthbearer.OAuthBearerLoginModule required
            unsecuredLoginStringClaim_sub="admin";
        };
      2. Pass the JAAS config file location as JVM parameter to each Kafka broker:
        -Djava.security.auth.login.config=/etc/kafka/kafka_server_jaas.conf
      3. Configure SASL port and SASL mechanisms in server.properties as described here. For example:
        listeners=SASL_SSL://host.name:port (or SASL_PLAINTEXT if non-production)
        security.inter.broker.protocol=SASL_SSL (or SASL_PLAINTEXT if non-production)
        sasl.mechanism.inter.broker.protocol=OAUTHBEARER
        sasl.enabled.mechanisms=OAUTHBEARER
    2. Configuring Kafka Clients
      To configure SASL authentication on the clients:
      1. Configure the JAAS configuration property for each client in producer.properties or consumer.properties. The login module describes how the clients like producer and consumer can connect to the Kafka Broker. The following is an example configuration for a client for the OAUTHBEARER mechanisms:
        sasl.jaas.config=org.apache.kafka.common.security.oauthbearer.OAuthBearerLoginModule required \
            unsecuredLoginStringClaim_sub="alice";

        The option unsecuredLoginStringClaim_sub is used by clients to configure the subject (sub) claim, which determines the user for client connections. In this example, clients connect to the broker as user alice. Different clients within a JVM may connect as different users by specifying different subject (sub) claims in .sasl.jaas.config

        JAAS configuration for clients may alternatively be specified as a JVM parameter similar to brokers as described here. Clients use the login section named KafkaClient. This option allows only one user for all client connections from a JVM.

      2. Configure the following properties in producer.properties or consumer.properties:
        security.protocol=SASL_SSL (or SASL_PLAINTEXT if non-production)
        sasl.mechanism=OAUTHBEARER
      3. The default implementation of SASL/OAUTHBEARER depends on the jackson-databind library. Since it's an optional dependency, users have to configure it as a dependency via their build tool.
    3. Unsecured Token Creation Options for SASL/OAUTHBEARER
      • The default implementation of SASL/OAUTHBEARER in Kafka creates and validates Unsecured JSON Web Tokens. While suitable only for non-production use, it does provide the flexibility to create arbitrary tokens in a DEV or TEST environment.
      • Here are the various supported JAAS module options on the client side (and on the broker side if OAUTHBEARER is the inter-broker protocol):
        JAAS Module Option for Unsecured Token Creation Documentation
        unsecuredLoginStringClaim_<claimname>="value" Creates a String claim with the given name and value. Any valid claim name can be specified except 'iat' and 'exp' (these are automatically generated).
        unsecuredLoginNumberClaim_<claimname>="value" Creates a Number claim with the given name and value. Any valid claim name can be specified except 'iat' and 'exp' (these are automatically generated).
        unsecuredLoginListClaim_<claimname>="value" Creates a String List claim with the given name and values parsed from the given value where the first character is taken as the delimiter. For example: unsecuredLoginListClaim_fubar="|value1|value2". Any valid claim name can be specified except 'iat' and 'exp' (these are automatically generated).
        unsecuredLoginExtension_<extensionname>="value" Creates a String extension with the given name and value. For example: unsecuredLoginExtension_traceId="123". A valid extension name is any sequence of lowercase or uppercase alphabet characters. In addition, the "auth" extension name is reserved. A valid extension value is any combination of characters with ASCII codes 1-127.
        unsecuredLoginPrincipalClaimName Set to a custom claim name if you wish the name of the String claim holding the principal name to be something other than 'sub'.
        unsecuredLoginLifetimeSeconds Set to an integer value if the token expiration is to be set to something other than the default value of 3600 seconds (which is 1 hour). The 'exp' claim will be set to reflect the expiration time.
        unsecuredLoginScopeClaimName Set to a custom claim name if you wish the name of the String or String List claim holding any token scope to be something other than 'scope'.
    4. Unsecured Token Validation Options for SASL/OAUTHBEARER
      • Here are the various supported JAAS module options on the broker side for Unsecured JSON Web Token validation:
        JAAS Module Option for Unsecured Token Validation Documentation
        unsecuredValidatorPrincipalClaimName="value" Set to a non-empty value if you wish a particular String claim holding a principal name to be checked for existence; the default is to check for the existence of the 'sub' claim.
        unsecuredValidatorScopeClaimName="value" Set to a custom claim name if you wish the name of the String or String List claim holding any token scope to be something other than 'scope'.
        unsecuredValidatorRequiredScope="value" Set to a space-delimited list of scope values if you wish the String/String List claim holding the token scope to be checked to make sure it contains certain values.
        unsecuredValidatorAllowableClockSkewMs="value" Set to a positive integer value if you wish to allow up to some number of positive milliseconds of clock skew (the default is 0).
      • The default unsecured SASL/OAUTHBEARER implementation may be overridden (and must be overridden in production environments) using custom login and SASL Server callback handlers.
      • For more details on security considerations, refer to RFC 6749, Section 10.
    5. Token Refresh for SASL/OAUTHBEARER
      Kafka periodically refreshes any token before it expires so that the client can continue to make connections to brokers. The parameters that impact how the refresh algorithm operates are specified as part of the producer/consumer/broker configuration and are as follows. See the documentation for these properties elsewhere for details. The default values are usually reasonable, in which case these configuration parameters would not need to be explicitly set.
      Producer/Consumer/Broker Configuration Property
      sasl.login.refresh.window.factor
      sasl.login.refresh.window.jitter
      sasl.login.refresh.min.period.seconds
      sasl.login.refresh.min.buffer.seconds
    6. Secure/Production Use of SASL/OAUTHBEARER
      Production use cases will require writing an implementation of org.apache.kafka.common.security.auth.AuthenticateCallbackHandler that can handle an instance of org.apache.kafka.common.security.oauthbearer.OAuthBearerTokenCallback and declaring it via either the sasl.login.callback.handler.class configuration option for a non-broker client or via the listener.name.sasl_ssl.oauthbearer.sasl.login.callback.handler.class configuration option for brokers (when SASL/OAUTHBEARER is the inter-broker protocol).

      Production use cases will also require writing an implementation of org.apache.kafka.common.security.auth.AuthenticateCallbackHandler that can handle an instance of org.apache.kafka.common.security.oauthbearer.OAuthBearerValidatorCallback and declaring it via the listener.name.sasl_ssl.oauthbearer.sasl.server.callback.handler.class broker configuration option.

    7. Security Considerations for SASL/OAUTHBEARER
      • The default implementation of SASL/OAUTHBEARER in Kafka creates and validates Unsecured JSON Web Tokens. This is suitable only for non-production use.
      • OAUTHBEARER should be used in production enviromnments only with TLS-encryption to prevent interception of tokens.
      • The default unsecured SASL/OAUTHBEARER implementation may be overridden (and must be overridden in production environments) using custom login and SASL Server callback handlers as described above.
      • For more details on OAuth 2 security considerations in general, refer to RFC 6749, Section 10.
  7. Enabling multiple SASL mechanisms in a broker

    1. Specify configuration for the login modules of all enabled mechanisms in the KafkaServer section of the JAAS config file. For example:
      KafkaServer {
          com.sun.security.auth.module.Krb5LoginModule required
          useKeyTab=true
          storeKey=true
          keyTab="/etc/security/keytabs/kafka_server.keytab"
          principal="kafka/kafka1.hostname.com@EXAMPLE.COM";
      
          org.apache.kafka.common.security.plain.PlainLoginModule required
          username="admin"
          password="admin-secret"
          user_admin="admin-secret"
          user_alice="alice-secret";
      };
    2. Enable the SASL mechanisms in server.properties:
      sasl.enabled.mechanisms=GSSAPI,PLAIN,SCRAM-SHA-256,SCRAM-SHA-512,OAUTHBEARER
    3. Specify the SASL security protocol and mechanism for inter-broker communication in server.properties if required:
      security.inter.broker.protocol=SASL_PLAINTEXT (or SASL_SSL)
      sasl.mechanism.inter.broker.protocol=GSSAPI (or one of the other enabled mechanisms)
    4. Follow the mechanism-specific steps in GSSAPI (Kerberos), PLAIN, SCRAM and OAUTHBEARER to configure SASL for the enabled mechanisms.
  8. Modifying SASL mechanism in a Running Cluster

    SASL mechanism can be modified in a running cluster using the following sequence:

    1. Enable new SASL mechanism by adding the mechanism to sasl.enabled.mechanisms in server.properties for each broker. Update JAAS config file to include both mechanisms as described here. Incrementally bounce the cluster nodes.
    2. Restart clients using the new mechanism.
    3. To change the mechanism of inter-broker communication (if this is required), set sasl.mechanism.inter.broker.protocol in server.properties to the new mechanism and incrementally bounce the cluster again.
    4. To remove old mechanism (if this is required), remove the old mechanism from sasl.enabled.mechanisms in server.properties and remove the entries for the old mechanism from JAAS config file. Incrementally bounce the cluster again.
  9. Authentication using Delegation Tokens

    Delegation token based authentication is a lightweight authentication mechanism to complement existing SASL/SSL methods. Delegation tokens are shared secrets between kafka brokers and clients. Delegation tokens will help processing frameworks to distribute the workload to available workers in a secure environment without the added cost of distributing Kerberos TGT/keytabs or keystores when 2-way SSL is used. See KIP-48 for more details.

    Under the default implementation of , the owner of delegation token is used as the authenticated for configuration of ACLs etc. principal.builder.classPrincipal

    Typical steps for delegation token usage are:

    1. User authenticates with the Kafka cluster via SASL or SSL, and obtains a delegation token. This can be done using Admin APIs or using kafka-delegation-tokens.sh script.
    2. User securely passes the delegation token to Kafka clients for authenticating with the Kafka cluster.
    3. Token owner/renewer can renew/expire the delegation tokens.
    1. Token Management

      A secret is used to generate and verify delegation tokens. This is supplied using config option delegation.token.secret.key. The same secret key must be configured across all the brokers. If the secret is not set or set to empty string, brokers will disable the delegation token authentication.

      In the current implementation, token details are stored in Zookeeper and is suitable for use in Kafka installations where Zookeeper is on a private network. Also currently, this secret is stored as plain text in the server.properties config file. We intend to make these configurable in a future Kafka release.

      A token has a current life, and a maximum renewable life. By default, tokens must be renewed once every 24 hours for up to 7 days. These can be configured using delegation.token.expiry.time.ms and delegation.token.max.lifetime.ms config options.

      Tokens can also be cancelled explicitly. If a token is not renewed by the token’s expiration time or if token is beyond the max life time, it will be deleted from all broker caches as well as from zookeeper.

    2. Creating Delegation Tokens

      Tokens can be created by using Admin APIs or using kafka-delegation-tokens.sh script. Delegation token requests (create/renew/expire/describe) should be issued only on SASL or SSL authenticated channels. Tokens can not be requests if the initial authentication is done through delegation token. A token can be created by the user for that user or others as well by specifying the --owner-principal parameter. Owner/Renewers can renew or expire tokens. Owner/renewers can always describe their own tokens. To describe other tokens, a DESCRIBE_TOKEN permission needs to be added on the User resource representing the owner of the token. kafka-delegation-tokens.sh script examples are given below.

      Create a delegation token:

      > bin/kafka-delegation-tokens.sh --bootstrap-server localhost:9092 --create   --max-life-time-period -1 --command-config client.properties --renewer-principal User:user1

      Create a delegation token for a different owner:

      > bin/kafka-delegation-tokens.sh --bootstrap-server localhost:9092 --create   --max-life-time-period -1 --command-config client.properties --renewer-principal User:user1 --owner-principal User:owner1

      Renew a delegation token:

      > bin/kafka-delegation-tokens.sh --bootstrap-server localhost:9092 --renew    --renew-time-period -1 --command-config client.properties --hmac ABCDEFGHIJK

      Expire a delegation token:

      > bin/kafka-delegation-tokens.sh --bootstrap-server localhost:9092 --expire   --expiry-time-period -1   --command-config client.properties  --hmac ABCDEFGHIJK

      Existing tokens can be described using the --describe option:

      > bin/kafka-delegation-tokens.sh --bootstrap-server localhost:9092 --describe --command-config client.properties  --owner-principal User:user1
    3. Token Authentication

      Delegation token authentication piggybacks on the current SASL/SCRAM authentication mechanism. We must enable SASL/SCRAM mechanism on Kafka cluster as described in here.

      Configuring Kafka Clients:

      1. Configure the JAAS configuration property for each client in producer.properties or consumer.properties. The login module describes how the clients like producer and consumer can connect to the Kafka Broker. The following is an example configuration for a client for the token authentication:
        sasl.jaas.config=org.apache.kafka.common.security.scram.ScramLoginModule required \
            username="tokenID123" \
            password="lAYYSFmLs4bTjf+lTZ1LCHR/ZZFNA==" \
            tokenauth="true";

        The options username and password are used by clients to configure the token id and token HMAC. And the option tokenauth is used to indicate the server about token authentication. In this example, clients connect to the broker using token id: tokenID123. Different clients within a JVM may connect using different tokens by specifying different token details in .sasl.jaas.config

        JAAS configuration for clients may alternatively be specified as a JVM parameter similar to brokers as described here. Clients use the login section named KafkaClient. This option allows only one user for all client connections from a JVM.

    4. Procedure to manually rotate the secret:

      We require a re-deployment when the secret needs to be rotated. During this process, already connected clients will continue to work. But any new connection requests and renew/expire requests with old tokens can fail. Steps are given below.

      1. Expire all existing tokens.
      2. Rotate the secret by rolling upgrade, and
      3. Generate new tokens

      We intend to automate this in a future Kafka release.

7.5 Authorization and ACLs

Kafka ships with a pluggable authorization framework, which is configured with the authorizer.class.name property in the server confgiuration. Configured implementations must extend . Kafka provides default implementations which store ACLs in the cluster metadata (either Zookeeper or the KRaft metadata log). For Zookeeper-based clusters, the provided implementation is configured as follows: For KRaft clusters, use the following configuration on all nodes (brokers, controllers, or combined broker/controller nodes): Kafka ACLs are defined in the general format of "Principal {P} is [Allowed|Denied] Operation {O} From Host {H} on any Resource {R} matching ResourcePattern {RP}". You can read more about the ACL structure in KIP-11 and resource patterns in KIP-290. In order to add, remove, or list ACLs, you can use the Kafka ACL CLI . By default, if no ResourcePatterns match a specific Resource R, then R has no associated ACLs, and therefore no one other than super users is allowed to access R. If you want to change that behavior, you can include the following in server.properties. One can also add super users in server.properties like the following (note that the delimiter is semicolon since SSL user names may contain comma). Default PrincipalType string "User" is case sensitive. org.apache.kafka.server.authorizer.Authorizer
authorizer.class.name=kafka.security.authorizer.AclAuthorizer
authorizer.class.name=org.apache.kafka.metadata.authorizer.StandardAuthorizer
kafka-acls.sh
allow.everyone.if.no.acl.found=true
super.users=User:Bob;User:Alice
KRaft Principal Forwarding
In KRaft clusters, admin requests such as and are sent to the broker listeners by the client. The broker then forwards the request to the active controller through the first listener configured in . Authorization of these requests is done on the controller node. This is achieved by way of an request which packages both the underlying request from the client as well as the client principal. When the controller receives the forwarded request from the broker, it first authorizes the request using the authenticated broker principal. Then it authorizes the underlying request using the forwarded principal.
All of this implies that Kafka must understand how to serialize and deserialize the client principal. The authentication framework allows for customized principals by overriding the configuration. In order for customized principals to work with KRaft, the configured class must implement so that Kafka knows how to serialize and deserialize the principals. The default implementation uses the Kafka RPC format defined in the source code: . For more detail about request forwarding in KRaft, see KIP-590
CreateTopicsDeleteTopicscontroller.listener.namesEnvelopeEnvelopeEnvelopeprincipal.builder.classorg.apache.kafka.common.security.auth.KafkaPrincipalSerdeorg.apache.kafka.common.security.authenticator.DefaultKafkaPrincipalBuilderclients/src/main/resources/common/message/DefaultPrincipalData.json
Customizing SSL User Name
By default, the SSL user name will be of the form "CN=writeuser,OU=Unknown,O=Unknown,L=Unknown,ST=Unknown,C=Unknown". One can change that by setting to a customized rule in server.properties. This config allows a list of rules for mapping X.500 distinguished name to short name. The rules are evaluated in order and the first rule that matches a distinguished name is used to map it to a short name. Any later rules in the list are ignored.
The format of is a list where each rule starts with "RULE:" and contains an expression as the following formats. Default rule will return string representation of the X.500 certificate distinguished name. If the distinguished name matches the pattern, then the replacement command will be run over the name. This also supports lowercase/uppercase options, to force the translated result to be all lower/uppercase case. This is done by adding a "/L" or "/U' to the end of the rule. Example values are: Above rules translate distinguished name "CN=serviceuser,OU=ServiceUsers,O=Unknown,L=Unknown,ST=Unknown,C=Unknown" to "serviceuser" and "CN=adminUser,OU=Admin,O=Unknown,L=Unknown,ST=Unknown,C=Unknown" to "adminuser@admin".
For advanced use cases, one can customize the name by setting a customized PrincipalBuilder in server.properties like the following.
ssl.principal.mapping.rulesssl.principal.mapping.rules
RULE:pattern/replacement/
RULE:pattern/replacement/[LU]
ssl.principal.mapping.rules
RULE:^CN=(.*?),OU=ServiceUsers.*$/$1/,
RULE:^CN=(.*?),OU=(.*?),O=(.*?),L=(.*?),ST=(.*?),C=(.*?)$/$1@$2/L,
RULE:^.*[Cc][Nn]=([a-zA-Z0-9.]*).*$/$1/L,
DEFAULT
principal.builder.class=CustomizedPrincipalBuilderClass
Customizing SASL User Name
By default, the SASL user name will be the primary part of the Kerberos principal. One can change that by setting to a customized rule in server.properties. The format of is a list where each rule works in the same way as the auth_to_local in Kerberos configuration file (krb5.conf). This also support additional lowercase/uppercase rule, to force the translated result to be all lowercase/uppercase. This is done by adding a "/L" or "/U" to the end of the rule. check below formats for syntax. Each rules starts with RULE: and contains an expression as the following formats. See the kerberos documentation for more details. An example of adding a rule to properly translate user@MYDOMAIN.COM to user while also keeping the default rule in place is: sasl.kerberos.principal.to.local.rulessasl.kerberos.principal.to.local.rules
RULE:[n:string](regexp)s/pattern/replacement/
RULE:[n:string](regexp)s/pattern/replacement/g
RULE:[n:string](regexp)s/pattern/replacement//L
RULE:[n:string](regexp)s/pattern/replacement/g/L
RULE:[n:string](regexp)s/pattern/replacement//U
RULE:[n:string](regexp)s/pattern/replacement/g/U
sasl.kerberos.principal.to.local.rules=RULE:[1:$1@$0](.*@MYDOMAIN.COM)s/@.*//,DEFAULT

Command Line Interface

Kafka Authorization management CLI can be found under bin directory with all the other CLIs. The CLI script is called kafka-acls.sh. Following lists all the options that the script supports:

Option Description Default Option type
--add Indicates to the script that user is trying to add an acl. Action
--remove Indicates to the script that user is trying to remove an acl. Action
--list Indicates to the script that user is trying to list acls. Action
--bootstrap-server A list of host/port pairs to use for establishing the connection to the Kafka cluster. Only one of --bootstrap-server or --authorizer option must be specified. Configuration
--command-config A property file containing configs to be passed to Admin Client. This option can only be used with --bootstrap-server option. Configuration
--cluster Indicates to the script that the user is trying to interact with acls on the singular cluster resource. ResourcePattern
--topic [topic-name] Indicates to the script that the user is trying to interact with acls on topic resource pattern(s). ResourcePattern
--group [group-name] Indicates to the script that the user is trying to interact with acls on consumer-group resource pattern(s) ResourcePattern
--transactional-id [transactional-id] The transactionalId to which ACLs should be added or removed. A value of * indicates the ACLs should apply to all transactionalIds. ResourcePattern
--delegation-token [delegation-token] Delegation token to which ACLs should be added or removed. A value of * indicates ACL should apply to all tokens. ResourcePattern
--user-principal [user-principal] A user resource to which ACLs should be added or removed. This is currently supported in relation with delegation tokens. A value of * indicates ACL should apply to all users. ResourcePattern
--resource-pattern-type [pattern-type] Indicates to the script the type of resource pattern, (for --add), or resource pattern filter, (for --list and --remove), the user wishes to use.
When adding acls, this should be a specific pattern type, e.g. 'literal' or 'prefixed'.
When listing or removing acls, a specific pattern type filter can be used to list or remove acls from a specific type of resource pattern, or the filter values of 'any' or 'match' can be used, where 'any' will match any pattern type, but will match the resource name exactly, and 'match' will perform pattern matching to list or remove all acls that affect the supplied resource(s).
WARNING: 'match', when used in combination with the '--remove' switch, should be used with care.
literal Configuration
--allow-principal Principal is in PrincipalType:name format that will be added to ACL with Allow permission. Default PrincipalType string "User" is case sensitive.
You can specify multiple --allow-principal in a single command.
Principal
--deny-principal Principal is in PrincipalType:name format that will be added to ACL with Deny permission. Default PrincipalType string "User" is case sensitive.
You can specify multiple --deny-principal in a single command.
Principal
--principal Principal is in PrincipalType:name format that will be used along with --list option. Default PrincipalType string "User" is case sensitive. This will list the ACLs for the specified principal.
You can specify multiple --principal in a single command.
Principal
--allow-host IP address from which principals listed in --allow-principal will have access. if --allow-principal is specified defaults to * which translates to "all hosts" Host
--deny-host IP address from which principals listed in --deny-principal will be denied access. if --deny-principal is specified defaults to * which translates to "all hosts" Host
--operation Operation that will be allowed or denied.
Valid values are:
  • Read
  • Write
  • Create
  • Delete
  • Alter
  • Describe
  • ClusterAction
  • DescribeConfigs
  • AlterConfigs
  • IdempotentWrite
  • CreateTokens
  • DescribeTokens
  • All
All Operation
--producer Convenience option to add/remove acls for producer role. This will generate acls that allows WRITE, DESCRIBE and CREATE on topic. Convenience
--consumer Convenience option to add/remove acls for consumer role. This will generate acls that allows READ, DESCRIBE on topic and READ on consumer-group. Convenience
--idempotent Enable idempotence for the producer. This should be used in combination with the --producer option.
Note that idempotence is enabled automatically if the producer is authorized to a particular transactional-id.
Convenience
--force Convenience option to assume yes to all queries and do not prompt. Convenience
--authorizer (DEPRECATED: not supported in KRaft) Fully qualified class name of the authorizer. kafka.security.authorizer.AclAuthorizer Configuration
--authorizer-properties (DEPRECATED: not supported in KRaft) key=val pairs that will be passed to authorizer for initialization. For the default authorizer in ZK clsuters, the example values are: zookeeper.connect=localhost:2181 Configuration
--zk-tls-config-file (DEPRECATED: not supported in KRaft) Identifies the file where ZooKeeper client TLS connectivity properties for the authorizer are defined. Any properties other than the following (with or without an "authorizer." prefix) are ignored: zookeeper.clientCnxnSocket, zookeeper.ssl.cipher.suites, zookeeper.ssl.client.enable, zookeeper.ssl.crl.enable, zookeeper.ssl.enabled.protocols, zookeeper.ssl.endpoint.identification.algorithm, zookeeper.ssl.keystore.location, zookeeper.ssl.keystore.password, zookeeper.ssl.keystore.type, zookeeper.ssl.ocsp.enable, zookeeper.ssl.protocol, zookeeper.ssl.truststore.location, zookeeper.ssl.truststore.password, zookeeper.ssl.truststore.type Configuration

Examples

  • Adding Acls
    Suppose you want to add an acl "Principals User:Bob and User:Alice are allowed to perform Operation Read and Write on Topic Test-Topic from IP 198.51.100.0 and IP 198.51.100.1". You can do that by executing the CLI with following options: By default, all principals that don't have an explicit acl that allows access for an operation to a resource are denied. In rare cases where an allow acl is defined that allows access to all but some principal we will have to use the --deny-principal and --deny-host option. For example, if we want to allow all users to Read from Test-topic but only deny User:BadBob from IP 198.51.100.3 we can do so using following commands: Note that and only support IP addresses (hostnames are not supported). Above examples add acls to a topic by specifying --topic [topic-name] as the resource pattern option. Similarly user can add acls to cluster by specifying --cluster and to a consumer group by specifying --group [group-name]. You can add acls on any resource of a certain type, e.g. suppose you wanted to add an acl "Principal User:Peter is allowed to produce to any Topic from IP 198.51.200.0" You can do that by using the wildcard resource '*', e.g. by executing the CLI with following options: You can add acls on prefixed resource patterns, e.g. suppose you want to add an acl "Principal User:Jane is allowed to produce to any Topic whose name starts with 'Test-' from any host". You can do that by executing the CLI with following options: Note, --resource-pattern-type defaults to 'literal', which only affects resources with the exact same name or, in the case of the wildcard resource name '*', a resource with any name.
    > bin/kafka-acls.sh --bootstrap-server localhost:9092 --add --allow-principal User:Bob --allow-principal User:Alice --allow-host 198.51.100.0 --allow-host 198.51.100.1 --operation Read --operation Write --topic Test-topic
    > bin/kafka-acls.sh --bootstrap-server localhost:9092 --add --allow-principal User:'*' --allow-host '*' --deny-principal User:BadBob --deny-host 198.51.100.3 --operation Read --topic Test-topic
    --allow-host--deny-host
    > bin/kafka-acls.sh --bootstrap-server localhost:9092 --add --allow-principal User:Peter --allow-host 198.51.200.1 --producer --topic '*'
    > bin/kafka-acls.sh --bootstrap-server localhost:9092 --add --allow-principal User:Jane --producer --topic Test- --resource-pattern-type prefixed
  • Removing Acls
    Removing acls is pretty much the same. The only difference is instead of --add option users will have to specify --remove option. To remove the acls added by the first example above we can execute the CLI with following options: If you want to remove the acl added to the prefixed resource pattern above we can execute the CLI with following options:
    > bin/kafka-acls.sh --bootstrap-server localhost:9092 --remove --allow-principal User:Bob --allow-principal User:Alice --allow-host 198.51.100.0 --allow-host 198.51.100.1 --operation Read --operation Write --topic Test-topic 
    > bin/kafka-acls.sh --bootstrap-server localhost:9092 --remove --allow-principal User:Jane --producer --topic Test- --resource-pattern-type Prefixed
  • List Acls
    We can list acls for any resource by specifying the --list option with the resource. To list all acls on the literal resource pattern Test-topic, we can execute the CLI with following options: However, this will only return the acls that have been added to this exact resource pattern. Other acls can exist that affect access to the topic, e.g. any acls on the topic wildcard '*', or any acls on prefixed resource patterns. Acls on the wildcard resource pattern can be queried explicitly: However, it is not necessarily possible to explicitly query for acls on prefixed resource patterns that match Test-topic as the name of such patterns may not be known. We can list all acls affecting Test-topic by using '--resource-pattern-type match', e.g. This will list acls on all matching literal, wildcard and prefixed resource patterns.
    > bin/kafka-acls.sh --bootstrap-server localhost:9092 --list --topic Test-topic
    > bin/kafka-acls.sh --bootstrap-server localhost:9092 --list --topic '*'
    > bin/kafka-acls.sh --bootstrap-server localhost:9092 --list --topic Test-topic --resource-pattern-type match
  • Adding or removing a principal as producer or consumer
    The most common use case for acl management are adding/removing a principal as producer or consumer so we added convenience options to handle these cases. In order to add User:Bob as a producer of Test-topic we can execute the following command: Similarly to add Alice as a consumer of Test-topic with consumer group Group-1 we just have to pass --consumer option: Note that for consumer option we must also specify the consumer group. In order to remove a principal from producer or consumer role we just need to pass --remove option.
    > bin/kafka-acls.sh --bootstrap-server localhost:9092 --add --allow-principal User:Bob --producer --topic Test-topic
    > bin/kafka-acls.sh --bootstrap-server localhost:9092 --add --allow-principal User:Bob --consumer --topic Test-topic --group Group-1 
  • Admin API based acl management
    Users having Alter permission on ClusterResource can use Admin API for ACL management. kafka-acls.sh script supports AdminClient API to manage ACLs without interacting with zookeeper/authorizer directly. All the above examples can be executed by using --bootstrap-server option. For example:
    bin/kafka-acls.sh --bootstrap-server localhost:9092 --command-config /tmp/adminclient-configs.conf --add --allow-principal User:Bob --producer --topic Test-topic
    bin/kafka-acls.sh --bootstrap-server localhost:9092 --command-config /tmp/adminclient-configs.conf --add --allow-principal User:Bob --consumer --topic Test-topic --group Group-1
    bin/kafka-acls.sh --bootstrap-server localhost:9092 --command-config /tmp/adminclient-configs.conf --list --topic Test-topic
    bin/kafka-acls.sh --bootstrap-server localhost:9092 --command-config /tmp/adminclient-configs.conf --add --allow-principal User:tokenRequester --operation CreateTokens --user-principal "owner1"

Authorization Primitives

Protocol calls are usually performing some operations on certain resources in Kafka. It is required to know the operations and resources to set up effective protection. In this section we'll list these operations and resources, then list the combination of these with the protocols to see the valid scenarios.

Operations in Kafka

There are a few operation primitives that can be used to build up privileges. These can be matched up with certain resources to allow specific protocol calls for a given user. These are:

  • Read
  • Write
  • Create
  • Delete
  • Alter
  • Describe
  • ClusterAction
  • DescribeConfigs
  • AlterConfigs
  • IdempotentWrite
  • CreateTokens
  • DescribeTokens
  • All
Resources in Kafka

The operations above can be applied on certain resources which are described below.

  • Topic: this simply represents a Topic. All protocol calls that are acting on topics (such as reading, writing them) require the corresponding privilege to be added. If there is an authorization error with a topic resource, then a TOPIC_AUTHORIZATION_FAILED (error code: 29) will be returned.
  • Group: this represents the consumer groups in the brokers. All protocol calls that are working with consumer groups, like joining a group must have privileges with the group in subject. If the privilege is not given then a GROUP_AUTHORIZATION_FAILED (error code: 30) will be returned in the protocol response.
  • Cluster: this resource represents the cluster. Operations that are affecting the whole cluster, like controlled shutdown are protected by privileges on the Cluster resource. If there is an authorization problem on a cluster resource, then a CLUSTER_AUTHORIZATION_FAILED (error code: 31) will be returned.
  • TransactionalId: this resource represents actions related to transactions, such as committing. If any error occurs, then a TRANSACTIONAL_ID_AUTHORIZATION_FAILED (error code: 53) will be returned by brokers.
  • DelegationToken: this represents the delegation tokens in the cluster. Actions, such as describing delegation tokens could be protected by a privilege on the DelegationToken resource. Since these objects have a little special behavior in Kafka it is recommended to read KIP-48 and the related upstream documentation at Authentication using Delegation Tokens.
  • User: CreateToken and DescribeToken operations can be granted to User resources to allow creating and describing tokens for other users. More info can be found in KIP-373.
Operations and Resources on Protocols

In the below table we'll list the valid operations on resources that are executed by the Kafka API protocols.

Protocol (API key) Operation Resource Note
PRODUCE (0) Write TransactionalId An transactional producer which has its transactional.id set requires this privilege.
PRODUCE (0) IdempotentWrite Cluster An idempotent produce action requires this privilege.
PRODUCE (0) Write Topic This applies to a normal produce action.
FETCH (1) ClusterAction Cluster A follower must have ClusterAction on the Cluster resource in order to fetch partition data.
FETCH (1) Read Topic Regular Kafka consumers need READ permission on each partition they are fetching.
LIST_OFFSETS (2) Describe Topic
METADATA (3) Describe Topic
METADATA (3) Create Cluster If topic auto-creation is enabled, then the broker-side API will check for the existence of a Cluster level privilege. If it's found then it'll allow creating the topic, otherwise it'll iterate through the Topic level privileges (see the next one).
METADATA (3) Create Topic This authorizes auto topic creation if enabled but the given user doesn't have a cluster level permission (above).
LEADER_AND_ISR (4) ClusterAction Cluster
STOP_REPLICA (5) ClusterAction Cluster
UPDATE_METADATA (6) ClusterAction Cluster
CONTROLLED_SHUTDOWN (7) ClusterAction Cluster
OFFSET_COMMIT (8) Read Group An offset can only be committed if it's authorized to the given group and the topic too (see below). Group access is checked first, then Topic access.
OFFSET_COMMIT (8) Read Topic Since offset commit is part of the consuming process, it needs privileges for the read action.
OFFSET_FETCH (9) Describe Group Similarly to OFFSET_COMMIT, the application must have privileges on group and topic level too to be able to fetch. However in this case it requires describe access instead of read. Group access is checked first, then Topic access.
OFFSET_FETCH (9) Describe Topic
FIND_COORDINATOR (10) Describe Group The FIND_COORDINATOR request can be of "Group" type in which case it is looking for consumergroup coordinators. This privilege would represent the Group mode.
FIND_COORDINATOR (10) Describe TransactionalId This applies only on transactional producers and checked when a producer tries to find the transaction coordinator.
JOIN_GROUP (11) Read Group
HEARTBEAT (12) Read Group
LEAVE_GROUP (13) Read Group
SYNC_GROUP (14) Read Group
DESCRIBE_GROUPS (15) Describe Group
LIST_GROUPS (16) Describe Cluster When the broker checks to authorize a list_groups request it first checks for this cluster level authorization. If none found then it proceeds to check the groups individually. This operation doesn't return CLUSTER_AUTHORIZATION_FAILED.
LIST_GROUPS (16) Describe Group If none of the groups are authorized, then just an empty response will be sent back instead of an error. This operation doesn't return CLUSTER_AUTHORIZATION_FAILED. This is applicable from the 2.1 release.
SASL_HANDSHAKE (17) The SASL handshake is part of the authentication process and therefore it's not possible to apply any kind of authorization here.
API_VERSIONS (18) The API_VERSIONS request is part of the Kafka protocol handshake and happens on connection and before any authentication. Therefore it's not possible to control this with authorization.
CREATE_TOPICS (19) Create Cluster If there is no cluster level authorization then it won't return CLUSTER_AUTHORIZATION_FAILED but fall back to use topic level, which is just below. That'll throw error if there is a problem.
CREATE_TOPICS (19) Create Topic This is applicable from the 2.0 release.
DELETE_TOPICS (20) Delete Topic
DELETE_RECORDS (21) Delete Topic
INIT_PRODUCER_ID (22) Write TransactionalId
INIT_PRODUCER_ID (22) IdempotentWrite Cluster
OFFSET_FOR_LEADER_EPOCH (23) ClusterAction Cluster If there is no cluster level privilege for this operation, then it'll check for topic level one.
OFFSET_FOR_LEADER_EPOCH (23) Describe Topic This is applicable from the 2.1 release.
ADD_PARTITIONS_TO_TXN (24) Write TransactionalId This API is only applicable to transactional requests. It first checks for the Write action on the TransactionalId resource, then it checks the Topic in subject (below).
ADD_PARTITIONS_TO_TXN (24) Write Topic
ADD_OFFSETS_TO_TXN (25) Write TransactionalId Similarly to ADD_PARTITIONS_TO_TXN this is only applicable to transactional request. It first checks for Write action on the TransactionalId resource, then it checks whether it can Read on the given group (below).
ADD_OFFSETS_TO_TXN (25) Read Group
END_TXN (26) Write TransactionalId
WRITE_TXN_MARKERS (27) ClusterAction Cluster
TXN_OFFSET_COMMIT (28) Write TransactionalId
TXN_OFFSET_COMMIT (28) Read Group
TXN_OFFSET_COMMIT (28) Read Topic
DESCRIBE_ACLS (29) Describe Cluster
CREATE_ACLS (30) Alter Cluster
DELETE_ACLS (31) Alter Cluster
DESCRIBE_CONFIGS (32) DescribeConfigs Cluster If broker configs are requested, then the broker will check cluster level privileges.
DESCRIBE_CONFIGS (32) DescribeConfigs Topic If topic configs are requested, then the broker will check topic level privileges.
ALTER_CONFIGS (33) AlterConfigs Cluster If broker configs are altered, then the broker will check cluster level privileges.
ALTER_CONFIGS (33) AlterConfigs Topic If topic configs are altered, then the broker will check topic level privileges.
ALTER_REPLICA_LOG_DIRS (34) Alter Cluster
DESCRIBE_LOG_DIRS (35) Describe Cluster An empty response will be returned on authorization failure.
SASL_AUTHENTICATE (36) SASL_AUTHENTICATE is part of the authentication process and therefore it's not possible to apply any kind of authorization here.
CREATE_PARTITIONS (37) Alter Topic
CREATE_DELEGATION_TOKEN (38) Creating delegation tokens has special rules, for this please see the Authentication using Delegation Tokens section.
CREATE_DELEGATION_TOKEN (38) CreateTokens User Allows creating delegation tokens for the User resource.
RENEW_DELEGATION_TOKEN (39) Renewing delegation tokens has special rules, for this please see the Authentication using Delegation Tokens section.
EXPIRE_DELEGATION_TOKEN (40) Expiring delegation tokens has special rules, for this please see the Authentication using Delegation Tokens section.
DESCRIBE_DELEGATION_TOKEN (41) Describe DelegationToken Describing delegation tokens has special rules, for this please see the Authentication using Delegation Tokens section.
DESCRIBE_DELEGATION_TOKEN (41) DescribeTokens User Allows describing delegation tokens of the User resource.
DELETE_GROUPS (42) Delete Group
ELECT_PREFERRED_LEADERS (43) ClusterAction Cluster
INCREMENTAL_ALTER_CONFIGS (44) AlterConfigs Cluster If broker configs are altered, then the broker will check cluster level privileges.
INCREMENTAL_ALTER_CONFIGS (44) AlterConfigs Topic If topic configs are altered, then the broker will check topic level privileges.
ALTER_PARTITION_REASSIGNMENTS (45) Alter Cluster
LIST_PARTITION_REASSIGNMENTS (46) Describe Cluster
OFFSET_DELETE (47) Delete Group
OFFSET_DELETE (47) Read Topic
DESCRIBE_CLIENT_QUOTAS (48) DescribeConfigs Cluster
ALTER_CLIENT_QUOTAS (49) AlterConfigs Cluster
DESCRIBE_USER_SCRAM_CREDENTIALS (50) Describe Cluster
ALTER_USER_SCRAM_CREDENTIALS (51) Alter Cluster
VOTE (52) ClusterAction Cluster
BEGIN_QUORUM_EPOCH (53) ClusterAction Cluster
END_QUORUM_EPOCH (54) ClusterAction Cluster
DESCRIBE_QUORUM (55) Describe Cluster
ALTER_PARTITION (56) ClusterAction Cluster
UPDATE_FEATURES (57) Alter Cluster
ENVELOPE (58) ClusterAction Cluster
FETCH_SNAPSHOT (59) ClusterAction Cluster
DESCRIBE_CLUSTER (60) Describe Cluster
DESCRIBE_PRODUCERS (61) Read Topic
BROKER_REGISTRATION (62) ClusterAction Cluster
BROKER_HEARTBEAT (63) ClusterAction Cluster
UNREGISTER_BROKER (64) Alter Cluster
DESCRIBE_TRANSACTIONS (65) Describe TransactionalId
LIST_TRANSACTIONS (66) Describe TransactionalId
ALLOCATE_PRODUCER_IDS (67) ClusterAction Cluster
CONSUMER_GROUP_HEARTBEAT (68) Read Group

7.6 Incorporating Security Features in a Running Cluster

You can secure a running cluster via one or more of the supported protocols discussed previously. This is done in phases:

  • Incrementally bounce the cluster nodes to open additional secured port(s).
  • Restart clients using the secured rather than PLAINTEXT port (assuming you are securing the client-broker connection).
  • Incrementally bounce the cluster again to enable broker-to-broker security (if this is required)
  • A final incremental bounce to close the PLAINTEXT port.

The specific steps for configuring SSL and SASL are described in sections 7.3 and 7.4. Follow these steps to enable security for your desired protocol(s). The security implementation lets you configure different protocols for both broker-client and broker-broker communication. These must be enabled in separate bounces. A PLAINTEXT port must be left open throughout so brokers and/or clients can continue to communicate. When performing an incremental bounce stop the brokers cleanly via a SIGTERM. It's also good practice to wait for restarted replicas to return to the ISR list before moving onto the next node. As an example, say we wish to encrypt both broker-client and broker-broker communication with SSL. In the first incremental bounce, an SSL port is opened on each node: We then restart the clients, changing their config to point at the newly opened, secured port: In the second incremental server bounce we instruct Kafka to use SSL as the broker-broker protocol (which will use the same SSL port): In the final bounce we secure the cluster by closing the PLAINTEXT port: Alternatively we might choose to open multiple ports so that different protocols can be used for broker-broker and broker-client communication. Say we wished to use SSL encryption throughout (i.e. for broker-broker and broker-client communication) but we'd like to add SASL authentication to the broker-client connection also. We would achieve this by opening two additional ports during the first bounce: We would then restart the clients, changing their config to point at the newly opened, SASL & SSL secured port: The second server bounce would switch the cluster to use encrypted broker-broker communication via the SSL port we previously opened on port 9092: The final bounce secures the cluster by closing the PLAINTEXT port. ZooKeeper can be secured independently of the Kafka cluster. The steps for doing this are covered in section 7.7.2.

listeners=PLAINTEXT://broker1:9091,SSL://broker1:9092
bootstrap.servers = [broker1:9092,...]
security.protocol = SSL
...etc
listeners=PLAINTEXT://broker1:9091,SSL://broker1:9092
security.inter.broker.protocol=SSL
listeners=SSL://broker1:9092
security.inter.broker.protocol=SSL
listeners=PLAINTEXT://broker1:9091,SSL://broker1:9092,SASL_SSL://broker1:9093
bootstrap.servers = [broker1:9093,...]
security.protocol = SASL_SSL
...etc
listeners=PLAINTEXT://broker1:9091,SSL://broker1:9092,SASL_SSL://broker1:9093
security.inter.broker.protocol=SSL
listeners=SSL://broker1:9092,SASL_SSL://broker1:9093
security.inter.broker.protocol=SSL

7.7 ZooKeeper Authentication

ZooKeeper supports mutual TLS (mTLS) authentication beginning with the 3.5.x versions. Kafka supports authenticating to ZooKeeper with SASL and mTLS -- either individually or both together -- beginning with version 2.5. See KIP-515: Enable ZK client to use the new TLS supported authentication for more details.

When using mTLS alone, every broker and any CLI tools (such as the ZooKeeper Security Migration Tool) should identify itself with the same Distinguished Name (DN) because it is the DN that is ACL'ed. This can be changed as described below, but it involves writing and deploying a custom ZooKeeper authentication provider. Generally each certificate should have the same DN but a different Subject Alternative Name (SAN) so that hostname verification of the brokers and any CLI tools by ZooKeeper will succeed.

When using SASL authentication to ZooKeeper together with mTLS, both the SASL identity and either the DN that created the znode (i.e. the creating broker's certificate) or the DN of the Security Migration Tool (if migration was performed after the znode was created) will be ACL'ed, and all brokers and CLI tools will be authorized even if they all use different DNs because they will all use the same ACL'ed SASL identity. It is only when using mTLS authentication alone that all the DNs must match (and SANs become critical -- again, in the absence of writing and deploying a custom ZooKeeper authentication provider as described below).

Use the broker properties file to set TLS configs for brokers as described below.

Use the --zk-tls-config-file <file> option to set TLS configs in the Zookeeper Security Migration Tool. The kafka-acls.sh and kafka-configs.sh CLI tools also support the --zk-tls-config-file <file> option.

Use the -zk-tls-config-file <file> option (note the single-dash rather than double-dash) to set TLS configs for the zookeeper-shell.sh CLI tool.

7.7.1 New clusters

7.7.1.1 ZooKeeper SASL Authentication
To enable ZooKeeper SASL authentication on brokers, there are two necessary steps:
  1. Create a JAAS login file and set the appropriate system property to point to it as described above
  2. Set the configuration property zookeeper.set.acl in each broker to true
The metadata stored in ZooKeeper for the Kafka cluster is world-readable, but can only be modified by the brokers. The rationale behind this decision is that the data stored in ZooKeeper is not sensitive, but inappropriate manipulation of that data can cause cluster disruption. We also recommend limiting the access to ZooKeeper via network segmentation (only brokers and some admin tools need access to ZooKeeper).
7.7.1.2 ZooKeeper Mutual TLS Authentication
ZooKeeper mTLS authentication can be enabled with or without SASL authentication. As mentioned above, when using mTLS alone, every broker and any CLI tools (such as the ZooKeeper Security Migration Tool) must generally identify itself with the same Distinguished Name (DN) because it is the DN that is ACL'ed, which means each certificate should have an appropriate Subject Alternative Name (SAN) so that hostname verification of the brokers and any CLI tool by ZooKeeper will succeed.

It is possible to use something other than the DN for the identity of mTLS clients by writing a class that extends org.apache.zookeeper.server.auth.X509AuthenticationProvider and overrides the method protected String getClientId(X509Certificate clientCert). Choose a scheme name and set authProvider.[scheme] in ZooKeeper to be the fully-qualified class name of the custom implementation; then set ssl.authProvider=[scheme] to use it.

Here is a sample (partial) ZooKeeper configuration for enabling TLS authentication. These configurations are described in the ZooKeeper Admin Guide. IMPORTANT: ZooKeeper does not support setting the key password in the ZooKeeper server keystore to a value different from the keystore password itself. Be sure to set the key password to be the same as the keystore password.
secureClientPort=2182
serverCnxnFactory=org.apache.zookeeper.server.NettyServerCnxnFactory
authProvider.x509=org.apache.zookeeper.server.auth.X509AuthenticationProvider
ssl.keyStore.location=/path/to/zk/keystore.jks
ssl.keyStore.password=zk-ks-passwd
ssl.trustStore.location=/path/to/zk/truststore.jks
ssl.trustStore.password=zk-ts-passwd

Here is a sample (partial) Kafka Broker configuration for connecting to ZooKeeper with mTLS authentication. These configurations are described above in Broker Configs.

# connect to the ZooKeeper port configured for TLS
zookeeper.connect=zk1:2182,zk2:2182,zk3:2182
# required to use TLS to ZooKeeper (default is false)
zookeeper.ssl.client.enable=true
# required to use TLS to ZooKeeper
zookeeper.clientCnxnSocket=org.apache.zookeeper.ClientCnxnSocketNetty
# define key/trust stores to use TLS to ZooKeeper; ignored unless zookeeper.ssl.client.enable=true
zookeeper.ssl.keystore.location=/path/to/kafka/keystore.jks
zookeeper.ssl.keystore.password=kafka-ks-passwd
zookeeper.ssl.truststore.location=/path/to/kafka/truststore.jks
zookeeper.ssl.truststore.password=kafka-ts-passwd
# tell broker to create ACLs on znodes
zookeeper.set.acl=true
IMPORTANT: ZooKeeper does not support setting the key password in the ZooKeeper client (i.e. broker) keystore to a value different from the keystore password itself. Be sure to set the key password to be the same as the keystore password.

7.7.2 Migrating clusters

If you are running a version of Kafka that does not support security or simply with security disabled, and you want to make the cluster secure, then you need to execute the following steps to enable ZooKeeper authentication with minimal disruption to your operations:
  1. Enable SASL and/or mTLS authentication on ZooKeeper. If enabling mTLS, you would now have both a non-TLS port and a TLS port, like this:
    clientPort=2181
    secureClientPort=2182
    serverCnxnFactory=org.apache.zookeeper.server.NettyServerCnxnFactory
    authProvider.x509=org.apache.zookeeper.server.auth.X509AuthenticationProvider
    ssl.keyStore.location=/path/to/zk/keystore.jks
    ssl.keyStore.password=zk-ks-passwd
    ssl.trustStore.location=/path/to/zk/truststore.jks
    ssl.trustStore.password=zk-ts-passwd
  2. Perform a rolling restart of brokers setting the JAAS login file and/or defining ZooKeeper mutual TLS configurations (including connecting to the TLS-enabled ZooKeeper port) as required, which enables brokers to authenticate to ZooKeeper. At the end of the rolling restart, brokers are able to manipulate znodes with strict ACLs, but they will not create znodes with those ACLs
  3. If you enabled mTLS, disable the non-TLS port in ZooKeeper
  4. Perform a second rolling restart of brokers, this time setting the configuration parameter zookeeper.set.acl to true, which enables the use of secure ACLs when creating znodes
  5. Execute the ZkSecurityMigrator tool. To execute the tool, there is this script: bin/zookeeper-security-migration.sh with zookeeper.acl set to secure. This tool traverses the corresponding sub-trees changing the ACLs of the znodes. Use the option if you enable mTLS.--zk-tls-config-file <file>

It is also possible to turn off authentication in a secure cluster. To do it, follow these steps:

  1. Perform a rolling restart of brokers setting the JAAS login file and/or defining ZooKeeper mutual TLS configurations, which enables brokers to authenticate, but setting zookeeper.set.acl to false. At the end of the rolling restart, brokers stop creating znodes with secure ACLs, but are still able to authenticate and manipulate all znodes
  2. Execute the ZkSecurityMigrator tool. To execute the tool, run this script bin/zookeeper-security-migration.sh with zookeeper.acl set to unsecure. This tool traverses the corresponding sub-trees changing the ACLs of the znodes. Use the option if you need to set TLS configuration.--zk-tls-config-file <file>
  3. If you are disabling mTLS, enable the non-TLS port in ZooKeeper
  4. Perform a second rolling restart of brokers, this time omitting the system property that sets the JAAS login file and/or removing ZooKeeper mutual TLS configuration (including connecting to the non-TLS-enabled ZooKeeper port) as required
  5. If you are disabling mTLS, disable the TLS port in ZooKeeper
Here is an example of how to run the migration tool:
> bin/zookeeper-security-migration.sh --zookeeper.acl=secure --zookeeper.connect=localhost:2181

Run this to see the full list of parameters:

> bin/zookeeper-security-migration.sh --help

7.7.3 Migrating the ZooKeeper ensemble

It is also necessary to enable SASL and/or mTLS authentication on the ZooKeeper ensemble. To do it, we need to perform a rolling restart of the server and set a few properties. See above for mTLS information. Please refer to the ZooKeeper documentation for more detail:
  1. Apache ZooKeeper documentation
  2. Apache ZooKeeper wiki

7.7.4 ZooKeeper Quorum Mutual TLS Authentication

It is possible to enable mTLS authentication between the ZooKeeper servers themselves. Please refer to the ZooKeeper documentation for more detail.

7.8 ZooKeeper Encryption

ZooKeeper connections that use mutual TLS are encrypted. Beginning with ZooKeeper version 3.5.7 (the version shipped with Kafka version 2.5) ZooKeeper supports a sever-side config ssl.clientAuth (case-insensitively: want/need/none are the valid options, the default is need), and setting this value to none in ZooKeeper allows clients to connect via a TLS-encrypted connection without presenting their own certificate. Here is a sample (partial) Kafka Broker configuration for connecting to ZooKeeper with just TLS encryption. These configurations are described above in Broker Configs.
# connect to the ZooKeeper port configured for TLS
zookeeper.connect=zk1:2182,zk2:2182,zk3:2182
# required to use TLS to ZooKeeper (default is false)
zookeeper.ssl.client.enable=true
# required to use TLS to ZooKeeper
zookeeper.clientCnxnSocket=org.apache.zookeeper.ClientCnxnSocketNetty
# define trust stores to use TLS to ZooKeeper; ignored unless zookeeper.ssl.client.enable=true
# no need to set keystore information assuming ssl.clientAuth=none on ZooKeeper
zookeeper.ssl.truststore.location=/path/to/kafka/truststore.jks
zookeeper.ssl.truststore.password=kafka-ts-passwd
# tell broker to create ACLs on znodes (if using SASL authentication, otherwise do not set this)
zookeeper.set.acl=true

8. Kafka 连接

8.1 Overview

Kafka Connect is a tool for scalably and reliably streaming data between Apache Kafka and other systems. It makes it simple to quickly define connectors that move large collections of data into and out of Kafka. Kafka Connect can ingest entire databases or collect metrics from all your application servers into Kafka topics, making the data available for stream processing with low latency. An export job can deliver data from Kafka topics into secondary storage and query systems or into batch systems for offline analysis.

Kafka Connect features include:

  • A common framework for Kafka connectors - Kafka Connect standardizes integration of other data systems with Kafka, simplifying connector development, deployment, and management
  • Distributed and standalone modes - scale up to a large, centrally managed service supporting an entire organization or scale down to development, testing, and small production deployments
  • REST interface - submit and manage connectors to your Kafka Connect cluster via an easy to use REST API
  • Automatic offset management - with just a little information from connectors, Kafka Connect can manage the offset commit process automatically so connector developers do not need to worry about this error prone part of connector development
  • Distributed and scalable by default - Kafka Connect builds on the existing group management protocol. More workers can be added to scale up a Kafka Connect cluster.
  • Streaming/batch integration - leveraging Kafka's existing capabilities, Kafka Connect is an ideal solution for bridging streaming and batch data systems

8.2 User Guide

The quickstart provides a brief example of how to run a standalone version of Kafka Connect. This section describes how to configure, run, and manage Kafka Connect in more detail.

Running Kafka Connect

Kafka Connect currently supports two modes of execution: standalone (single process) and distributed.

In standalone mode all work is performed in a single process. This configuration is simpler to setup and get started with and may be useful in situations where only one worker makes sense (e.g. collecting log files), but it does not benefit from some of the features of Kafka Connect such as fault tolerance. You can start a standalone process with the following command:

> bin/connect-standalone.sh config/connect-standalone.properties [connector1.properties connector2.properties ...]

The first parameter is the configuration for the worker. This includes settings such as the Kafka connection parameters, serialization format, and how frequently to commit offsets. The provided example should work well with a local cluster running with the default configuration provided by . It will require tweaking to use with a different configuration or production deployment. All workers (both standalone and distributed) require a few configs:config/server.properties

  • bootstrap.servers - List of Kafka servers used to bootstrap connections to Kafka
  • key.converter - Converter class used to convert between Kafka Connect format and the serialized form that is written to Kafka. This controls the format of the keys in messages written to or read from Kafka, and since this is independent of connectors it allows any connector to work with any serialization format. Examples of common formats include JSON and Avro.
  • value.converter - Converter class used to convert between Kafka Connect format and the serialized form that is written to Kafka. This controls the format of the values in messages written to or read from Kafka, and since this is independent of connectors it allows any connector to work with any serialization format. Examples of common formats include JSON and Avro.
  • plugin.path (default ) - a list of paths that contain Connect plugins (connectors, converters, transformations). Before running quick starts, users must add the absolute path that contains the example FileStreamSourceConnector and FileStreamSinkConnector packaged in , because these connectors are not included by default to the or the of the Connect worker (see plugin.path property for examples).emptyconnect-file-"version".jarCLASSPATHplugin.path

The important configuration options specific to standalone mode are:

  • offset.storage.file.filename - File to store source connector offsets

The parameters that are configured here are intended for producers and consumers used by Kafka Connect to access the configuration, offset and status topics. For configuration of the producers used by Kafka source tasks and the consumers used by Kafka sink tasks, the same parameters can be used but need to be prefixed with and respectively. The only Kafka client parameter that is inherited without a prefix from the worker configuration is , which in most cases will be sufficient, since the same cluster is often used for all purposes. A notable exception is a secured cluster, which requires extra parameters to allow connections. These parameters will need to be set up to three times in the worker configuration, once for management access, once for Kafka sources and once for Kafka sinks.producer.consumer.bootstrap.servers

Starting with 2.3.0, client configuration overrides can be configured individually per connector by using the prefixes and for Kafka sources or Kafka sinks respectively. These overrides are included with the rest of the connector's configuration properties.producer.override.consumer.override.

The remaining parameters are connector configuration files. You may include as many as you want, but all will execute within the same process (on different threads). You can also choose not to specify any connector configuration files on the command line, and instead use the REST API to create connectors at runtime after your standalone worker starts.

Distributed mode handles automatic balancing of work, allows you to scale up (or down) dynamically, and offers fault tolerance both in the active tasks and for configuration and offset commit data. Execution is very similar to standalone mode:

> bin/connect-distributed.sh config/connect-distributed.properties

The difference is in the class which is started and the configuration parameters which change how the Kafka Connect process decides where to store configurations, how to assign work, and where to store offsets and task statues. In the distributed mode, Kafka Connect stores the offsets, configs and task statuses in Kafka topics. It is recommended to manually create the topics for offset, configs and statuses in order to achieve the desired the number of partitions and replication factors. If the topics are not yet created when starting Kafka Connect, the topics will be auto created with default number of partitions and replication factor, which may not be best suited for its usage.

In particular, the following configuration parameters, in addition to the common settings mentioned above, are critical to set before starting your cluster:

  • group.id (default ) - unique name for the cluster, used in forming the Connect cluster group; note that this must not conflict with consumer group IDsconnect-cluster
  • config.storage.topic (default ) - topic to use for storing connector and task configurations; note that this should be a single partition, highly replicated, compacted topic. You may need to manually create the topic to ensure the correct configuration as auto created topics may have multiple partitions or be automatically configured for deletion rather than compactionconnect-configs
  • offset.storage.topic (default ) - topic to use for storing offsets; this topic should have many partitions, be replicated, and be configured for compactionconnect-offsets
  • status.storage.topic (default ) - topic to use for storing statuses; this topic can have multiple partitions, and should be replicated and configured for compactionconnect-status

Note that in distributed mode the connector configurations are not passed on the command line. Instead, use the REST API described below to create, modify, and destroy connectors.

Configuring Connectors

Connector configurations are simple key-value mappings. In both standalone and distributed mode, they are included in the JSON payload for the REST request that creates (or modifies) the connector. In standalone mode these can also be defined in a properties file and passed to the Connect process on the command line.

Most configurations are connector dependent, so they can't be outlined here. However, there are a few common options:

  • name - Unique name for the connector. Attempting to register again with the same name will fail.
  • connector.class - The Java class for the connector
  • tasks.max - The maximum number of tasks that should be created for this connector. The connector may create fewer tasks if it cannot achieve this level of parallelism.
  • key.converter - (optional) Override the default key converter set by the worker.
  • value.converter - (optional) Override the default value converter set by the worker.

The config supports several formats: the full name or alias of the class for this connector. If the connector is org.apache.kafka.connect.file.FileStreamSinkConnector, you can either specify this full name or use FileStreamSink or FileStreamSinkConnector to make the configuration a bit shorter.connector.class

Sink connectors also have a few additional options to control their input. Each sink connector must set one of the following:

  • topics - A comma-separated list of topics to use as input for this connector
  • topics.regex - A Java regular expression of topics to use as input for this connector

For any other options, you should consult the documentation for the connector.

Transformations

Connectors can be configured with transformations to make lightweight message-at-a-time modifications. They can be convenient for data massaging and event routing.

A transformation chain can be specified in the connector configuration.

  • transforms - List of aliases for the transformation, specifying the order in which the transformations will be applied.
  • transforms.$alias.type - Fully qualified class name for the transformation.
  • transforms.$alias.$transformationSpecificConfig Configuration properties for the transformation

For example, lets take the built-in file source connector and use a transformation to add a static field.

Throughout the example we'll use schemaless JSON data format. To use schemaless format, we changed the following two lines in from true to false:connect-standalone.properties

key.converter.schemas.enable
value.converter.schemas.enable

The file source connector reads each line as a String. We will wrap each line in a Map and then add a second field to identify the origin of the event. To do this, we use two transformations:

  • HoistField to place the input line inside a Map
  • InsertField to add the static field. In this example we'll indicate that the record came from a file connector

After adding the transformations, file looks as following:connect-file-source.properties

name=local-file-source
connector.class=FileStreamSource
tasks.max=1
file=test.txt
topic=connect-test
transforms=MakeMap, InsertSource
transforms.MakeMap.type=org.apache.kafka.connect.transforms.HoistField$Value
transforms.MakeMap.field=line
transforms.InsertSource.type=org.apache.kafka.connect.transforms.InsertField$Value
transforms.InsertSource.static.field=data_source
transforms.InsertSource.static.value=test-file-source

All the lines starting with were added for the transformations. You can see the two transformations we created: "InsertSource" and "MakeMap" are aliases that we chose to give the transformations. The transformation types are based on the list of built-in transformations you can see below. Each transformation type has additional configuration: HoistField requires a configuration called "field", which is the name of the field in the map that will include the original String from the file. InsertField transformation lets us specify the field name and the value that we are adding.transforms

When we ran the file source connector on my sample file without the transformations, and then read them using , the results were:kafka-console-consumer.sh

"foo"
"bar"
"hello world"

We then create a new file connector, this time after adding the transformations to the configuration file. This time, the results will be:

{"line":"foo","data_source":"test-file-source"}
{"line":"bar","data_source":"test-file-source"}
{"line":"hello world","data_source":"test-file-source"}

You can see that the lines we've read are now part of a JSON map, and there is an extra field with the static value we specified. This is just one example of what you can do with transformations.

Included transformations

Several widely-applicable data and routing transformations are included with Kafka Connect:

  • InsertField - Add a field using either static data or record metadata
  • ReplaceField - Filter or rename fields
  • MaskField - Replace field with valid null value for the type (0, empty string, etc) or custom replacement (non-empty string or numeric value only)
  • ValueToKey - Replace the record key with a new key formed from a subset of fields in the record value
  • HoistField - Wrap the entire event as a single field inside a Struct or a Map
  • ExtractField - Extract a specific field from Struct and Map and include only this field in results
  • SetSchemaMetadata - modify the schema name or version
  • TimestampRouter - Modify the topic of a record based on original topic and timestamp. Useful when using a sink that needs to write to different tables or indexes based on timestamps
  • RegexRouter - modify the topic of a record based on original topic, replacement string and a regular expression
  • Filter - Removes messages from all further processing. This is used with a predicate to selectively filter certain messages.
  • InsertHeader - Add a header using static data
  • HeadersFrom - Copy or move fields in the key or value to the record headers
  • DropHeaders - Remove headers by name

Details on how to configure each transformation are listed below:

org.apache.kafka.connect.transforms.InsertField
Insert field(s) using attributes from the record metadata or a configured static value.

Use the concrete transformation type designed for the record key () or value (). org.apache.kafka.connect.transforms.InsertField$Keyorg.apache.kafka.connect.transforms.InsertField$Value

  • offset.field

    Field name for Kafka offset - only applicable to sink connectors.
    Suffix with to make this a required field, or to keep it optional (the default).
    !?

    Type:string
    Default:null
    Valid Values:
    Importance:medium
  • partition.field

    Field name for Kafka partition. Suffix with to make this a required field, or to keep it optional (the default).!?

    Type:string
    Default:null
    Valid Values:
    Importance:medium
  • static.field

    Field name for static data field. Suffix with to make this a required field, or to keep it optional (the default).!?

    Type:string
    Default:null
    Valid Values:
    Importance:medium
  • static.value

    Static field value, if field name configured.

    Type:string
    Default:null
    Valid Values:
    Importance:medium
  • timestamp.field

    Field name for record timestamp. Suffix with to make this a required field, or to keep it optional (the default).!?

    Type:string
    Default:null
    Valid Values:
    Importance:medium
  • topic.field

    Field name for Kafka topic. Suffix with to make this a required field, or to keep it optional (the default).!?

    Type:string
    Default:null
    Valid Values:
    Importance:medium
org.apache.kafka.connect.transforms.ReplaceField
Filter or rename fields.

Use the concrete transformation type designed for the record key () or value (). org.apache.kafka.connect.transforms.ReplaceField$Keyorg.apache.kafka.connect.transforms.ReplaceField$Value

  • exclude

    Fields to exclude. This takes precedence over the fields to include.

    Type:list
    Default:""
    Valid Values:
    Importance:medium
  • include

    Fields to include. If specified, only these fields will be used.

    Type:list
    Default:""
    Valid Values:
    Importance:medium
  • renames

    Field rename mappings.

    Type:list
    Default:""
    Valid Values:list of colon-delimited pairs, e.g. foo:bar,abc:xyz
    Importance:medium
  • blacklist

    Deprecated. Use exclude instead.

    Type:list
    Default:null
    Valid Values:
    Importance:low
  • whitelist

    Deprecated. Use include instead.

    Type:list
    Default:null
    Valid Values:
    Importance:low
org.apache.kafka.connect.transforms.MaskField
Mask specified fields with a valid null value for the field type (i.e. 0, false, empty string, and so on).

For numeric and string fields, an optional replacement value can be specified that is converted to the correct type.

Use the concrete transformation type designed for the record key () or value (). org.apache.kafka.connect.transforms.MaskField$Keyorg.apache.kafka.connect.transforms.MaskField$Value

  • fields

    Names of fields to mask.

    Type:list
    Default:
    Valid Values:non-empty list
    Importance:high
  • replacement

    Custom value replacement, that will be applied to all 'fields' values (numeric or non-empty string values only).

    Type:string
    Default:null
    Valid Values:non-empty string
    Importance:low
org.apache.kafka.connect.transforms.ValueToKey
Replace the record key with a new key formed from a subset of fields in the record value.

  • fields

    Field names on the record value to extract as the record key.

    Type:list
    Default:
    Valid Values:non-empty list
    Importance:high
org.apache.kafka.connect.transforms.HoistField
Wrap data using the specified field name in a Struct when schema present, or a Map in the case of schemaless data.

Use the concrete transformation type designed for the record key () or value (). org.apache.kafka.connect.transforms.HoistField$Keyorg.apache.kafka.connect.transforms.HoistField$Value

  • field

    Field name for the single field that will be created in the resulting Struct or Map.

    Type:string
    Default:
    Valid Values:
    Importance:medium
org.apache.kafka.connect.transforms.ExtractField
Extract the specified field from a Struct when schema present, or a Map in the case of schemaless data. Any null values are passed through unmodified.

Use the concrete transformation type designed for the record key () or value (). org.apache.kafka.connect.transforms.ExtractField$Keyorg.apache.kafka.connect.transforms.ExtractField$Value

  • field

    Field name to extract.

    Type:string
    Default:
    Valid Values:
    Importance:medium
org.apache.kafka.connect.transforms.SetSchemaMetadata
Set the schema name, version or both on the record's key () or value () schema. org.apache.kafka.connect.transforms.SetSchemaMetadata$Keyorg.apache.kafka.connect.transforms.SetSchemaMetadata$Value

  • schema.name

    Schema name to set.

    Type:string
    Default:null
    Valid Values:
    Importance:high
  • schema.version

    Schema version to set.

    Type:int
    Default:null
    Valid Values:
    Importance:high
org.apache.kafka.connect.transforms.TimestampRouter
Update the record's topic field as a function of the original topic value and the record timestamp.

This is mainly useful for sink connectors, since the topic field is often used to determine the equivalent entity name in the destination system(e.g. database table or search index name).

  • timestamp.format

    Format string for the timestamp that is compatible with .java.text.SimpleDateFormat

    Type:string
    Default:yyyyMMdd
    Valid Values:
    Importance:high
  • topic.format

    Format string which can contain and as placeholders for the topic and timestamp, respectively.${topic}${timestamp}

    Type:string
    Default:${topic}-${timestamp}
    Valid Values:
    Importance:high
org.apache.kafka.connect.transforms.RegexRouter
Update the record topic using the configured regular expression and replacement string.

Under the hood, the regex is compiled to a . If the pattern matches the input topic, is used with the replacement string to obtain the new topic. java.util.regex.Patternjava.util.regex.Matcher#replaceFirst()

  • regex

    Regular expression to use for matching.

    Type:string
    Default:
    Valid Values:valid regex
    Importance:high
  • replacement

    Replacement string.

    Type:string
    Default:
    Valid Values:
    Importance:high
org.apache.kafka.connect.transforms.Flatten
Flatten a nested data structure, generating names for each field by concatenating the field names at each level with a configurable delimiter character. Applies to Struct when schema present, or a Map in the case of schemaless data. Array fields and their contents are not modified. The default delimiter is '.'.

Use the concrete transformation type designed for the record key () or value (). org.apache.kafka.connect.transforms.Flatten$Keyorg.apache.kafka.connect.transforms.Flatten$Value

  • delimiter

    Delimiter to insert between field names from the input record when generating field names for the output record

    Type:string
    Default:.
    Valid Values:
    Importance:medium
org.apache.kafka.connect.transforms.Cast
Cast fields or the entire key or value to a specific type, e.g. to force an integer field to a smaller width. Cast from integers, floats, boolean and string to any other type, and cast binary to string (base64 encoded).

Use the concrete transformation type designed for the record key () or value (). org.apache.kafka.connect.transforms.Cast$Keyorg.apache.kafka.connect.transforms.Cast$Value

  • spec

    List of fields and the type to cast them to of the form field1:type,field2:type to cast fields of Maps or Structs. A single type to cast the entire value. Valid types are int8, int16, int32, int64, float32, float64, boolean, and string. Note that binary fields can only be cast to string.

    Type:list
    Default:
    Valid Values:list of colon-delimited pairs, e.g. foo:bar,abc:xyz
    Importance:high
org.apache.kafka.connect.transforms.TimestampConverter
Convert timestamps between different formats such as Unix epoch, strings, and Connect Date/Timestamp types.Applies to individual fields or to the entire value.

Use the concrete transformation type designed for the record key () or value (). org.apache.kafka.connect.transforms.TimestampConverter$Keyorg.apache.kafka.connect.transforms.TimestampConverter$Value

  • target.type

    The desired timestamp representation: string, unix, Date, Time, or Timestamp

    Type:string
    Default:
    Valid Values:[string, unix, Date, Time, Timestamp]
    Importance:high
  • field

    The field containing the timestamp, or empty if the entire value is a timestamp

    Type:string
    Default:""
    Valid Values:
    Importance:high
  • format

    A SimpleDateFormat-compatible format for the timestamp. Used to generate the output when type=string or used to parse the input if the input is a string.

    Type:string
    Default:""
    Valid Values:
    Importance:medium
  • unix.precision

    The desired Unix precision for the timestamp: seconds, milliseconds, microseconds, or nanoseconds. Used to generate the output when type=unix or used to parse the input if the input is a Long.Note: This SMT will cause precision loss during conversions from, and to, values with sub-millisecond components.

    Type:string
    Default:milliseconds
    Valid Values:[nanoseconds, microseconds, milliseconds, seconds]
    Importance:low
org.apache.kafka.connect.transforms.Filter
Drops all records, filtering them from subsequent transformations in the chain. This is intended to be used conditionally to filter out records matching (or not matching) a particular Predicate.

org.apache.kafka.connect.transforms.InsertHeader
Add a header to each record.

  • header

    The name of the header.

    Type:string
    Default:
    Valid Values:non-null string
    Importance:high
  • value.literal

    The literal value that is to be set as the header value on all records.

    Type:string
    Default:
    Valid Values:non-null string
    Importance:high
org.apache.kafka.connect.transforms.DropHeaders
Removes one or more headers from each record.

  • headers

    The name of the headers to be removed.

    Type:list
    Default:
    Valid Values:non-empty list
    Importance:high
org.apache.kafka.connect.transforms.HeaderFrom
Moves or copies fields in the key/value of a record into that record's headers. Corresponding elements of and together identify a field and the header it should be moved or copied to. Use the concrete transformation type designed for the record key () or value (). fieldsheadersorg.apache.kafka.connect.transforms.HeaderFrom$Keyorg.apache.kafka.connect.transforms.HeaderFrom$Value

  • fields

    Field names in the record whose values are to be copied or moved to headers.

    Type:list
    Default:
    Valid Values:non-empty list
    Importance:high
  • headers

    Header names, in the same order as the field names listed in the fields configuration property.

    Type:list
    Default:
    Valid Values:non-empty list
    Importance:high
  • operation

    Either if the fields are to be moved to the headers (removed from the key/value), or if the fields are to be copied to the headers (retained in the key/value).movecopy

    Type:string
    Default:
    Valid Values:[move, copy]
    Importance:high
Predicates

Transformations can be configured with predicates so that the transformation is applied only to messages which satisfy some condition. In particular, when combined with the Filter transformation predicates can be used to selectively filter out certain messages.

Predicates are specified in the connector configuration.

  • predicates - Set of aliases for the predicates to be applied to some of the transformations.
  • predicates.$alias.type - Fully qualified class name for the predicate.
  • predicates.$alias.$predicateSpecificConfig - Configuration properties for the predicate.

All transformations have the implicit config properties and . A predicular predicate is associated with a transformation by setting the transformation's config to the predicate's alias. The predicate's value can be reversed using the configuration property.predicatenegatepredicatenegate

For example, suppose you have a source connector which produces messages to many different topics and you want to:

  • filter out the messages in the 'foo' topic entirely
  • apply the ExtractField transformation with the field name 'other_field' to records in all topics except the topic 'bar'

To do this we need first to filter out the records destined for the topic 'foo'. The Filter transformation removes records from further processing, and can use the TopicNameMatches predicate to apply the transformation only to records in topics which match a certain regular expression. TopicNameMatches's only configuration property is which is a Java regular expression for matching against the topic name. The configuration would look like this:pattern

transforms=Filter
transforms.Filter.type=org.apache.kafka.connect.transforms.Filter
transforms.Filter.predicate=IsFoo

predicates=IsFoo
predicates.IsFoo.type=org.apache.kafka.connect.transforms.predicates.TopicNameMatches
predicates.IsFoo.pattern=foo

Next we need to apply ExtractField only when the topic name of the record is not 'bar'. We can't just use TopicNameMatches directly, because that would apply the transformation to matching topic names, not topic names which do not match. The transformation's implicit config properties allows us to invert the set of records which a predicate matches. Adding the configuration for this to the previous example we arrive at:negate

transforms=Filter,Extract
transforms.Filter.type=org.apache.kafka.connect.transforms.Filter
transforms.Filter.predicate=IsFoo

transforms.Extract.type=org.apache.kafka.connect.transforms.ExtractField$Key
transforms.Extract.field=other_field
transforms.Extract.predicate=IsBar
transforms.Extract.negate=true

predicates=IsFoo,IsBar
predicates.IsFoo.type=org.apache.kafka.connect.transforms.predicates.TopicNameMatches
predicates.IsFoo.pattern=foo

predicates.IsBar.type=org.apache.kafka.connect.transforms.predicates.TopicNameMatches
predicates.IsBar.pattern=bar

Kafka Connect includes the following predicates:

  • TopicNameMatches - matches records in a topic with a name matching a particular Java regular expression.
  • HasHeaderKey - matches records which have a header with the given key.
  • RecordIsTombstone - matches tombstone records, that is records with a null value.

Details on how to configure each predicate are listed below:

org.apache.kafka.connect.transforms.predicates.HasHeaderKey
A predicate which is true for records with at least one header with the configured name.

  • name

    The header name.

    Type:string
    Default:
    Valid Values:non-empty string
    Importance:medium
org.apache.kafka.connect.transforms.predicates.RecordIsTombstone
A predicate which is true for records which are tombstones (i.e. have null value).

org.apache.kafka.connect.transforms.predicates.TopicNameMatches
A predicate which is true for records with a topic name that matches the configured regular expression.

  • pattern

    A Java regular expression for matching against the name of a record's topic.

    Type:string
    Default:
    Valid Values:non-empty string, valid regex
    Importance:medium

REST API

Since Kafka Connect is intended to be run as a service, it also provides a REST API for managing connectors. This REST API is available in both standalone and distributed mode. The REST API server can be configured using the configuration option. This field should contain a list of listeners in the following format: . Currently supported protocols are and . For example:listenersprotocol://host:port,protocol2://host2:port2httphttps

listeners=http://localhost:8080,https://localhost:8443

By default, if no are specified, the REST server runs on port 8083 using the HTTP protocol. When using HTTPS, the configuration has to include the SSL configuration. By default, it will use the settings. In case it is needed to use different configuration for the REST API than for connecting to Kafka brokers, the fields can be prefixed with . When using the prefix, only the prefixed options will be used and the options without the prefix will be ignored. Following fields can be used to configure HTTPS for the REST API:listenersssl.*listeners.httpsssl.*

  • ssl.keystore.location
  • ssl.keystore.password
  • ssl.keystore.type
  • ssl.key.password
  • ssl.truststore.location
  • ssl.truststore.password
  • ssl.truststore.type
  • ssl.enabled.protocols
  • ssl.provider
  • ssl.protocol
  • ssl.cipher.suites
  • ssl.keymanager.algorithm
  • ssl.secure.random.implementation
  • ssl.trustmanager.algorithm
  • ssl.endpoint.identification.algorithm
  • ssl.client.auth

The REST API is used not only by users to monitor / manage Kafka Connect. In distributed mode, it is also used for the Kafka Connect cross-cluster communication. Some requests received on the follower nodes REST API will be forwarded to the leader node REST API. In case the URI under which is given host reachable is different from the URI which it listens on, the configuration options , and can be used to change the URI which will be used by the follower nodes to connect with the leader. When using both HTTP and HTTPS listeners, the option can be also used to define which listener will be used for the cross-cluster communication. When using HTTPS for communication between nodes, the same or options will be used to configure the HTTPS client.rest.advertised.host.namerest.advertised.portrest.advertised.listenerrest.advertised.listenerssl.*listeners.https

The following are the currently supported REST API endpoints:

  • GET /connectors - return a list of active connectors
  • POST /connectors - create a new connector; the request body should be a JSON object containing a string field and an object field with the connector configuration parametersnameconfig
  • GET /connectors/{name} - get information about a specific connector
  • GET /connectors/{name}/config - get the configuration parameters for a specific connector
  • PUT /connectors/{name}/config - update the configuration parameters for a specific connector
  • GET /connectors/{name}/status - get current status of the connector, including if it is running, failed, paused, etc., which worker it is assigned to, error information if it has failed, and the state of all its tasks
  • GET /connectors/{name}/tasks - get a list of tasks currently running for a connector
  • GET /connectors/{name}/tasks/{taskid}/status - get current status of the task, including if it is running, failed, paused, etc., which worker it is assigned to, and error information if it has failed
  • PUT /connectors/{name}/pause - pause the connector and its tasks, which stops message processing until the connector is resumed. Any resources claimed by its tasks are left allocated, which allows the connector to begin processing data quickly once it is resumed.
  • PUT /connectors/{name}/stop - stop the connector and shut down its tasks, deallocating any resources claimed by its tasks. This is more efficient from a resource usage standpoint than pausing the connector, but can cause it to take longer to begin processing data once resumed.
  • PUT /connectors/{name}/resume - resume a paused or stopped connector (or do nothing if the connector is not paused or stopped)
  • POST /connectors/{name}/restart?includeTasks=<true|false>&onlyFailed=<true|false> - restart a connector and its tasks instances.
    • the "includeTasks" parameter specifies whether to restart the connector instance and task instances ("includeTasks=true") or just the connector instance ("includeTasks=false"), with the default ("false") preserving the same behavior as earlier versions.
    • the "onlyFailed" parameter specifies whether to restart just the instances with a FAILED status ("onlyFailed=true") or all instances ("onlyFailed=false"), with the default ("false") preserving the same behavior as earlier versions.
  • POST /connectors/{name}/tasks/{taskId}/restart - restart an individual task (typically because it has failed)
  • DELETE /connectors/{name} - delete a connector, halting all tasks and deleting its configuration
  • GET /connectors/{name}/topics - get the set of topics that a specific connector is using since the connector was created or since a request to reset its set of active topics was issued
  • PUT /connectors/{name}/topics/reset - send a request to empty the set of active topics of a connector
  • GET /connectors/{name}/offsets - get the current offsets for a connector (see KIP-875 for more details)

Kafka Connect also provides a REST API for getting information about connector plugins:

  • GET /connector-plugins- return a list of connector plugins installed in the Kafka Connect cluster. Note that the API only checks for connectors on the worker that handles the request, which means you may see inconsistent results, especially during a rolling upgrade if you add new connector jars
  • PUT /connector-plugins/{connector-type}/config/validate - validate the provided configuration values against the configuration definition. This API performs per config validation, returns suggested values and error messages during validation.

The following is a supported REST request at the top-level (root) endpoint:

  • GET /- return basic information about the Kafka Connect cluster such as the version of the Connect worker that serves the REST request (including git commit ID of the source code) and the Kafka cluster ID that is connected to.

For the complete specification of the REST API, see the OpenAPI documentation

Error Reporting in Connect

Kafka Connect provides error reporting to handle errors encountered along various stages of processing. By default, any error encountered during conversion or within transformations will cause the connector to fail. Each connector configuration can also enable tolerating such errors by skipping them, optionally writing each error and the details of the failed operation and problematic record (with various levels of detail) to the Connect application log. These mechanisms also capture errors when a sink connector is processing the messages consumed from its Kafka topics, and all of the errors can be written to a configurable "dead letter queue" (DLQ) Kafka topic.

To report errors within a connector's converter, transforms, or within the sink connector itself to the log, set in the connector configuration to log details of each error and problem record's topic, partition, and offset. For additional debugging purposes, set to also log the problem record key, value, and headers to the log (note this may log sensitive information).errors.log.enable=trueerrors.log.include.messages=true

To report errors within a connector's converter, transforms, or within the sink connector itself to a dead letter queue topic, set , and optionally .errors.deadletterqueue.topic.nameerrors.deadletterqueue.context.headers.enable=true

By default connectors exhibit "fail fast" behavior immediately upon an error or exception. This is equivalent to adding the following configuration properties with their defaults to a connector configuration:

# disable retries on failure
errors.retry.timeout=0

# do not log the error and their contexts
errors.log.enable=false

# do not record errors in a dead letter queue topic
errors.deadletterqueue.topic.name=

# Fail on first error
errors.tolerance=none

These and other related connector configuration properties can be changed to provide different behavior. For example, the following configuration properties can be added to a connector configuration to setup error handling with multiple retries, logging to the application logs and the Kafka topic, and tolerating all errors by reporting them rather than failing the connector task:my-connector-errors

# retry for at most 10 minutes times waiting up to 30 seconds between consecutive failures
errors.retry.timeout=600000
errors.retry.delay.max.ms=30000

# log error context along with application logs, but do not include configs and messages
errors.log.enable=true
errors.log.include.messages=false

# produce error context into the Kafka topic
errors.deadletterqueue.topic.name=my-connector-errors

# Tolerate all errors.
errors.tolerance=all

Exactly-once support

Kafka Connect is capable of providing exactly-once semantics for sink connectors (as of version 0.11.0) and source connectors (as of version 3.3.0). Please note that support for exactly-once semantics is highly dependent on the type of connector you run. Even if you set all the correct worker properties in the configuration for each node in a cluster, if a connector is not designed to, or cannot take advantage of the capabilities of the Kafka Connect framework, exactly-once may not be possible.

Sink connectors

If a sink connector supports exactly-once semantics, to enable exactly-once at the Connect worker level, you must ensure its consumer group is configured to ignore records in aborted transactions. You can do this by setting the worker property to or, if running a version of Kafka Connect that supports it, using a connector client config override policy that allows the property to be set to in individual connector configs. There are no additional ACL requirements.consumer.isolation.levelread_committedconsumer.override.isolation.levelread_committed

Source connectors

If a source connector supports exactly-once semantics, you must configure your Connect cluster to enable framework-level support for exactly-once source connectors. Additional ACLs may be necessary if running against a secured Kafka cluster. Note that exactly-once support for source connectors is currently only available in distributed mode; standalone Connect workers cannot provide exactly-once semantics.

Worker configuration

For new Connect clusters, set the property to in the worker config for each node in the cluster. For existing clusters, two rolling upgrades are necessary. During the first upgrade, the property should be set to , and during the second, it should be set to .exactly.once.source.supportenabledexactly.once.source.supportpreparingenabled

ACL requirements

With exactly-once source support enabled, the principal for each Connect worker will require the following ACLs:

Operation Resource Type Resource Name Note
Write TransactionalId connect-cluster-${groupId}, where is the of the cluster${groupId}group.id
Describe TransactionalId connect-cluster-${groupId}, where is the of the cluster${groupId}group.id
IdempotentWrite Cluster ID of the Kafka cluster that hosts the worker's config topic The IdempotentWrite ACL has been deprecated as of 2.8 and will only be necessary for Connect clusters running on pre-2.8 Kafka clusters

And the principal for each individual connector will require the following ACLs:

Operation Resource Type Resource Name Note
Write TransactionalId ${groupId}-${connector}-${taskId}, for each task that the connector will create, where is the of the Connect cluster, is the name of the connector, and is the ID of the task (starting from zero)${groupId}group.id${connector}${taskId} A wildcard prefix of can be used for convenience if there is no risk of conflict with other transactional IDs or if conflicts are acceptable to the user.${groupId}-${connector}*
Describe TransactionalId ${groupId}-${connector}-${taskId}, for each task that the connector will create, where is the of the Connect cluster, is the name of the connector, and is the ID of the task (starting from zero)${groupId}group.id${connector}${taskId} A wildcard prefix of can be used for convenience if there is no risk of conflict with other transactional IDs or if conflicts are acceptable to the user.${groupId}-${connector}*
Write Topic Offsets topic used by the connector, which is either the value of the property in the connector’s configuration if provided, or the value of the property in the worker’s configuration if not.offsets.storage.topicoffsets.storage.topic
Read Topic Offsets topic used by the connector, which is either the value of the property in the connector’s configuration if provided, or the value of the property in the worker’s configuration if not.offsets.storage.topicoffsets.storage.topic
Describe Topic Offsets topic used by the connector, which is either the value of the property in the connector’s configuration if provided, or the value of the property in the worker’s configuration if not.offsets.storage.topicoffsets.storage.topic
Create Topic Offsets topic used by the connector, which is either the value of the property in the connector’s configuration if provided, or the value of the property in the worker’s configuration if not.offsets.storage.topicoffsets.storage.topic Only necessary if the offsets topic for the connector does not exist yet
IdempotentWrite Cluster ID of the Kafka cluster that the source connector writes to The IdempotentWrite ACL has been deprecated as of 2.8 and will only be necessary for Connect clusters running on pre-2.8 Kafka clusters

8.3 Connector Development Guide

This guide describes how developers can write new connectors for Kafka Connect to move data between Kafka and other systems. It briefly reviews a few key concepts and then describes how to create a simple connector.

Core Concepts and APIs

Connectors and Tasks

To copy data between Kafka and another system, users create a for the system they want to pull data from or push data to. Connectors come in two flavors: import data from another system (e.g. would import a relational database into Kafka) and export data (e.g. would export the contents of a Kafka topic to an HDFS file).ConnectorSourceConnectorsJDBCSourceConnectorSinkConnectorsHDFSSinkConnector

Connectors do not perform any data copying themselves: their configuration describes the data to be copied, and the is responsible for breaking that job into a set of that can be distributed to workers. These also come in two corresponding flavors: and .ConnectorTasksTasksSourceTaskSinkTask

With an assignment in hand, each must copy its subset of the data to or from Kafka. In Kafka Connect, it should always be possible to frame these assignments as a set of input and output streams consisting of records with consistent schemas. Sometimes this mapping is obvious: each file in a set of log files can be considered a stream with each parsed line forming a record using the same schema and offsets stored as byte offsets in the file. In other cases it may require more effort to map to this model: a JDBC connector can map each table to a stream, but the offset is less clear. One possible mapping uses a timestamp column to generate queries incrementally returning new data, and the last queried timestamp can be used as the offset.Task

Streams and Records

Each stream should be a sequence of key-value records. Both the keys and values can have complex structure -- many primitive types are provided, but arrays, objects, and nested data structures can be represented as well. The runtime data format does not assume any particular serialization format; this conversion is handled internally by the framework.

In addition to the key and value, records (both those generated by sources and those delivered to sinks) have associated stream IDs and offsets. These are used by the framework to periodically commit the offsets of data that have been processed so that in the event of failures, processing can resume from the last committed offsets, avoiding unnecessary reprocessing and duplication of events.

Dynamic Connectors

Not all jobs are static, so implementations are also responsible for monitoring the external system for any changes that might require reconfiguration. For example, in the example, the might assign a set of tables to each . When a new table is created, it must discover this so it can assign the new table to one of the by updating its configuration. When it notices a change that requires reconfiguration (or a change in the number of ), it notifies the framework and the framework updates any corresponding .ConnectorJDBCSourceConnectorConnectorTaskTasksTasksTasks

Developing a Simple Connector

Developing a connector only requires implementing two interfaces, the and . A simple example is included with the source code for Kafka in the package. This connector is meant for use in standalone mode and has implementations of a / to read each line of a file and emit it as a record and a / that writes each record to a file.ConnectorTaskfileSourceConnectorSourceTaskSinkConnectorSinkTask

The rest of this section will walk through some code to demonstrate the key steps in creating a connector, but developers should also refer to the full example source code as many details are omitted for brevity.

Connector Example

We'll cover the as a simple example. implementations are very similar. Start by creating the class that inherits from and add a field that will store the configuration information to be propagated to the task(s) (the topic to send data to, and optionally - the filename to read from and the maximum batch size):SourceConnectorSinkConnectorSourceConnector

public class FileStreamSourceConnector extends SourceConnector {
    private Map<String, String> props;

The easiest method to fill in is , which defines the class that should be instantiated in worker processes to actually read the data:taskClass()

@Override
public Class<? extends Task> taskClass() {
    return FileStreamSourceTask.class;
}

We will define the class below. Next, we add some standard lifecycle methods, and :FileStreamSourceTaskstart()stop()

@Override
public void start(Map<String, String> props) {
    // Initialization logic and setting up of resources can take place in this method.
    // This connector doesn't need to do any of that, but we do log a helpful message to the user.

    this.props = props;
    AbstractConfig config = new AbstractConfig(CONFIG_DEF, props);
    String filename = config.getString(FILE_CONFIG);
    filename = (filename == null || filename.isEmpty()) ? "standard input" : config.getString(FILE_CONFIG);
    log.info("Starting file source connector reading from {}", filename);
}

@Override
public void stop() {
    // Nothing to do since no background monitoring is required.
}

Finally, the real core of the implementation is in . In this case we are only handling a single file, so even though we may be permitted to generate more tasks as per the argument, we return a list with only one entry:taskConfigs()maxTasks

@Override
public List<Map<String, String>> taskConfigs(int maxTasks) {
    // Note that the task configs could contain configs additional to or different from the connector configs if needed. For instance,
    // if different tasks have different responsibilities, or if different tasks are meant to process different subsets of the source data stream).
    ArrayList<Map<String, String>> configs = new ArrayList<>();
    // Only one input stream makes sense.
    configs.add(props);
    return configs;
}

Even with multiple tasks, this method implementation is usually pretty simple. It just has to determine the number of input tasks, which may require contacting the remote service it is pulling data from, and then divvy them up. Because some patterns for splitting work among tasks are so common, some utilities are provided in to simplify these cases.ConnectorUtils

Note that this simple example does not include dynamic input. See the discussion in the next section for how to trigger updates to task configs.

Task Example - Source Task

Next we'll describe the implementation of the corresponding . The implementation is short, but too long to cover completely in this guide. We'll use pseudo-code to describe most of the implementation, but you can refer to the source code for the full example.SourceTask

Just as with the connector, we need to create a class inheriting from the appropriate base class. It also has some standard lifecycle methods:Task

public class FileStreamSourceTask extends SourceTask {
    private String filename;
    private InputStream stream;
    private String topic;
    private int batchSize;

    @Override
    public void start(Map<String, String> props) {
        filename = props.get(FileStreamSourceConnector.FILE_CONFIG);
        stream = openOrThrowError(filename);
        topic = props.get(FileStreamSourceConnector.TOPIC_CONFIG);
        batchSize = props.get(FileStreamSourceConnector.TASK_BATCH_SIZE_CONFIG);
    }

    @Override
    public synchronized void stop() {
        stream.close();
    }

These are slightly simplified versions, but show that these methods should be relatively simple and the only work they should perform is allocating or freeing resources. There are two points to note about this implementation. First, the method does not yet handle resuming from a previous offset, which will be addressed in a later section. Second, the method is synchronized. This will be necessary because are given a dedicated thread which they can block indefinitely, so they need to be stopped with a call from a different thread in the Worker.start()stop()SourceTasks

Next, we implement the main functionality of the task, the method which gets events from the input system and returns a :poll()List<SourceRecord>

@Override
public List<SourceRecord> poll() throws InterruptedException {
    try {
        ArrayList<SourceRecord> records = new ArrayList<>();
        while (streamValid(stream) && records.isEmpty()) {
            LineAndOffset line = readToNextLine(stream);
            if (line != null) {
                Map<String, Object> sourcePartition = Collections.singletonMap("filename", filename);
                Map<String, Object> sourceOffset = Collections.singletonMap("position", streamOffset);
                records.add(new SourceRecord(sourcePartition, sourceOffset, topic, Schema.STRING_SCHEMA, line));
                if (records.size() >= batchSize) {
                    return records;
                }
            } else {
                Thread.sleep(1);
            }
        }
        return records;
    } catch (IOException e) {
        // Underlying stream was killed, probably as a result of calling stop. Allow to return
        // null, and driving thread will handle any shutdown if necessary.
    }
    return null;
}

Again, we've omitted some details, but we can see the important steps: the method is going to be called repeatedly, and for each call it will loop trying to read records from the file. For each line it reads, it also tracks the file offset. It uses this information to create an output with four pieces of information: the source partition (there is only one, the single file being read), source offset (byte offset in the file), output topic name, and output value (the line, and we include a schema indicating this value will always be a string). Other variants of the constructor can also include a specific output partition, a key, and headers.poll()SourceRecordSourceRecord

Note that this implementation uses the normal Java interface and may sleep if data is not available. This is acceptable because Kafka Connect provides each task with a dedicated thread. While task implementations have to conform to the basic interface, they have a lot of flexibility in how they are implemented. In this case, an NIO-based implementation would be more efficient, but this simple approach works, is quick to implement, and is compatible with older versions of Java.InputStreampoll()

Although not used in the example, also provides two APIs to commit offsets in the source system: and . The APIs are provided for source systems which have an acknowledgement mechanism for messages. Overriding these methods allows the source connector to acknowledge messages in the source system, either in bulk or individually, once they have been written to Kafka. The API stores the offsets in the source system, up to the offsets that have been returned by . The implementation of this API should block until the commit is complete. The API saves the offset in the source system for each after it is written to Kafka. As Kafka Connect will record offsets automatically, s are not required to implement them. In cases where a connector does need to acknowledge messages in the source system, only one of the APIs is typically required.SourceTaskcommitcommitRecordcommitpollcommitRecordSourceRecordSourceTask

Sink Tasks

The previous section described how to implement a simple . Unlike and , and have very different interfaces because uses a pull interface and uses a push interface. Both share the common lifecycle methods, but the interface is quite different:SourceTaskSourceConnectorSinkConnectorSourceTaskSinkTaskSourceTaskSinkTaskSinkTask

public abstract class SinkTask implements Task {
    public void initialize(SinkTaskContext context) {
        this.context = context;
    }

    public abstract void put(Collection<SinkRecord> records);

    public void flush(Map<TopicPartition, OffsetAndMetadata> currentOffsets) {
    }

The documentation contains full details, but this interface is nearly as simple as the . The method should contain most of the implementation, accepting sets of , performing any required translation, and storing them in the destination system. This method does not need to ensure the data has been fully written to the destination system before returning. In fact, in many cases internal buffering will be useful so an entire batch of records can be sent at once, reducing the overhead of inserting events into the downstream data store. The contain essentially the same information as : Kafka topic, partition, offset, the event key and value, and optional headers.SinkTaskSourceTaskput()SinkRecordsSinkRecordsSourceRecords

The method is used during the offset commit process, which allows tasks to recover from failures and resume from a safe point such that no events will be missed. The method should push any outstanding data to the destination system and then block until the write has been acknowledged. The parameter can often be ignored, but is useful in some cases where implementations want to store offset information in the destination store to provide exactly-once delivery. For example, an HDFS connector could do this and use atomic move operations to make sure the operation atomically commits the data and offsets to a final location in HDFS.flush()offsetsflush()

Errant Record Reporter

When error reporting is enabled for a connector, the connector can use an to report problems with individual records sent to a sink connector. The following example shows how a connector's subclass might obtain and use the , safely handling a null reporter when the DLQ is not enabled or when the connector is installed in an older Connect runtime that doesn't have this reporter feature:ErrantRecordReporterSinkTaskErrantRecordReporter

private ErrantRecordReporter reporter;

@Override
public void start(Map<String, String> props) {
    ...
    try {
        reporter = context.errantRecordReporter(); // may be null if DLQ not enabled
    } catch (NoSuchMethodException | NoClassDefFoundError e) {
        // Will occur in Connect runtimes earlier than 2.6
        reporter = null;
    }
}

@Override
public void put(Collection<SinkRecord> records) {
    for (SinkRecord record: records) {
        try {
            // attempt to process and send record to data sink
            process(record);
        } catch(Exception e) {
            if (reporter != null) {
                // Send errant record to error reporter
                reporter.report(record, e);
            } else {
                // There's no error reporter, so fail
                throw new ConnectException("Failed on record", e);
            }
        }
    }
}
Resuming from Previous Offsets

The implementation included a stream ID (the input filename) and offset (position in the file) with each record. The framework uses this to commit offsets periodically so that in the case of a failure, the task can recover and minimize the number of events that are reprocessed and possibly duplicated (or to resume from the most recent offset if Kafka Connect was stopped gracefully, e.g. in standalone mode or due to a job reconfiguration). This commit process is completely automated by the framework, but only the connector knows how to seek back to the right position in the input stream to resume from that location.SourceTask

To correctly resume upon startup, the task can use the passed into its method to access the offset data. In , we would add a bit more code to read the offset (if it exists) and seek to that position:SourceContextinitialize()initialize()

stream = new FileInputStream(filename);
Map<String, Object> offset = context.offsetStorageReader().offset(Collections.singletonMap(FILENAME_FIELD, filename));
if (offset != null) {
    Long lastRecordedOffset = (Long) offset.get("position");
    if (lastRecordedOffset != null)
        seekToOffset(stream, lastRecordedOffset);
}

Of course, you might need to read many keys for each of the input streams. The interface also allows you to issue bulk reads to efficiently load all offsets, then apply them by seeking each input stream to the appropriate position.OffsetStorageReader

Exactly-once source connectors
Supporting exactly-once

With the passing of KIP-618, Kafka Connect supports exactly-once source connectors as of version 3.3.0. In order for a source connector to take advantage of this support, it must be able to provide meaningful source offsets for each record that it emits, and resume consumption from the external system at the exact position corresponding to any of those offsets without dropping or duplicating messages.

Defining transaction boundaries

By default, the Kafka Connect framework will create and commit a new Kafka transaction for each batch of records that a source task returns from its method. However, connectors can also define their own transaction boundaries, which can be enabled by users by setting the property to in the config for the connector.polltransaction.boundaryconnector

If enabled, the connector's tasks will have access to a from their , which they can use to control when transactions are aborted and committed.TransactionContextSourceTaskContext

For example, to commit a transaction at least every ten records:

private int recordsSent;

@Override
public void start(Map<String, String> props) {
    this.recordsSent = 0;
}

@Override
public List<SourceRecord> poll() {
    List<SourceRecord> records = fetchRecords();
    boolean shouldCommit = false;
    for (SourceRecord record : records) {
        if (++this.recordsSent >= 10) {
            shouldCommit = true;
        }
    }
    if (shouldCommit) {
        this.recordsSent = 0;
        this.context.transactionContext().commitTransaction();
    }
    return records;
}

Or to commit a transaction for exactly every tenth record:

private int recordsSent;

@Override
public void start(Map<String, String> props) {
    this.recordsSent = 0;
}

@Override
public List<SourceRecord> poll() {
    List<SourceRecord> records = fetchRecords();
    for (SourceRecord record : records) {
        if (++this.recordsSent % 10 == 0) {
            this.context.transactionContext().commitTransaction(record);
        }
    }
    return records;
}

Most connectors do not need to define their own transaction boundaries. However, it may be useful if files or objects in the source system are broken up into multiple source records, but should be delivered atomically. Additionally, it may be useful if it is impossible to give each source record a unique source offset, if every record with a given offset is delivered within a single transaction.

Note that if the user has not enabled connector-defined transaction boundaries in the connector configuration, the returned by will be .TransactionContextcontext.transactionContext()null

Validation APIs

A few additional preflight validation APIs can be implemented by source connector developers.

Some users may require exactly-once semantics from a connector. In this case, they may set the property to in the configuration for the connector. When this happens, the Kafka Connect framework will ask the connector whether it can provide exactly-once semantics with the specified configuration. This is done by invoking the method on the connector.exactly.once.supportrequiredexactlyOnceSupport

If a connector doesn't support exactly-once semantics, it should still implement this method to let users know for certain that it cannot provide exactly-once semantics:

@Override
public ExactlyOnceSupport exactlyOnceSupport(Map<String, String> props) {
    // This connector cannot provide exactly-once semantics under any conditions
    return ExactlyOnceSupport.UNSUPPORTED;
}

Otherwise, a connector should examine the configuration, and return if it can provide exactly-once semantics:ExactlyOnceSupport.SUPPORTED

@Override
public ExactlyOnceSupport exactlyOnceSupport(Map<String, String> props) {
    // This connector can always provide exactly-once semantics
    return ExactlyOnceSupport.SUPPORTED;
}

Additionally, if the user has configured the connector to define its own transaction boundaries, the Kafka Connect framework will ask the connector whether it can define its own transaction boundaries with the specified configuration, using the method:canDefineTransactionBoundaries

@Override
public ConnectorTransactionBoundaries canDefineTransactionBoundaries(Map<String, String> props) {
    // This connector can always define its own transaction boundaries
    return ConnectorTransactionBoundaries.SUPPORTED;
}

This method should only be implemented for connectors that can define their own transaction boundaries in some cases. If a connector is never able to define its own transaction boundaries, it does not need to implement this method.

Dynamic Input/Output Streams

Kafka Connect is intended to define bulk data copying jobs, such as copying an entire database rather than creating many jobs to copy each table individually. One consequence of this design is that the set of input or output streams for a connector can vary over time.

Source connectors need to monitor the source system for changes, e.g. table additions/deletions in a database. When they pick up changes, they should notify the framework via the object that reconfiguration is necessary. For example, in a :ConnectorContextSourceConnector

if (inputsChanged())
    this.context.requestTaskReconfiguration();

The framework will promptly request new configuration information and update the tasks, allowing them to gracefully commit their progress before reconfiguring them. Note that in the this monitoring is currently left up to the connector implementation. If an extra thread is required to perform this monitoring, the connector must allocate it itself.SourceConnector

Ideally this code for monitoring changes would be isolated to the and tasks would not need to worry about them. However, changes can also affect tasks, most commonly when one of their input streams is destroyed in the input system, e.g. if a table is dropped from a database. If the encounters the issue before the , which will be common if the needs to poll for changes, the will need to handle the subsequent error. Thankfully, this can usually be handled simply by catching and handling the appropriate exception.ConnectorTaskConnectorConnectorTask

SinkConnectors usually only have to handle the addition of streams, which may translate to new entries in their outputs (e.g., a new database table). The framework manages any changes to the Kafka input, such as when the set of input topics changes because of a regex subscription. should expect new input streams, which may require creating new resources in the downstream system, such as a new table in a database. The trickiest situation to handle in these cases may be conflicts between multiple seeing a new input stream for the first time and simultaneously trying to create the new resource. , on the other hand, will generally require no special code for handling a dynamic set of streams.SinkTasksSinkTasksSinkConnectors

Configuration Validation

Kafka Connect allows you to validate connector configurations before submitting a connector to be executed and can provide feedback about errors and recommended values. To take advantage of this, connector developers need to provide an implementation of to expose the configuration definition to the framework.config()

The following code in defines the configuration and exposes it to the framework.FileStreamSourceConnector

static final ConfigDef CONFIG_DEF = new ConfigDef()
    .define(FILE_CONFIG, Type.STRING, null, Importance.HIGH, "Source filename. If not specified, the standard input will be used")
    .define(TOPIC_CONFIG, Type.STRING, ConfigDef.NO_DEFAULT_VALUE, new ConfigDef.NonEmptyString(), Importance.HIGH, "The topic to publish data to")
    .define(TASK_BATCH_SIZE_CONFIG, Type.INT, DEFAULT_TASK_BATCH_SIZE, Importance.LOW,
        "The maximum number of records the source task can read from the file each time it is polled");

public ConfigDef config() {
    return CONFIG_DEF;
}

ConfigDef class is used for specifying the set of expected configurations. For each configuration, you can specify the name, the type, the default value, the documentation, the group information, the order in the group, the width of the configuration value and the name suitable for display in the UI. Plus, you can provide special validation logic used for single configuration validation by overriding the class. Moreover, as there may be dependencies between configurations, for example, the valid values and visibility of a configuration may change according to the values of other configurations. To handle this, allows you to specify the dependents of a configuration and to provide an implementation of to get valid values and set visibility of a configuration given the current configuration values.ValidatorConfigDefRecommender

Also, the method in provides a default validation implementation which returns a list of allowed configurations together with configuration errors and recommended values for each configuration. However, it does not use the recommended values for configuration validation. You may provide an override of the default implementation for customized configuration validation, which may use the recommended values.validate()Connector

Working with Schemas

The FileStream connectors are good examples because they are simple, but they also have trivially structured data -- each line is just a string. Almost all practical connectors will need schemas with more complex data formats.

To create more complex data, you'll need to work with the Kafka Connect API. Most structured records will need to interact with two classes in addition to primitive types: and .dataSchemaStruct

The API documentation provides a complete reference, but here is a simple example creating a and :SchemaStruct

Schema schema = SchemaBuilder.struct().name(NAME)
    .field("name", Schema.STRING_SCHEMA)
    .field("age", Schema.INT_SCHEMA)
    .field("admin", SchemaBuilder.bool().defaultValue(false).build())
    .build();

Struct struct = new Struct(schema)
    .put("name", "Barbara Liskov")
    .put("age", 75);

If you are implementing a source connector, you'll need to decide when and how to create schemas. Where possible, you should avoid recomputing them as much as possible. For example, if your connector is guaranteed to have a fixed schema, create it statically and reuse a single instance.

However, many connectors will have dynamic schemas. One simple example of this is a database connector. Considering even just a single table, the schema will not be predefined for the entire connector (as it varies from table to table). But it also may not be fixed for a single table over the lifetime of the connector since the user may execute an command. The connector must be able to detect these changes and react appropriately.ALTER TABLE

Sink connectors are usually simpler because they are consuming data and therefore do not need to create schemas. However, they should take just as much care to validate that the schemas they receive have the expected format. When the schema does not match -- usually indicating the upstream producer is generating invalid data that cannot be correctly translated to the destination system -- sink connectors should throw an exception to indicate this error to the system.

8.4 Administration

Kafka Connect's REST layer provides a set of APIs to enable administration of the cluster. This includes APIs to view the configuration of connectors and the status of their tasks, as well as to alter their current behavior (e.g. changing configuration and restarting tasks).

When a connector is first submitted to the cluster, a rebalance is triggered between the Connect workers in order to distribute the load that consists of the tasks of the new connector. This same rebalancing procedure is also used when connectors increase or decrease the number of tasks they require, when a connector's configuration is changed, or when a worker is added or removed from the group as part of an intentional upgrade of the Connect cluster or due to a failure.

In versions prior to 2.3.0, the Connect workers would rebalance the full set of connectors and their tasks in the cluster as a simple way to make sure that each worker has approximately the same amount of work. This behavior can be still enabled by setting . connect.protocol=eager

Starting with 2.3.0, Kafka Connect is using by default a protocol that performs incremental cooperative rebalancing that incrementally balances the connectors and tasks across the Connect workers, affecting only tasks that are new, to be removed, or need to move from one worker to another. Other tasks are not stopped and restarted during the rebalance, as they would have been with the old protocol.

If a Connect worker leaves the group, intentionally or due to a failure, Connect waits for before triggering a rebalance. This delay defaults to five minutes () to tolerate failures or upgrades of workers without immediately redistributing the load of a departing worker. If this worker returns within the configured delay, it gets its previously assigned tasks in full. However, this means that the tasks will remain unassigned until the time specified by elapses. If a worker does not return within that time limit, Connect will reassign those tasks among the remaining workers in the Connect cluster. scheduled.rebalance.max.delay.ms300000msscheduled.rebalance.max.delay.ms

The new Connect protocol is enabled when all the workers that form the Connect cluster are configured with , which is also the default value when this property is missing. Therefore, upgrading to the new Connect protocol happens automatically when all the workers upgrade to 2.3.0. A rolling upgrade of the Connect cluster will activate incremental cooperative rebalancing when the last worker joins on version 2.3.0. connect.protocol=compatible

You can use the REST API to view the current status of a connector and its tasks, including the ID of the worker to which each was assigned. For example, the request shows the status of a connector named : GET /connectors/file-source/statusfile-source

{
    "name": "file-source",
    "connector": {
        "state": "RUNNING",
        "worker_id": "192.168.1.208:8083"
    },
    "tasks": [
        {
        "id": 0,
        "state": "RUNNING",
        "worker_id": "192.168.1.209:8083"
        }
    ]
}

Connectors and their tasks publish status updates to a shared topic (configured with ) which all workers in the cluster monitor. Because the workers consume this topic asynchronously, there is typically a (short) delay before a state change is visible through the status API. The following states are possible for a connector or one of its tasks: status.storage.topic

  • UNASSIGNED: The connector/task has not yet been assigned to a worker.
  • RUNNING: The connector/task is running.
  • PAUSED: The connector/task has been administratively paused.
  • STOPPED: The connector has been stopped. Note that this state is not applicable to tasks because the tasks for a stopped connector are shut down and won't be visible in the status API.
  • FAILED: The connector/task has failed (usually by raising an exception, which is reported in the status output).
  • RESTARTING: The connector/task is either actively restarting or is expected to restart soon

In most cases, connector and task states will match, though they may be different for short periods of time when changes are occurring or if tasks have failed. For example, when a connector is first started, there may be a noticeable delay before the connector and its tasks have all transitioned to the RUNNING state. States will also diverge when tasks fail since Connect does not automatically restart failed tasks. To restart a connector/task manually, you can use the restart APIs listed above. Note that if you try to restart a task while a rebalance is taking place, Connect will return a 409 (Conflict) status code. You can retry after the rebalance completes, but it might not be necessary since rebalances effectively restart all the connectors and tasks in the cluster.

Starting with 2.5.0, Kafka Connect uses the to also store information related to the topics that each connector is using. Connect Workers use these per-connector topic status updates to respond to requests to the REST endpoint by returning the set of topic names that a connector is using. A request to the REST endpoint resets the set of active topics for a connector and allows a new set to be populated, based on the connector's latest pattern of topic usage. Upon connector deletion, the set of the connector's active topics is also deleted. Topic tracking is enabled by default but can be disabled by setting . If you want to disallow requests to reset the active topics of connectors during runtime, set the Worker property . status.storage.topicGET /connectors/{name}/topicsPUT /connectors/{name}/topics/resettopic.tracking.enable=falsetopic.tracking.allow.reset=false

It's sometimes useful to temporarily stop the message processing of a connector. For example, if the remote system is undergoing maintenance, it would be preferable for source connectors to stop polling it for new data instead of filling logs with exception spam. For this use case, Connect offers a pause/resume API. While a source connector is paused, Connect will stop polling it for additional records. While a sink connector is paused, Connect will stop pushing new messages to it. The pause state is persistent, so even if you restart the cluster, the connector will not begin message processing again until the task has been resumed. Note that there may be a delay before all of a connector's tasks have transitioned to the PAUSED state since it may take time for them to finish whatever processing they were in the middle of when being paused. Additionally, failed tasks will not transition to the PAUSED state until they have been restarted.

In 3.5.0, Connect introduced a stop API that completely shuts down the tasks for a connector and deallocates any resources claimed by them. This is different from pausing a connector where tasks are left idling and any resources claimed by them are left allocated (which allows the connector to begin processing data quickly once it is resumed). Stopping a connector is more efficient from a resource usage standpoint than pausing it, but can cause it to take longer to begin processing data once resumed.

9. kafka流

Kafka Streams 是一个客户端库,用于处理和分析存储在 Kafka 中的数据。它建立在重要的流处理概念之上,例如正确区分事件时间和处理时间、窗口支持、恰好一次处理语义以及简单而高效的应用程序状态管理。

Kafka Streams 的进入门槛很低:您可以在单台机器上快速编写和运行小规模的概念验证;您只需在多台计算机上运行应用程序的其他实例,即可扩展到大批量生产工作负载。Kafka Streams 利用 Kafka 的并行模型以透明方式处理同一应用程序的多个实例的负载均衡。

要了解有关 Kafka Streams 的更多信息,请阅读本节

APP信息