Exception in thread “main“ java.lang.IllegalStateException: Transactional method invoked on a non-tr

bug解决方式

在学习使用Kafka的事务时,出现如下错误:

这是因为没有指定事务id

使用如下代码指定事务id

      //指定事务id,随便起,但要保证全局唯一,使用Kafka事务时必须指定,否则报错
      //Transactional method invoked on a non-transactional producer.
      properties.put(ProducerConfig.TRANSACTIONAL_ID_CONFIG,"transaction_id_001");

完整demo

package com.atguigu.kafka.producer;

import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.serialization.StringSerializer;

import java.util.Properties;

public class ProducerTransaction {
   public static void main(String[] args) {
      // 0 创建 kafka 生产者的配置对象
      Properties properties = new Properties();
      //服务器集群
      properties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG,"atguigu100:9092,atguigu101:9092,atguigu102:9092");
      //key和value序列化器,必须指定
      properties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
      properties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG,StringSerializer.class.getName());
      //batch.size:批次大小,默认16K
      properties.put(ProducerConfig.BATCH_SIZE_CONFIG,16384);
      //linger.ma:停留时间,默认0
      properties.put(ProducerConfig.LINGER_MS_CONFIG,1);
      //RecordAccumulator:缓冲区大小,默认32M,即33554432,buffer.memory
      properties.put(ProducerConfig.BUFFER_MEMORY_CONFIG,33554432);
       compression.type:压缩类型,默认 none,可配置值 gzip、snappy、lz4 和 zstd,常用snappy
      properties.put(ProducerConfig.COMPRESSION_TYPE_CONFIG,"snappy");

      //指定事务id,随便起,但要保证全局唯一,使用Kafka事务时必须指定,否则报错
      //Transactional method invoked on a non-transactional producer.
      properties.put(ProducerConfig.TRANSACTIONAL_ID_CONFIG,"transaction_id_001");

      // 1 创建kafka生产者对象
      KafkaProducer kafkaProducer = new KafkaProducer<>(properties);
      //初始化事务
      kafkaProducer.initTransactions();
      //开启事务
      kafkaProducer.beginTransaction();
      //发送数据时,可能出现错误,出现错误时,就终止事务.所以放到try,快捷键:先鼠标选中代码块,然后Ctrl+Alt+T
      try {
         // 2 发送数据
         String topic = "mytopic";
         for (int i = 0; i < 5; i++) {
            kafkaProducer.send(new ProducerRecord<>(topic,"key1","hello"+i));
         }
         //提交事务
         kafkaProducer.commitTransaction();
      } catch (Exception e) {
         //出现异常时,终止事务
         kafkaProducer.abortTransaction();
         throw new RuntimeException(e);
      } finally {
         // 3 关闭资源
         kafkaProducer.close();
      }

   }
}

你可能感兴趣的:(Kafka,java,开发语言)