博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Kafka 发送消息 Idempotent
阅读量:4051 次
发布时间:2019-05-25

本文共 1825 字,大约阅读时间需要 6 分钟。

– Start


我们先来回答一下上个例子最后问题的答案,很遗憾 Producer 并不能证明消息发送成功了,如果设置了 retry,Producer 会再次发送消息,这会导致消息重复,如何避免?有两种办法,一种是 Idempotent,也就是说支持重复发送,broker 会自动认为是一条消息,另一种办法是使用事务。

下面的例子演示使用 Idempotent。

package shangbo.kafka.example2;import java.util.Properties;import org.apache.kafka.clients.producer.Callback;import org.apache.kafka.clients.producer.KafkaProducer;import org.apache.kafka.clients.producer.Producer;import org.apache.kafka.clients.producer.ProducerRecord;import org.apache.kafka.clients.producer.RecordMetadata;public class App {	public static void main(String[] args) {		// Producer 配置信息,应该配置在属性文件中		Properties props = new Properties();		//指定要连接的 broker,不需要列出所有的 broker,但建议至少列出2个,以防某个 broker 挂了		props.put("bootstrap.servers", "localhost:9092");		props.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer");		props.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer");		props.put("enable.idempotence", "true");//		props.put("retries", 3); // 不能手动设置 retries,自动设置为 Integer.MAX_VALUE//		props.put("acks", "1"); // 不能手动设置 acks,自动设置为 all		// 创建 Producer		Producer
producer = new KafkaProducer
(props); // 发送消息 producer.send(new ProducerRecord
("topic0", "message 4"), new Callback() { public void onCompletion(RecordMetadata metadata, Exception exception) { if(exception != null) { System.out.println("send message4 failed with " + exception.getMessage()); } else { // offset 是消息在 partition 中的编号,可以根据 offset 检索消息 System.out.println("message4 sent to " + metadata.topic() + ", partition " + metadata.partition() + ", offset " + metadata.offset()); } } }); // producer 需要关闭,放在 finally 里 producer.close(); }}

– 更多参见:

– 声 明:转载请注明出处
– Last Edited on 2018-06-13
– Written by ShangBo on 2018-06-13
– End

你可能感兴趣的文章
[LeetCode By Python]136. Single Number
查看>>
Android/Linux 内存监视
查看>>
Android2.1消息应用(Messaging)源码学习笔记
查看>>
MPMoviePlayerViewController和MPMoviePlayerController的使用
查看>>
CocoaPods实践之制作篇
查看>>
[Mac]Mac 操作系统 常见技巧
查看>>
苹果Swift编程语言入门教程【中文版】
查看>>
捕鱼忍者(ninja fishing)之游戏指南+游戏攻略+游戏体验
查看>>
iphone开发基础之objective-c学习
查看>>
iphone开发之SDK研究(待续)
查看>>
计算机网络复习要点
查看>>
Variable property attributes or Modifiers in iOS
查看>>
NSNotificationCenter 用法总结
查看>>
C primer plus 基础总结(一)
查看>>
剑指offer算法题分析与整理(三)
查看>>
Ubuntu 13.10使用fcitx输入法
查看>>
pidgin-lwqq 安装
查看>>
mint/ubuntu安装搜狗输入法
查看>>
C++动态申请数组和参数传递问题
查看>>
opencv学习——在MFC中读取和显示图像
查看>>