gpt4 book ai didi

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

转载 作者:知者 更新时间:2024-03-13 06:18:30 27 4
gpt4 key购买 nike

文(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控制台收到。

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com