springboot整合Kafka,使用zookeeper做服务治理

一、springboot自动配置方式整合kafka:

springboot提供自动配置整合kafka的方式,需要做一下步骤:

(1)引入kafka依赖包:

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

(2)在springboot配置中加入kafka相关配置,springboot启动时候会自动加载这些配置,完成链接kafka,创建producer,consumer等。

spring:
  kafka:
    # kafka服务地址
    bootstrap-servers: 127.0.0.1:9092
    # 消费者配置
    consumer:
      bootstrap-servers: 127.0.0.1:9092
      group-id: myGroup
      enable-auto-commit: true
      auto-offset-reset: earliest
      auto-commit-interval: 1000
      max-poll-records: 10
    # 生产者配置
    producer:
      retries: 5
      batch-size: 16384
      buffer-memory: 33554432
      acks: 1

(3)消息发送端:

@Component
public class MqProviderImpl{
   

    @Autowired
    private KafkaTemplate<String, String> kafkaTemplate;
    
    @Override
    public void sendSkMessage(String message, Properties properties) {
   
        // 发送消息,注册一个回调事件
        ListenableFuture<SendResult<String, String>> futureMessage = KafkaConfig.kafkaTemplateStatic.send("test_topic",
                message);

        futureMessage.addCallback(new ListenableFutureCallback<SendResult<String, String>>(){
   

            @Override
            public void onSuccess(SendResult<String, String> sendResult) {
   
                log.info(" rev "+sendResult.getProducerRecord().value());
            }

            @Override
            public void onFailure(Throwable ex) {
   
                log.error(" error "+ex.getMessage());
            }
        });
    }}

(4)消息消费端:

@KafkaListener(topics = {
   "test_topic"})
    public void receiveSkMessageInfo(ConsumerRecord<String, String> record, @Header(KafkaHeaders.RECEIVED_TOPIC) String topic, Acknowledgment ack) {
   
        log.info

你可能感兴趣的:(Java后端,框架知识,Spring,Boot,java,spring,boot,后端)