[英]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.