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,后续我在完善,我也正在学习这玩意儿,哈哈,喜欢的朋友点个赞收藏吧;

相关推荐
2601_949817721 天前
Spring Boot3.3.X整合Mybatis-Plus
spring boot·后端·mybatis
uNke DEPH1 天前
Spring Boot的项目结构
java·spring boot·后端
zhenxin01221 天前
Spring Boot 3.x 系列【3】Spring Initializr快速创建Spring Boot项目
spring boot·后端·spring
zhenxin01221 天前
【wiki知识库】07.用户管理后端SpringBoot部分
spring boot·后端·状态模式
SeSs IZED1 天前
SSM与Springboot是什么关系? -----区别与联系
java·spring boot·后端
勿忘,瞬间1 天前
SpringBoot配置文件
java·spring boot·后端
2601_949814491 天前
Spring Boot中使用Server-Sent Events (SSE) 实现实时数据推送教程
java·spring boot·后端
wellc1 天前
SpringBoot集成Flowable
java·spring boot·后端
xuefeiniao1 天前
使用宝塔安装RabbitMQ,启动不起来
分布式·rabbitmq·ruby
tongxh4231 天前
Spring Boot 3.X:Unable to connect to Redis错误记录
spring boot·redis·后端