spring boot集成kafka开发,发送消息,Java实现(2)

x33g5p2x  于2022-02-28 转载在 Spring  
字(1.1k)|赞(0)|评价(0)|浏览(563)

文(1):

https://zhangphil.blog.csdn.net/article/details/123108051

https://zhangphil.blog.csdn.net/article/details/123108051在文(1)基础上,实现一个简单功能:在spring程序里面,发送kafka消息,kafka控制台里面,接受消息。

kafka配置和文(1)相同。

写一个简单controller,实现功能,当用户浏览器打开/send页面后,就发送一条kafka消息:

  1. import org.springframework.beans.factory.annotation.Autowired;
  2. import org.springframework.kafka.core.KafkaTemplate;
  3. import org.springframework.web.bind.annotation.RequestMapping;
  4. import org.springframework.web.bind.annotation.RequestMethod;
  5. import org.springframework.web.bind.annotation.RestController;
  6. @RestController
  7. public class MyKafka {
  8. @Autowired
  9. private KafkaTemplate kafkaTemplate;
  10. private int count = 2022;
  11. @RequestMapping(value = "/send", method = RequestMethod.GET)
  12. private String sendMsg() {
  13. String topic = "zhangphil_demo";
  14. String key = "my_key";
  15. String data = "hello,world! " + (count++);
  16. kafkaTemplate.send(topic, key, data);
  17. return data;
  18. }
  19. }

启动spring,然后在kafka控制台使用命令方式启动在主题topic为zhangphil_demo上接收消息:

  1. kafka-console-consumer.bat --topic zhangphil_demo --from-beginning --bootstrap-server localhost:9092

当打开浏览器访问页面localhost:7999/send时候,即发送一条消息:

发送的消息,被kafka控制台收到。

相关文章