kafka producer 发送消息

package com.zhp.springbootstreamdemo.kafka;

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;

public class ProducerDemo {
    public static void main(String[] args) {
        //消息发送模式:同步或异步
        boolean isAsync = args.length == 0
                || !args[0].trim().equalsIgnoreCase("sync");

        Properties properties = new Properties();
        //Kafka服务端的主机名和端口号
        properties.put("bootstrap.servers", "localhost:9092");
        //客户的ID
        properties.put("client.id", "ProducerDemo");
        //消息的keyvalue都是字节数组,为了将Java对象转化为字节数组,可以配置
        //key.serializervalue.serializer两个序列化器,完成转化
        properties.put("key.serializer", "org.apache.kafka.common.serialization.IntegerSerializer");
        // StringSerializer用来将String对象序列化成字节数组
        properties.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer");

        //生产者核心类
        KafkaProducer<Integer, String> producer = new KafkaProducer<>(properties);
        String topic = "test";
        //消息的Key
        int messageKey = 1;
        while (true) {
            // 消息的value
            String messageValue = "Message_" + messageKey;
            long startTime = System.currentTimeMillis();
            if (isAsync) {
                //异步发送消息
                // 第一个参数是ProducerRecord类型的对象,封装了目标Topic、消息的key、消息的value
                // 第二个参数是一个CallBack对象,当生产者接收到Kafka发来的ACK                // 认消息的时候,会调用此CallBack对象的onCompletion()方法,实现 回调功能
                ProducerRecord<Integer, String> record = new ProducerRecord<>(topic, messageKey, messageValue);
                producer.send(record, new DemoCallBack<>(startTime, messageKey, messageValue));
            } else {
                //同步发送消息
                //KafkaProducer.send()方法的返回值类型是Future<RecordMetadata>
                //这里通过Future.get()方法,阻塞当前线程,等待Kafka服务端的ACK响应
                ProducerRecord<Integer, String> producerRecord = new ProducerRecord<>(topic, messageKey, messageValue);
                try {
                    RecordMetadata recordMetadata = producer.send(producerRecord).get();
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
            messageKey++;
        }
    }
}

class DemoCallBack<K, V> implements Callback {
    private final long startTime;
    private final K key;
    private final V value;

    public DemoCallBack(long startTime, K key, V value) {
        this.startTime = startTime;
        this.key = key;
        this.value = value;
    }

    /**
     * 生产者成功发送消息,收到Kafka服务端发来的ACK确认消息后,会调用此回调函数
     *
     * @param recordMetadata 生产者发送的消息的元数据,如果发送过程中出现异常,此参数为null
     * @param exception      发送过程中出现的异常,如果发送成功,则此参数为null
     */
    @Override
    public void onCompletion(RecordMetadata recordMetadata, Exception exception) {
        if (recordMetadata != null) {
            long elapsedTime = System.currentTimeMillis() - startTime;
            System.out.println("message(" + key + "," + value + ") send to partition("
                    + recordMetadata.partition() + ")," + "offset(" + recordMetadata.offset() + ") in" + elapsedTime);
        } else {
            exception.printStackTrace();
        }
    }

}

发送的消息如何选择分区:

在KafkaProducer的doSend方法中有如下代码:

int partition = partition(record, serializedKey, serializedValue, cluster);
private int partition(ProducerRecord<K, V> record, byte[] serializedKey, byte[] serializedValue, Cluster cluster) {
    Integer partition = record.partition();
    return partition != null ?
            partition :
            partitioner.partition(
                    record.topic(), record.key(), serializedKey, record.value(), serializedValue, cluster);
}
如果我们创建ProducerRecord时设置了partition,就用我们设置的。否则进行计算。

默认的实现是DefaultPartitioner

public static final String PARTITIONER_CLASS_CONFIG = "partitioner.class";

.define(PARTITIONER_CLASS_CONFIG,
        Type.CLASS,
        DefaultPartitioner.class,
        Importance.MEDIUM, PARTITIONER_CLASS_DOC)
如果我们没有配置就使用默认的。
我们看默认实现方法
public int partition(String topic, Object key, byte[] keyBytes, Object value, byte[] valueBytes, Cluster cluster) {
    List<PartitionInfo> partitions = cluster.partitionsForTopic(topic);
    int numPartitions = partitions.size();
    if (keyBytes == null) {
        int nextValue = nextValue(topic);
        List<PartitionInfo> availablePartitions = cluster.availablePartitionsForTopic(topic);
        if (availablePartitions.size() > 0) {
            int part = Utils.toPositive(nextValue) % availablePartitions.size();
            return availablePartitions.get(part).partition();
        } else {
            // no partitions are available, give a non-available partition
            return Utils.toPositive(nextValue) % numPartitions;
        }
    } else {
        // hash the keyBytes to choose a partition
        return Utils.toPositive(Utils.murmur2(keyBytes)) % numPartitions;
    }
}

private int nextValue(String topic) {
    AtomicInteger counter = topicCounterMap.get(topic);
    if (null == counter) {
        counter = new AtomicInteger(ThreadLocalRandom.current().nextInt());
        AtomicInteger currentCounter = topicCounterMap.putIfAbsent(topic, counter);
        if (currentCounter != null) {
            counter = currentCounter;
        }
    }
    return counter.getAndIncrement();
}
如果keyBytes为null 就使用轮询选择分区。否则根据key的hash值。




  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Kafka Producer发送消息需要传入以下配置: 1. bootstrap.servers:Kafka集群中broker节点的地址清单,格式为host:port,多个地址用逗号分隔。 2. acks:表示Producer等待broker响应确认消息的级别。有三个值可选,分别是: - 0:Producer在成功写入消息之前不会等待来自broker的任何确认。此时,Producer发送消息的可靠性较低,因为broker无法检测到消息是否已经成功写入。但是,这种方式的发送速度是最快的。 - 1:Producer在成功写入消息后会等待broker的确认。在此级别下,如果broker在接收到消息后宕机或者发送失败,则会丢失消息。 - all:Producer在成功写入消息后会等待所有的broker都确认。这种级别的消息发送最可靠,但是速度最慢。 3. key.serializer:Producer发送消息中key的序列化方式,通常为字符串。 4. value.serializer:Producer发送消息中value的序列化方式,通常为对象序列化后的字节数组。 示例代码如下: ```java import org.apache.kafka.clients.producer.*; import java.util.Properties; public class KafkaProducerDemo { public static void main(String[] args) { Properties props = new Properties(); props.put("bootstrap.servers", "localhost:9092"); // kafka集群地址 props.put("acks", "all"); props.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer"); props.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer"); Producer<String, String> producer = new KafkaProducer<>(props); for (int i = 0; i < 10; i++) { producer.send(new ProducerRecord<>("test_topic", Integer.toString(i), Integer.toString(i))); } producer.close(); } } ``` 在上面的代码中,我们传入了一个Kafka集群地址,即localhost:9092。如果你有多个Kafka集群,可以在这里传入多个地址,用逗号分隔即可。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值