SpringBoot3集成Kafka

本文详细介绍了Kafka的安装、环境配置、生产者和消费者操作,包括使用KafkaConsole工具、KafkaEagle可视化工具,以及在SpringBoot项目中的应用。还涉及了Kafka的KSQL查询和工程架构设置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

标签:Kafka3.Kafka-eagle3;

一、简介

Kafka是一个开源的分布式事件流平台,常被用于高性能数据管道、流分析、数据集成和关键任务应用,基于Zookeeper协调的处理平台,也是一种消息系统,具有更好的吞吐量、内置分区、复制和容错,这使得它成为大规模消息处理应用程序的一个很好的解决方案;

二、环境搭建

1、Kafka部署

1、下载安装包:kafka_2.13-3.5.0.tgz

2、配置环境变量

open -e ~/.bash_profile

export KAFKA_HOME=/本地路径/kafka3.5
export PATH=$PATH:$KAFKA_HOME/bin

source ~/.bash_profile

3、该目录【kafka3.5/bin】启动zookeeper
zookeeper-server-start.sh ../config/zookeeper.properties

4、该目录【kafka3.5/bin】启动kafka
kafka-server-start.sh ../config/server.properties

2、Kafka测试

1、生产者
kafka-console-producer.sh --broker-list localhost:9092 --topic test-topic
>id-1-message
>id-2-message

2、消费者
kafka-console-consumer.sh --bootstrap-server localhost:9092 --topic test-topic
id-1-message
id-2-message

3、查看topic列表
kafka-topics.sh --bootstrap-server localhost:9092 --list
test-topic

4、查看消息列表
kafka-console-consumer.sh --bootstrap-server localhost:9092 --topic test-topic --from-beginning --partition 0
id-1-message
id-2-message

3、可视化工具

配置和部署

1、下载安装包:kafka-eagle-bin-3.0.2.tar.gz

2、配置环境变量

open -e ~/.bash_profile

export KE_HOME=/本地路径/efak-web-3.0.2
export PATH=$PATH:$KE_HOME/bin

source ~/.bash_profile

3、修改配置文件:system-config.properties

efak.zk.cluster.alias=cluster1
cluster1.zk.list=localhost:2181
efak.url=jdbc:mysql://127.0.0.1:3306/kafka-eagle

4、本地新建数据库:kafka-eagle,注意用户名和密码是否一致

5、启动命令
efak-web-3.0.2/bin/ke.sh start
命令语法: ./ke.sh {start|stop|restart|status|stats|find|gc|jdk|version|sdate|cluster}

6、本地访问【localhost:8048】 username:admin password:123456

KSQL语句测试

select * from `test-topic` where `partition` in (0)  order by `date` desc limit 5

select * from `test-topic` where `partition` in (0) and msg like '%5%' order by `date` desc limit 3

三、工程搭建

1、工程结构

2、依赖管理

这里关于依赖的管理就比较复杂了,首先spring-kafka组件选择与boot框架中spring相同的依赖,即6.0.10版本,在spring-kafka最近的版本中3.0.8符合;

但是该版本使用的是kafka-clients组件的3.3.2版本,在Spring文档的kafka模块中,明确说明spring-boot:3.1要使用kafka-clients:3.4,所以从spring-kafka组件中排除掉,重新依赖kafka-clients组件;

<dependency>
    <groupId>org.springframework.kafka</groupId>
    <artifactId>spring-kafka</artifactId>
    <version>${spring-kafka.version}</version>
    <exclusions>
        <exclusion>
            <groupId>org.apache.kafka</groupId>
            <artifactId>kafka-clients</artifactId>
        </exclusion>
    </exclusions>
</dependency>
<dependency>
    <groupId>org.apache.kafka</groupId>
    <artifactId>kafka-clients</artifactId>
    <version>${kafka-clients.version}</version>
</dependency>

3、配置文件

配置kafka连接地址,监听器的消息应答机制,消费者的基础模式;

spring:
  # kafka配置
  kafka:
    bootstrap-servers: localhost:9092
    listener:
      missing-topics-fatal: false
      ack-mode: manual_immediate
    consumer:
      group-id: boot-kafka-group
      enable-auto-commit: false
      max-poll-records: 10
      properties:
        max.poll.interval.ms: 3600000

四、基础用法

1、消息生产

模板类KafkaTemplate用于执行高级的操作,封装各种消息发送的方法,在该方法中,通过topickey以及消息主体,实现消息的生产;

@RestController
public class ProducerWeb {

    @Resource
    private KafkaTemplate<String, String> kafkaTemplate;

    @GetMapping("/send/msg")
    public String sendMsg (){
        try {
            // 构建消息主体
            JsonMapper jsonMapper = new JsonMapper();
            String msgBody = jsonMapper.writeValueAsString(new MqMsg(7,"boot-kafka-msg"));
            // 发送消息
            kafkaTemplate.send("boot-kafka-topic","boot-kafka-key",msgBody);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return "OK" ;
    }
}

2、消息消费

编写消息监听类,通过KafkaListener注解控制监听的具体信息,在实现消息生产和消费的方法测试后,使用可视化工具kafka-eagle查看topic和消息列表;

@Component
public class ConsumerListener {

    private static final Logger log = LoggerFactory.getLogger(ConsumerListener.class);

    @KafkaListener(topics = "boot-kafka-topic")
    public void listenUser (ConsumerRecord<?,String> record, Acknowledgment acknowledgment) {
        try {
            String key =  String.valueOf(record.key());
            String body = record.value();
            log.info("\n=====\ntopic:boot-kafka-topic,key{},body:{}\n=====\n",key,body);
        } catch (Exception e){
            e.printStackTrace();
        } finally {
            acknowledgment.acknowledge();
        }
    }
}

五、参考源码

文档仓库:
https://gitee.com/cicadasmile/butte-java-note

源码仓库:
https://gitee.com/cicadasmile/butte-spring-parent
<think>好的,我现在需要帮助用户在Spring Boot项目中集成并使用Apache Kafka。首先,我得回忆一下之前学过的相关知识,确保步骤正确。用户已经提供了一些引用内容,我需要参考这些内容来组织回答。 首先,用户提到的引用[3]里提到需要在pom.xml中添加Kafka的依赖。我应该确认最新的Spring Boot版本对应的Kafka依赖版本是否正确。比如,当前Spring Boot 3.x可能使用更高版本spring-kafka,比如3.0.0以上。不过用户示例中是2.8.0,可能需要指出根据项目版本选择合适版本。 接下来是配置Kafka的连接信息,引用[3]也提到了配置application.yml或application.properties文件。需要说明如何配置bootstrap-servers、生产者配置如key和value的序列化方式,消费者配置如group-id和反序列化方式。 然后是创建生产者和消费者,引用[2]中提到了使用KafkaTemplate发送消息,以及通过@KafkaListener注解来监听主题。需要详细说明如何定义生产者服务类,注入KafkaTemplate,并编写发送消息的方法。对于消费者,需要说明如何创建监听器方法,处理接收到的消息。 另外,可能需要提到配置类,但根据Spring Boot的自动配置,可能不需要额外的配置类,除非有自定义需求。比如分区策略、确认机制等,这些可以作为优化或高级配置提及。 用户的问题还可能涉及测试,比如如何发送和接收消息的示例,确保配置正确。可以建议用户编写测试用例或使用main方法进行测试。 还需要检查是否有遗漏的步骤,比如依赖添加后是否需要重新构建项目,配置项是否有误,以及常见的错误,比如bootstrap-servers地址错误,防火墙设置,Kafka服务器是否运行等。 最后,根据用户提供的示例,可能需要补充相关的问题,比如如何确保消息顺序、处理异常、监控Kafka性能等,作为相关问题部分。 现在需要将这些步骤结构化,分点说明,确保用户能够一步步跟随操作,并且代码示例正确无误。同时,引用正确的参考文献,比如引用[3]对应依赖配置,引用[2]对应生产者和消费者的使用。</think>在Spring Boot项目中集成并使用Apache Kafka的步骤如下: ### 一、添加依赖 在`pom.xml`中添加Spring Kafka依赖: ```xml <dependency> <groupId>org.springframework.kafka</groupId> <artifactId>spring-kafka</artifactId> <version>3.0.0</version> <!-- 根据Spring Boot版本选择 --> </dependency> ``` ### 二、配置Kafka连接 在`application.yml`中配置Kafka服务器地址和生产者/消费者参数: ```yaml spring: kafka: bootstrap-servers: localhost:9092 producer: key-serializer: org.apache.kafka.common.serialization.StringSerializer value-serializer: org.apache.kafka.common.serialization.StringSerializer consumer: group-id: my-group key-deserializer: org.apache.kafka.common.serialization.StringDeserializer value-deserializer: org.apache.kafka.common.serialization.StringDeserializer ``` ### 三、创建消息生产者 通过`KafkaTemplate`发送消息: ```java @Service public class KafkaProducerService { @Autowired private KafkaTemplate<String, String> kafkaTemplate; public void sendMessage(String topic, String message) { kafkaTemplate.send(topic, message); } } ``` ### 四、创建消息消费者 使用`@KafkaListener`注解监听消息: ```java @Service public class KafkaConsumerService { @KafkaListener(topics = "my-topic", groupId = "my-group") public void receiveMessage(String message) { System.out.println("Received: " + message); } } ``` ### 五、测试流程 在Controller中调用生产者发送消息: ```java @RestController public class KafkaController { @Autowired private KafkaProducerService producer; @GetMapping("/send") public String send(@RequestParam String msg) { producer.sendMessage("my-topic", msg); return "Message sent: " + msg; } } ``` 启动应用后访问`http://localhost:8080/send?msg=test`,消费者控制台将输出`Received: test`[^2][^3]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值