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

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

文(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消息:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class MyKafka {
    @Autowired
    private KafkaTemplate kafkaTemplate;

    private int count = 2022;

    @RequestMapping(value = "/send", method = RequestMethod.GET)
    private String sendMsg() {
        String topic = "zhangphil_demo";
        String key = "my_key";
        String data = "hello,world! " + (count++);

        kafkaTemplate.send(topic, key, data);

        return data;
    }
}

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

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

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

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

相关文章

微信公众号

最新文章

更多