I have got the json using kafka-avro console-consumer
. Now I want to get the json in a spring-boot
console. 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.
Here is a working example of a class that reads Kafka messages:
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();
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.