介绍
通过 KafkaTemplate 发送消息
KafkaTemplate
1
public ListenableFuture<SendResult<K, V>> send(String topic, @Nullable V data)
形参:
topic:主题data:数据
不指定 partition、key ,会依次将消息发送该topic下的所有分区,即:轮询策略
2
public ListenableFuture<SendResult<K, V>> send(String topic, K key, @Nullable V data)
形参:
topic:主题data:数据key:将key的hash值进行计算,得出分区号,将消息保存到该分区,即:哈希策略
好处:key相同的消息会在一个分区下
3
public ListenableFuture<SendResult<K, V>> send(String topic, Integer partition, K key, @Nullable V data)
形参:
topic:主题data:数据partition:将消息保存到 partiton 分区上
4
public ListenableFuture<SendResult<K, V>> send(String topic, Integer partition, Long timestamp, K key, @Nullable V data)
形参:
topic:主题partition:将消息保存到 partiton 分区上timestamp:时间戳。如果为null,则生产者将使用System.currentTimeMillis()分配时间戳key:keydata:数据
5
public ListenableFuture<SendResult<K, V>> send(ProducerRecord<K, V> record)
将发送的消息封装为 ProducerRecord 对象,其数据结构如下:
public class ProducerRecord<K, V> {
private final String topic; //目标topic
private final Integer partition; //目标partition
private final Headers headers;//消息头信息
private final K key; //消息key
private final V value; //消息体
private final Long timestamp; //消息时间戳
//省略构造方法与成员方法
headers 属性是Kafka 0.11.x 版本引入的,可以用它存储一些应用或业务相关的信息