简体   繁体   English

如何在 Spring Boot 中使用来自 Apache Kafka 的数据

[英]How to consume data from Apache Kafka in Spring Boot

I have got the json using kafka-avro console-consumer .我已经使用kafka-avro console-consumer获得了 json。 Now I want to get the json in a spring-boot console.现在我想在spring-boot控制台中获取 json。 What to do next?接下来做什么?

You simply need to create a consumer:你只需要创建一个消费者:

@Service
public class Consumer {

    private final Logger logger = LoggerFactory.getLogger(Consumer.class);

    @KafkaListener(topics = "myTopic", groupId = "myTopic-consumer-group")
    public void consume(String message) throws IOException {
        logger.info(String.format("Message: %s", message));
    }
}

@KafkaListener annotation can be used to read messages from kafka topic. @KafkaListener注释可用于从 kafka 主题读取消息。

Here is a working example of a class that reads Kafka messages:这是读取 Kafka 消息的类的工作示例:

import org.springframework.kafka.annotation.KafkaListener;

public class KafkaReader {

  private String latestMessage = "";

  @KafkaListener(topics = "${kafka.topic}")
  public void receive(String payload) {
      latestMessage = payload;
  }

  public String getLatestMessage() {
      System.out.println("Message read from topic: \n" + latestMessage);

      // Code to format the message

      return latestMessage.trim();
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用 Apache Kafka 在 Spring Boot 中使用和保存自定义类型列表? - How to consume and save a List of custom types in Spring Boot using Apache Kafka? 在 Spring 引导中通过 Kafka 消费批次 - Consume Batches through Kafka in Spring boot 默认情况下如何使用Kafka Spring Cloud Stream并使用汇合API生成的Kafka消息? - How to consume from Kafka Spring Cloud Stream by default and also consume a Kafka message generated by the confluent API? 如何使用 spring webflux 从 Kafka 主题中持续消费? - How to continually consume from Kafka topic using spring webflux? Apache Kafka不会从api中使用 - Apache Kafka does not consume from api 如何在Spring Boot中使用带有休息模板的多部分表单数据 - How to consume multipart form data with a rest template in spring boot 如何使用 Java 和 Spring Boot 使用 XML 数据 - How to consume XML data using Java and Spring Boot 如何在Apache Kafka中使用以前的消息 - how to consume previous messages in apache kafka 如何在 Spring Boot 中使用来自 UI 服务的登录服务? - How to consume Login Service from UI Service in Spring Boot? 如何在特定偏移量到特定偏移量中使用来自 kafka 主题的数据? - How to consume data from kafka topic in specific offset to specific offset?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM