Kafka 0.11.0.0 实现 producer的Exactly-once 语义(官方DEMO)
<dependency>
<groupId>org.apache.kafka</groupId>
<artifactId>kafka-clients</artifactId>
<version>0.11.0.2</version>
</dependency>
public class KafkaProducer<K,V>
extends java.lang.Object
implements Producer<K,V>
The producer is thread safe and sharing a single producer instance across threads will generally be faster than having multiple instances.
Here is a simple example of using the producer to send records with strings containing sequential numbers as the key/value pairs.
Properties props = new Properties();
props.put("bootstrap.servers", "localhost:9092");
props.put("acks", "all");
props.put("retries", );
props.put("batch.size", );
props.put("linger.ms", );
props.put("buffer.memory", );
props.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer");
props.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer"); Producer<String, String> producer = new KafkaProducer<>(props);
for (int i = ; i < ; i++)
producer.send(new ProducerRecord<String, String>("my-topic", Integer.toString(i), Integer.toString(i))); producer.close();
The producer consists of a pool of buffer space that holds records that haven't yet been transmitted to the server as well as a background I/O thread that is responsible for turning these records into requests and transmitting them to the cluster. Failure to close the producer after use will leak these resources.
The send()
method is asynchronous. When called it adds the record to a buffer of pending record sends and immediately returns. This allows the producer to batch together individual records for efficiency.
The acks
config controls the criteria under which requests are considered complete. The "all" setting we have specified will result in blocking on the full commit of the record, the slowest but most durable setting.
If the request fails, the producer can automatically retry, though since we have specified retries
as 0 it won't. Enabling retries also opens up the possibility of duplicates (see the documentation on message delivery semantics for details).
The producer maintains buffers of unsent records for each partition. These buffers are of a size specified by the batch.size
config. Making this larger can result in more batching, but requires more memory (since we will generally have one of these buffers for each active partition).
By default a buffer is available to send immediately even if there is additional unused space in the buffer. However if you want to reduce the number of requests you can set linger.ms
to something greater than 0. This will instruct the producer to wait up to that number of milliseconds before sending a request in hope that more records will arrive to fill up the same batch. This is analogous to Nagle's algorithm in TCP. For example, in the code snippet above, likely all 100 records would be sent in a single request since we set our linger time to 1 millisecond. However this setting would add 1 millisecond of latency to our request waiting for more records to arrive if we didn't fill up the buffer. Note that records that arrive close together in time will generally batch together even with linger.ms=0
so under heavy load batching will occur regardless of the linger configuration; however setting this to something larger than 0 can lead to fewer, more efficient requests when not under maximal load at the cost of a small amount of latency.
The buffer.memory
controls the total amount of memory available to the producer for buffering. If records are sent faster than they can be transmitted to the server then this buffer space will be exhausted. When the buffer space is exhausted additional send calls will block. The threshold for time to block is determined by max.block.ms
after which it throws a TimeoutException.
The key.serializer
and value.serializer
instruct how to turn the key and value objects the user provides with their ProducerRecord
into bytes. You can use the included ByteArraySerializer
or StringSerializer
for simple string or byte types.
From Kafka 0.11, the KafkaProducer supports two additional modes: the idempotent producer and the transactional producer. The idempotent producer strengthens Kafka's delivery semantics from at least once to exactly once delivery. In particular producer retries will no longer introduce duplicates. The transactional producer allows an application to send messages to multiple partitions (and topics!) atomically.
To enable idempotence, the enable.idempotence
configuration must be set to true. If set, the retries
config will be defaulted to Integer.MAX_VALUE
, the max.in.flight.requests.per.connection
config will be defaulted to 1
, and acks
config will be defaulted to all
. There are no API changes for the idempotent producer, so existing applications will not need to be modified to take advantage of this feature.
To take advantage of the idempotent producer, it is imperative to avoid application level re-sends since these cannot be de-duplicated. As such, if an application enables idempotence, it is recommended to leave the retries
config unset, as it will be defaulted to Integer.MAX_VALUE
. Additionally, if a send(ProducerRecord)
returns an error even with infinite retries (for instance if the message expires in the buffer before being sent), then it is recommended to shut down the producer and check the contents of the last produced message to ensure that it is not duplicated. Finally, the producer can only guarantee idempotence for messages sent within a single session.
To use the transactional producer and the attendant APIs, you must set the transactional.id
configuration property. If the transactional.id
is set, idempotence is automatically enabled along with the producer configs which idempotence depends on. Further, topics which are included in transactions should be configured for durability. In particular, the replication.factor
should be at least 3
, and the min.insync.replicas
for these topics should be set to 2. Finally, in order for transactional guarantees to be realized from end-to-end, the consumers must be configured to read only committed messages as well.
The purpose of the transactional.id
is to enable transaction recovery across multiple sessions of a single producer instance. It would typically be derived from the shard identifier in a partitioned, stateful, application. As such, it should be unique to each producer instance running within a partitioned application.
All the new transactional APIs are blocking and will throw exceptions on failure. The example below illustrates how the new APIs are meant to be used. It is similar to the example above, except that all 100 messages are part of a single transaction.
Properties props = new Properties();
props.put("bootstrap.servers", "localhost:9092");
props.put("transactional.id", "my-transactional-id");
Producer<String, String> producer = new KafkaProducer<>(props, new StringSerializer(), new StringSerializer()); producer.initTransactions(); try {
producer.beginTransaction();
for (int i = ; i < ; i++)
producer.send(new ProducerRecord<>("my-topic", Integer.toString(i), Integer.toString(i)));
producer.commitTransaction();
} catch (ProducerFencedException | OutOfOrderSequenceException | AuthorizationException e) {
// We can't recover from these exceptions, so our only option is to close the producer and exit.
producer.close();
} catch (KafkaException e) {
// For all other exceptions, just abort the transaction and try again.
producer.abortTransaction();
}
producer.close();
As is hinted at in the example, there can be only one open transaction per producer. All messages sent between the beginTransaction()
and commitTransaction()
calls will be part of a single transaction. When the transactional.id
is specified, all messages sent by the producer must be part of a transaction.
The transactional producer uses exceptions to communicate error states. In particular, it is not required to specify callbacks for producer.send()
or to call .get()
on the returned Future: a KafkaException
would be thrown if any of the producer.send()
or transactional calls hit an irrecoverable error during a transaction. See the send(ProducerRecord)
documentation for more details about detecting errors from a transactional send.
By calling producer.abortTransaction()
upon receiving a KafkaException
we can ensure that any successful writes are marked as aborted, hence keeping the transactional guarantees.
This client can communicate with brokers that are version 0.10.0 or newer. Older or newer brokers may not support certain client features. For instance, the transactional APIs need broker versions 0.11.0 or later. You will receive an UnsupportedVersionException
when invoking an API that is not available in the running broker version.
Kafka 0.11.0.0 实现 producer的Exactly-once 语义(官方DEMO)的更多相关文章
- Kafka设计解析(二十二)Flink + Kafka 0.11端到端精确一次处理语义的实现
转载自 huxihx,原文链接 [译]Flink + Kafka 0.11端到端精确一次处理语义的实现 本文是翻译作品,作者是Piotr Nowojski和Michael Winters.前者是该方案 ...
- PHP 5.5.38 + mysql 5.0.11 + zabbix3.0 + nginx 安装
PHP 5.5.38 + mysql 5.0.11 + zabbix3.0 + nginx 1.首先在安装好环境下安装 zabbix3.0情况下 2. yum install mysql-devel ...
- 【译】Flink + Kafka 0.11端到端精确一次处理语义的实现
本文是翻译作品,作者是Piotr Nowojski和Michael Winters.前者是该方案的实现者. 原文地址是https://data-artisans.com/blog/end-to-end ...
- cocos2d-x v3.0各个环境下创建项目以及编译、执行官方DEMO
摘自:https://github.com/cocos2d/cocos2d-x/ 怎样创建一个新项目 How to start a new game Download the code from co ...
- 探索Oracle数据库升级6 11.2.0.4.3 Upgrade12c(12.1.0.1)
探索Oracle数据库升级6 11.2.0.4.3 Upgrade12c(12.1.0.1) 一.前言: Oracle 12c公布距今已经一年有余了,其最大亮点是一个能够插拔的数据库(PD ...
- Mysql8.0.11安装以及注意事项
一.环境配置 首先在官网下载最新的mysql8.0.11数据库,解压到你需要放置的盘符最好不要有中文,然后新建MYSQL_HOME,参数为mysql解压后安装文件的bin文件路径如我的:变量名:MYS ...
- CENTOS7下安装REDIS4.0.11
拷贝收藏私用,别无他意,原博客地址: https://www.cnblogs.com/zuidongfeng/p/8032505.html 1.安装redis 第一步:下载redis安装包 wget ...
- Patch 21352635 - Database Patch Set Update 11.2.0.4.8
一.CPU和PSU 近日,将数据库从9.2.0.6升级到11.2.0.4后,发现11.2.0.4通过DBLINK访问其他的9i库时发生ORA-02072错误,通过Google找到解决方案,即升级到PS ...
- Downgrade ASM DATABASE_COMPATIBILITY (from 11.2.0.4.0 to 11.2.0.0.0) on 12C CRS stack.
使用Onecommand完成快速Oracle 12c RAC部署后 发现ASM database compatibilty无法设置,默认为11.2.0.4.0. 由于我们还有些数据库低于这个版本,所以 ...
- [linux]centos7.4上安装MySQL-8.0.11【完美安装】
版本声明 centos7.4 MySQL-8.0.11 1.我用的阿里云的虚拟主机,刚从windows换到linux,需要装下常用工具 #安装下sz rz常用到上传下载的命令 yum install ...
随机推荐
- Python爬虫入门教程 24-100 微医挂号网医生数据抓取
1. 写在前面 今天要抓取的一个网站叫做微医网站,地址为 https://www.guahao.com ,我们将通过python3爬虫抓取这个网址,然后数据存储到CSV里面,为后面的一些分析类的教程做 ...
- C#版 - PAT乙级(Basic Level)真题 之 1021.个位数统计 - 题解
版权声明: 本文为博主Bravo Yeung(知乎UserName同名)的原创文章,欲转载请先私信获博主允许,转载时请附上网址 http://blog.csdn.net/lzuacm. C#版 - P ...
- SpringBoot入门教程(十二)DevTools热部署
devtools模块,是为开发者服务的一个模块.主要的功能就是代码修改后一般在5秒之内就会自动重新加载至服务器,相当于restart成功.与JRebel不同的是,JRebel是一款商业插件,devto ...
- PL/SQL基础语法入门
先前安装了PL/SQL软件 PL/SQL全称为Procedural Language/SQL. PL/SQL也是一种程序语言,叫做过程化SQL语言,是Oracle数据库对SQL语句的扩展 打PL/SQ ...
- python学习第一讲,python简介
目录 python学习第一讲,python简介 一丶python简介 1.解释型语言与编译型语言 2.python的特点 3.python的优缺点 二丶第一个python程序 1.python源程序概 ...
- 痞子衡嵌入式:语音处理工具Jays-PySPEECH诞生记(5)- 语音识别实现(SpeechRecognition, PocketSphinx0.1.15)
大家好,我是痞子衡,是正经搞技术的痞子.今天痞子衡给大家介绍的是语音处理工具Jays-PySPEECH诞生之语音识别实现. 语音识别是Jays-PySPEECH的核心功能,Jays-PySPEECH借 ...
- 解读经典《C#高级编程》泛型 页122-127.章4
前言 本篇继续讲解泛型.上一篇讲解了泛型类的创建.本篇讲解泛型类创建和使用的细节. 泛型类 上篇举了个我产品中用到的例子,本篇的功能可以对照着此案例进行理解. /// <summary> ...
- Spring Cloud Alibaba基础教程:支持的几种服务消费方式(RestTemplate、WebClient、Feign)
通过<Spring Cloud Alibaba基础教程:使用Nacos实现服务注册与发现>一文的学习,我们已经学会如何使用Nacos来实现服务的注册与发现,同时也介绍如何通过LoadBal ...
- 【转载】C#处理空格和换行
使用C#处理字符串是一个常见的情况,当字符串中含有空格或者换行符号的时候,如果业务需要,我们可以通过相应的方法将之处理掉,处理成不含空格和换行符号的字符串,处理的过程使用到正则表达式. 具体函数处理的 ...
- C# 如何在Excel表格中插入、编辑和删除批注
概述 为文档添加必要的批注可以给文档使用者提供重要的提示信息,下面的示例中,将介绍通过C#编程语言来给Excel表格中的指定单元格内容添加批注,此外,对于已有的批注,如果需要修改,我们也可以进行编辑或 ...