Apache Kafka - 生产者在initTransaction上中断

时间:2017-11-23 14:01:47

标签: java apache-kafka kafka-producer-api spring-kafka

我正在测试一个基本的事务案例,但它仍然停留在producer.initTransaction(); 任何配置都可能出错吗?

public static void main(String[] argv) throws Exception {
    String topicName = "helloworldpartitioned";
    // Configure the Producer
    Properties configProperties = new Properties();
    configProperties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
    configProperties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
    configProperties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
    configProperties.put(ProducerConfig.TRANSACTION_TIMEOUT_CONFIG, "1000");
    configProperties.put(ProducerConfig.CLIENT_ID_CONFIG, "test");
//      configProperties.put(ProducerConfig.ENABLE_IDEMPOTENCE_CONFIG, Boolean.TRUE);
    configProperties.put(ProducerConfig.TRANSACTIONAL_ID_CONFIG, PRODUCER_TRANSACTIONAL_ID);

    KafkaProducer<String, String> producer = new KafkaProducer<String, String>(configProperties);
    producer.initTransactions();
    producer.beginTransaction();
        String line = "TestMessage";
        System.out.println("Inizializzo la transazione");
        ProducerRecord<String, String> rec = new ProducerRecord<String, String>(topicName, line);
        producer.send(rec);
    // Thread.sleep(5000);
    producer.commitTransaction();
    producer.flush();
    producer.close();
}

1 个答案:

答案 0 :(得分:0)

尝试:

producer.initTransactions();
producer.beginTransaction();
    String line = "TestMessage";
    System.out.println("Inizializzo la transazione");
    ProducerRecord<String, String> rec = new ProducerRecord<String, String>(topicName, line);
    producer.send(rec);


// Thread.sleep(5000);
producer.commitTransaction();
producer.flush();
producer.close();