【源码剖析】3-生产者KafkaProducer使用示例

首先在properties对象中写入生产者对象KafkaProducer需要的配置项,然后通过KafkaProducer的send对象进行发送。

java 复制代码
import org.apache.kafka.clients.producer.Callback;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.clients.producer.RecordMetadata;

import java.util.Properties;
import java.util.concurrent.ExecutionException;

public class ProducerDemo {
    public static void main(String[] args) {

        // 消息的发送方式:异步发送还是同步发送
        boolean isAsync = args.length ==0 || !args[0].trim().equalsIgnoreCase("sync");

        Properties props = new Properties();
        // Kafka服务器的主机号和端口号
        props.put("bootstrap.servers", "localhost:9092");
        props.put("client.id", "DemoProducer");
        props.put("key.serializer", "org.apache.kafka.common.serialization.IntegerSerializer");
        props.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer");
        
        // 创建生产者对象
        KafkaProducer kafkaProducer = new KafkaProducer(props);
        
        // 主题
        String topic = "test";
        int messageNo = 1;
        while (true){
            String messageStr = "Message_"+messageNo;
            long startTime = System.currentTimeMillis();
            if (isAsync){
                // 第一个参数封装了消息对象
                // 第二个参数封装了回调对象
                kafkaProducer.send(new ProducerRecord<>(topic, messageNo, messageStr), new DemoCallback(startTime, messageNo, messageStr));
            }else {
                try {
                    // KafkaProducer.send返回的对象是Future<RecordMetadata>
                    // 通过调用其get方法阻塞当前县城,等待kafka的ack响应
                    kafkaProducer.send(new ProducerRecord<>(topic, messageNo, messageStr)).get();
                    System.out.println(String.format("sent message :(%s,%s)", messageNo, messageStr));
                } catch (InterruptedException | ExecutionException e) {
                    throw new RuntimeException(e);
                }
            }
            messageNo++;
        }
    }
}


class DemoCallback implements Callback{
    private final long startTime;
    private final int key;
    private final String message;

    public DemoCallback(long startTime, int key, String message){
        this.startTime = startTime;
        this.key = key;
        this.message = message;
    }

    @Override
    public void onCompletion(RecordMetadata metadata, Exception e) {
        long elapsedTime = System.currentTimeMillis() - startTime;
        if (metadata!=null){
            System.out.println(String.format("message(%s,%s) sent to partition(%s), offset(%s) in %s ms", key, message, metadata.partition(), metadata.offset(), elapsedTime));
        }else {
            e.printStackTrace();
        }
    }
}