Kafka 发送消息 -- 事务

– Start

点击此处观看本系列配套视频


上节课我们讲了使用 Idempotent 确保消息只发送一次,本节课我们演示如何使用事务。

package shangbo.kafka.example3;

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;
import org.apache.kafka.common.KafkaException;

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("transactional.id", "test.transactional.id"); // 需要设置 transactional.id

		// 创建 Producer
		Producer producer = new KafkaProducer(props);
		
		// 初始化事务
		producer.initTransactions();
		
		try {
			// 开启事务
			producer.beginTransaction();
			
			// 发送消息
			producer.send(new ProducerRecord("topic0", "message 5"), new Callback() {

				public void onCompletion(RecordMetadata metadata, Exception exception) {
					if(exception != null) {
						System.out.println("send message5 failed with " + exception.getMessage());
					} else {
						// offset 是消息在 partition 中的编号,可以根据 offset 检索消息
						System.out.println("message5 sent to " + metadata.topic() + ", partition " + metadata.partition() + ", offset " + metadata.offset());	
					}
					
				}
				
			});
			
			// 提交事务
			producer.commitTransaction();
			
		} catch(KafkaException e) {
			// 终止事务
			producer.abortTransaction();
		} finally {
			producer.close();
		}

	}
}

– 更多参见:Kafka 精萃
– 声 明:转载请注明出处
– Last Edited on 2018-06-13
– Written by ShangBo on 2018-06-13
– End

你可能感兴趣的:(Kafka)