在Spring Boot微服务集成spring-kafka操作Kafka集群

记录:461

场景:在Spring Boot微服务集成spring-kafka-2.8.2操作Kafka集群。使用KafkaTemplate操作Kafka集群的生产者Producer。使用@KafkaListener操作Kafka集群的消费者Consumer。

版本:JDK 1.8,Spring Boot 2.6.3,kafka_2.12-2.8.0,spring-kafka-2.8.2。

Kafka集群安装:https://blog.csdn.net/zhangbeizhen18/article/details/131156084

1.基础概念

Event:An event records the fact that "something happened" in the world or in your business. It is also called record or message in the documentation.

Broker:一个Kafka节点就是一个broker;多个Broker可以组成一个Kafka集群。

Topic:Kafka根据Topic对消息进行归类,发布到Kafka的每条消息都需要指定一个Topic。

Producer:消息生产者,向Broker发送消息的客户端。

Consumer:消息消费者,从Broker读取消息的客户端。

ConsumerGroup:每个Consumer属于一个特定的ConsumerGroup,一条消息可以被多个不同的ConsumerGroup消费;但是一个ConsumerGroup中只能有一个Consumer能够消费该消息。

Partition:一个topic可以分为多个partition,每个partition内部消息是有序的。

publish:发布,使用Producer向Kafka写入数据。

subscribe:订阅,使用Consumer从Kafka读取数据。

2.微服务中配置Kafka信息信息

(1)在pom.xml添加依赖

pom.xml文件:

<dependency>
  <groupId>org.springframework.kafka</groupId>
  <artifactId>spring-kafka</artifactId>
  <version>2.8.2</version>
</dependency>

解析:spring-kafka选择一般是使用spring-boot集成的对应版本。

请知悉:spring-kafka框架底层使用了原生的kafka-clients。本例对应版本:3.0.0。

(2)在application.yml中配置Kafka信息

配置细节在官网的configuration:https://kafka.apache.org/documentation/

(1)application.yml配置内容

spring:
  kafka:
    #kafka集群的IP和端口,格式:(ip:port)
    bootstrap-servers:
      - 192.168.19.161:29092
      - 192.168.19.162:29092
      - 192.168.19.163:29092
    #生产者
    producer:
      #客户端发送服务端失败的重试次数
      retries: 2
      #多个记录被发送到同一个分区时,生产者将尝试将记录一起批处理成更少的请求.
      #此设置有助于提高客户端和服务器的性能,配置控制默认批量大小(以字节为单位)
      batch-size: 16384
      #生产者可用于缓冲等待发送到服务器的记录的总内存字节数(以字节为单位)
      buffer-memory: 33554432
      #指定key使用的序列化类
      key-serializer: org.apache.kafka.common.serialization.StringSerializer
      #指定value使用的序列化类
      value-serializer: org.apache.kafka.common.serialization.StringSerializer
      #生产者producer要求leader节点在考虑完成请求之前收到的确认数,用于控制发送记录在服务端的持久化
      #acks=0,设置为0,则生产者producer将不会等待来自服务器的任何确认.该记录将立即添加到套接字(socket)缓冲区并视为已发送.在这种情况下,无法保证服务器已收到记录,并且重试配置(retries)将不会生效(因为客户端通常不会知道任何故障),每条记录返回的偏移量始终设置为-1.
      #acks=1,设置为1,leader节点会把记录写入本地日志,不需要等待所有follower节点完全确认就会立即应答producer.在这种情况下,在follower节点复制前,leader节点确认记录后立即失败的话,记录将会丢失.
      #acks=all,acks=-1,leader节点将等待所有同步复制副本完成再确认记录,这保证了只要至少有一个同步复制副本存活,记录就不会丢失.
      acks: -1
    consumer:
      #开启consumer的偏移量(offset)自动提交到Kafka
      enable-auto-commit: true
      #consumer的偏移量(offset)自动提交的时间间隔,单位毫秒
      auto-commit-interval: 1000
      #在Kafka中没有初始化偏移量或者当前偏移量不存在情况
      #earliest,在偏移量无效的情况下,自动重置为最早的偏移量
      #latest,在偏移量无效的情况下,自动重置为最新的偏移量
      #none,在偏移量无效的情况下,抛出异常.
      auto-offset-reset: latest
      #一次调用poll返回的最大记录条数
      max-poll-records: 500
      #请求阻塞的最大时间(毫秒)
      fetch-max-wait: 500
      #请求应答的最小字节数
      fetch-min-size: 1
      #心跳间隔时间(毫秒)
      heartbeat-interval: 3000
      #指定key使用的反序列化类
      key-deserializer: org.apache.kafka.common.serialization.StringDeserializer
      #指定value使用的反序列化类
      value-deserializer: org.apache.kafka.common.serialization.StringDeserializer

(2)解析

配置类在spring boot自动注解包:spring-boot-autoconfigure-2.6.3.jar。

类:org.springframework.boot.autoconfigure.kafka.KafkaProperties。

使用@ConfigurationProperties注解使其生效,前缀是:spring.kafka。

spring-kafka框架对操作Kafka单机版和Kafka集群版的配置差异:

在于bootstrap-servers属性,单机版配置一个IP:端口对。集群版配置多个IP:端口对就行。

(3)加载逻辑

Spring Boot微服务在启动时,Spring Boot会读取application.yml的配置信息,根据配置内容在spring-boot-autoconfigure-2.6.3.jar找到KafkaProperties并注入到对应属性。Spring Boot微服务在启动完成后,KafkaProperties的配置信息在Spring环境中就能无缝使用。

Spring的spring-kafka框架将KafkaProperties配置信息注入到KafkaTemplate操作生产者Producer。

Spring的spring-kafka框架使用KafkaProperties和@KafkaListener操作Kafka的消费者Consumer。

3.使用KafkaTemplate操作Kafka集群的生产者Producer

在集成spring-kafka后,操作Kafka集群的生产者Producer极度简化了,只需注入KafkaTemplate就能操作。其它繁琐对象生成均交给spring-kafka框架处理完成。

KafkaTemplate全称:org.springframework.kafka.core.KafkaTemplate。

(1)示例代码

@RestController
@RequestMapping("/hub/example/cluster/producer")
@Slf4j
public class OperateKafkaClusterProducerController {
  //注入KafkaTemplate
  @Autowired
  private KafkaTemplate<String, String> kafkaTemplate;
  //定义Kafka的Topic
  private final String topicName = "hub-topic-city-info-01";
  @GetMapping("/f01_1")
  public Object f01_1() {
      try {
          //1.获取业务数据对象
          Long cityId = 2023061801L;
          String cityName = "苏州";
          String msgKey = cityId + ":" + cityName + ":" + System.currentTimeMillis();
          CityDTO cityDTO = CityDTO.buildDto(cityId, cityName, "苏州是一个工业");
          String msgData = JSONObject.toJSONString(cityDTO);
          log.info("KafkaProducer向Kafka集群的Topic: {},写入Key:",topicName);
          log.info(msgKey);
          log.info("KafkaProducer向Kafka集群的Topic: {},写入Data:",topicName);
          log.info(msgData);
          //2.使用KafkaTemplate向Kafka集群写入数据(topic,key,data)
          kafkaTemplate.send(topicName, msgKey, msgData);
      } catch (Exception e) {
          log.info("Producer写入Topic异常.");
          e.printStackTrace();
      }
      return "写入成功";
  }
}

(2)解析代码

使用KafkaTemplate的send方法,指定Kafka的Topic名称、key值、需要写入的数data据,就能完成Producer向Kafka集群的Broker节点写入数据。

4.使用@KafkaListener操作Kafka的消费者Consumer

在集成spring-kafka后,操作Kafka集群的消费者Consumer相当容易,只需在指定方法上使用@KafkaListener注解,就能监听消费Kafka的Topic的消息。其它繁琐操作均交给spring-kafka框架处理完成。

注解KafkaListener全称:org.springframework.kafka.annotation.KafkaListener。

(1)示例代码

@Component
@Slf4j
public class OperateKafkaClusterConsumer {
  // Topic名称
  private final String topicName = "hub-topic-city-info-01";
  // 使用@KafkaListener监听Kafka集群的Topic
  @KafkaListener(
          topics = {topicName},
          groupId = "hub-topic-city-info-01-group")
  public void consumeMsg(ConsumerRecord<?, ?> record) {
      try {
          //KafkaConsumer从集群中监听的消息存储在ConsumerRecord
          String msgKey= (String) record.key();
          String msgData = (String) record.value();
          log.info("KafkaConsumer从Kafka集群中的Topic:{},消费的原始数据的Key:",topicName);
          log.info(msgKey);
          log.info("KafkaConsumer从Kafka集群中的Topic:{},消费的原始数据的Data:",topicName);
          log.info(msgData);
      } catch (Exception e) {
          log.info("Consumer消费Topic异常.");
          e.printStackTrace();
      }
  }
}

(2)解析代码

使用@KafkaListener注解,指定Kafka的Topic名称和消费者group Id,在注解作用的监听方法上使用ConsumerRecord作为函数入参,spring-kafka框架会自动把监听到的数据写入的ConsumerRecord中。在监听方法中,从ConsumerRecord的取出数据,完成从Kafka节点消费的数据。

5.测试

(1)使用Postman测试,调用生产者写入数据

请求RUL:http://127.0.0.1:18208/hub-208-kafka/hub/example/cluster/producer/f01_1

(2)消费者自动消费数据

(3)日志信息

KafkaProducer向Kafka集群的Topic: hub-topic-city-info-01,写入Key:
2023061801:苏州:1687073734285
KafkaProducer向Kafka集群的Topic: hub-topic-city-info-01,写入Data:
{"cityDescribe":"苏州是一个工业","cityId":2023061801,"cityName":"苏州","updateTime":"2023-06-18 15:35:34"}
KafkaConsumer从Kafka集群中的Topic:hub-topic-city-info-01,消费的原始数据的Key:
2023061801:苏州:1687073734285
KafkaConsumer从Kafka集群中的Topic:hub-topic-city-info-01,消费的原始数据的Data:
{"cityDescribe":"苏州是一个工业","cityId":2023061801,"cityName":"苏州","updateTime":"2023-06-18 15:35:34"}

6.辅助类

@Data
@Builder
public class CityDTO {
  private Long cityId;
  private String cityName;
  private String cityDescribe;
  private String updateTime;
  public static CityDTO buildDto(Long cityId, String cityName,
                                 String cityDescribe) {
      return builder().cityId(cityId)
              .cityName(cityName).cityDescribe(cityDescribe)
              .updateTime(DateUtil.formatDateTime(new Date())).build();
  }
}

以上,感谢。

2023年6月18日

猜你喜欢

转载自blog.csdn.net/zhangbeizhen18/article/details/131272835