kafka 事務問題。
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.Producer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.Properties;
/**
* @author: nko-sun
* @Date: 2019/4/17 12:27
* @Description:
* Kafka生產者
* 先啓動生產者,發送消息到broker, 相關配置可以以配置文件獨流的形式獲取
*/
public class KafkaProducerConfiguration {
//事務初始化一次
public static Producer buildProducer() {
Properties props = new Properties();
//broker地址
props.put("bootstrap.servers", "192.168.1.160:9092,192.168.1.161:9092,192.168.1.162:9092"); // "localhost:9092"
//請求時候需要驗證
props.put(ProducerConfig.ACKS_CONFIG, "all");
//請求失敗時候需要重試
props.put("retries", 3);
//內存緩存區大小
props.put("buffer.memory", 33554432);
//指定消息key序列化方式
props.put("key.serializer",
"org.apache.kafka.common.serialization.StringSerializer");
//指定消息本身的序列化方式
props.put("value.serializer",
"org.apache.kafka.common.serialization.StringSerializer");
// 設置事務id
props.put(ProducerConfig.TRANSACTIONAL_ID_CONFIG, "first-transactional");
// 設置冪等性
props.put(ProducerConfig.ENABLE_IDEMPOTENCE_CONFIG,true);
props.put("client-id","officeKapi");
Producer<String, String> producer = new KafkaProducer<String, String>(props);
//需要各位注意這段代碼
producer.initTransactions();
producer.beginTransaction();
//如果寫在service中每次創建 init、begin 事務就會報 Invalid transition attempted from state READY to state INITIALIZING 這樣的錯誤。
//原因可以參考 https://www.cnblogs.com/felixzh/p/10184762.html
return producer;
}
}