Kafka的API-Java篇

上一篇文章已经将Kafka的服务配置分享了一遍,这篇主要是将java的API分享一波。
Kafka有四个核心API:

  • Producer API :允许应用程序发送数据流到kafka集群中的topic。
  • Consumer API :允许应用程序从kafka集群的topic中读取数据流。
  • Streams API :允许从输入topic转换数据流到输出topic。
  • Connect API:通过实现连接器(connector),不断地从一些源系统或应用程序中拉取数据到kafka,或从kafka提交数据到宿系统(sink system)或应用程序。

但这些Springboot都已经为我们集成的差不多了,我们只需要发挥拿来主义就可以:

生产者发送消息:
ListenableFuture<SendResult<K, V>> sendDefault(V data);

ListenableFuture<SendResult<K, V>> sendDefault(K key, V data);

ListenableFuture<SendResult<K, V>> sendDefault(Integer partition, K key, V data);

ListenableFuture<SendResult<K, V>> sendDefault(Integer partition, Long timestamp, K key, V data);

ListenableFuture<SendResult<K, V>> send(String topic, V data);

ListenableFuture<SendResult<K, V>> send(String topic, K key, V data);

ListenableFuture<SendResult<K, V>> send(String topic, Integer partition, K key, V data);

ListenableFuture<SendResult<K, V>> send(String topic, Integer partition, Long timestamp, K key, V data);

ListenableFuture<SendResult<K, V>> send(ProducerRecord<K, V> record);

ListenableFuture<SendResult<K, V>> send(Message<?> message);

topic:这里填写的是Topic的名字
partition:这里填写的是分区的id,其实也是就第几个分区,id从0开始。表示指定发送到该分区中
timestamp:时间戳,一般默认当前时间戳
key:消息的键
data:消息的数据
ProducerRecord:消息对应的封装类,包含上述字段
Message<?>:Spring自带的Message封装类,包含消息及消息头

监听更是可以直接将注解@KafkaListener注在方法上就可以:
@KafkaListener的注解都提供了什么属性:

  • id:消费者的id,当GroupId没有被配置的时候,默认id为GroupId
  • containerFactory:上面提到了@KafkaListener区分单数据还是多数据消费只需要配置一下注解的containerFactory属性就可以了,这里面配置的是监听容器工厂,也就是ConcurrentKafkaListenerContainerFactory,配置BeanName
  • topics:需要监听的Topic,可监听多个
  • topicPartitions:可配置更加详细的监听信息,必须监听某个Topic中的指定分区,或者从offset为200的偏移量开始监听
  • errorHandler:监听异常处理器,配置BeanName
  • groupId:消费组ID
  • idIsGroup:id是否为GroupId
  • clientIdPrefix:消费者Id前缀
  • beanRef:真实监听容器的BeanName,需要在 BeanName前加 “__”
    下一篇我将自己使用Springboot集成Kafka的代码分享一下,希望大家可以指点一波。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章