kafka 事务代码

package cn.duanjt;

import java.sql.SQLOutput;
import java.util.Properties;
import java.util.Random;

import org.apache.kafka.clients.admin.AdminClient;
import org.apache.kafka.clients.admin.NewPartitions;
import org.apache.kafka.clients.producer.*;
import org.apache.kafka.common.serialization.StringSerializer;

public class Producer {

    public static void main(String[] args) throws InterruptedException {
        Properties p = new Properties();
        p.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "192.168.199.129:9092");//kafka地址,多个地址用逗号分割
        p.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer");
        p.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer");
        p.put(ProducerConfig.TRANSACTIONAL_ID_CONFIG,"transaction_id");
        KafkaProducer kafkaProducer = new KafkaProducer<>(p);

        kafkaProducer.initTransactions();
        kafkaProducer.beginTransaction();
        try {
            for(int i = 0; i < 10000; i++){
                System.out.println(Integer.toString(i));
                kafkaProducer.send(new ProducerRecord("mykafka", Integer.toString(i), Integer.toString(i)));
            }
            kafkaProducer.commitTransaction();
        }
        catch (Exception e){
            kafkaProducer.abortTransaction();
            e.printStackTrace();
        }
        finally {
            kafkaProducer.close();
        }
    }
}

 

你可能感兴趣的:(Kafka)