Kafka入门到精通(四)-SpringBoot+Kafka

一丶IDEA创建一个空项目

二丶添加相关依赖

复制代码
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.kafka</groupId>
            <artifactId>spring-kafka</artifactId>
            <version>2.9.13</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.28</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>com.alibaba.fastjson2</groupId>
            <artifactId>fastjson2</artifactId>
            <version>2.0.12</version>
        </dependency>
    </dependencies>

三丶编写简单生产者

复制代码
    /**
     * 简单的生产者消费者
     * @param message
     */
    @GetMapping("/kafka/normal/message")
    public void sendNormalMessage(@RequestParam("message") String message) {
        log.info("======================="+message);
        kafkaTemplate.send("sb_topic", 0, System.currentTimeMillis(), "key1", message);
    }

四丶编写简单消费者

复制代码
@Component
public class KafkaConsumer {
 
    //监听消费
    //@KafkaListener(topics = {"sb_topic"})
    @KafkaListener(topics = {"sb_topic","callbackOne_topic"}, groupId = "testGroup")
    public void onNormalMessage(ConsumerRecords<String,Object> records) {
        for (ConsumerRecord<String, Object> record : records) {
            System.out.printf("offset = %d, key = %s, value = %s\n", record.offset(), record.key(), record.value());
        }
    }
 
}

这里有个坑,ConsumerRecord如果不加s会报错,我之间在借鉴他人代码的时候出现的,不知道是不是版本问题。我也刚用kafka,正在研究哈哈,见谅见谅;

postman请求:

成功:

结尾:目前只是一个简单的demo,后续我在完善,我也正在学习这玩意儿,哈哈,喜欢的朋友点个赞收藏吧;

相关推荐
用户3521802454752 天前
当 Prompt 学会"热更新":Spring Boot × Nacos3 AI 实战
java·spring boot·ai编程
昵称为空C2 天前
手撸一个动态 SQL 执行引擎:不重启服务,在线增删改查任意数据库
spring boot·后端
霸道流氓气质3 天前
领域驱动设计(DDD)在 Spring Boot 微服务中的实践指南
运维·spring boot·微服务
于先生吖3 天前
SpringBoot对接大模型开发AI命理测算系统:八字排盘与AI解析接口源码全解
人工智能·spring boot·后端
Flittly3 天前
【AgentScope Java新手村系列】(10)实战-多Agent天气助手
java·spring boot·spring
星落zx4 天前
Spring Boot 多模型集成:优雅调用全球主流大模型
人工智能·spring boot·chatgpt
一杯奶茶¥4 天前
水果销售网站 CRM客户信息管理系统 超市管理系 酒店管理系统 健身房管理系统 在线音乐网站 校园招聘系统
java·vue.js·spring boot·mysql·spring·java项目
进阶的小名4 天前
Spring Boot SSE + Nginx 配置:解决 EventSource 不实时返回、连接超时、流式响应被缓冲问题
spring boot·后端·nginx
我登哥MVP4 天前
SpringCloud Alibaba 核心组件解析:服务链路追踪
java·spring boot·后端·spring·spring cloud·java-ee·maven