Spring Cloud Alibaba整合 Kafka 的完整实现

以下是基于 Spring Cloud Alibaba 2025(假设为最新版本)整合 Kafka 的完整实现文档和代码示例,包含消息发送与监听的核心配置和代码。


环境准备

  • JDK 17+
  • Spring Boot 3.x
  • Spring Cloud Alibaba 2025.x
  • Kafka 3.x(单机或集群)
  • Maven/Gradle

添加依赖

在 pom.xml 中添加 Kafka 和 Spring Cloud Stream 依赖:

xml 复制代码
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-stream</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-stream-binder-kafka</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.kafka</groupId>
    <artifactId>spring-kafka</artifactId>
</dependency>

配置文件

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: demo-group
      key-deserializer: org.apache.kafka.common.serialization.StringDeserializer
      value-deserializer: org.apache.kafka.common.serialization.StringDeserializer
      auto-offset-reset: earliest

  cloud:
    stream:
      bindings:
        output:
          destination: demo-topic
          content-type: application/json
        input:
          destination: demo-topic
          content-type: application/json

消息发送接口

定义消息发送的绑定接口:

java 复制代码
public interface KafkaSource {
    String OUTPUT = "output";

    @Output(OUTPUT)
    MessageChannel output();
}

消息监听接口

定义消息监听的绑定接口:

java 复制代码
public interface KafkaSink {
    String INPUT = "input";

    @Input(INPUT)
    SubscribableChannel input();
}

消息生产者实现

通过 KafkaSource 发送消息:

java 复制代码
@Service
@EnableBinding(KafkaSource.class)
public class MessageProducer {
    private final KafkaSource source;

    public MessageProducer(KafkaSource source) {
        this.source = source;
    }

    public void send(String message) {
        source.output().send(MessageBuilder.withPayload(message).build());
    }
}

消息消费者实现

通过 KafkaSink 监听消息:

java 复制代码
@Service
@EnableBinding(KafkaSink.class)
public class MessageConsumer {
    @StreamListener(KafkaSink.INPUT)
    public void handle(String message) {
        System.out.println("Received message: " + message);
    }
}

启动类配置

确保启动类开启绑定功能:

java 复制代码
@SpringBootApplication
@EnableBinding({KafkaSource.class, KafkaSink.class})
public class KafkaApplication {
    public static void main(String[] args) {
        SpringApplication.run(KafkaApplication.class, args);
    }
}

测试用例

编写测试验证消息发送和接收:

java 复制代码
@SpringBootTest
class KafkaIntegrationTest {
    @Autowired
    private MessageProducer producer;

    @Test
    void testSendAndReceive() {
        producer.send("Test message");
        // 监听控制台输出或通过断言验证
    }
}

注意事项

  1. 主题创建 :确保 Kafka 中已存在 demo-topic,或配置自动创建:

    yaml 复制代码
    spring:
      kafka:
        admin:
          properties:
            auto.create.topics.enable: true
  2. 序列化:若传输复杂对象,需自定义序列化器。

  3. 错误处理 :通过 @ServiceActivator 处理消费异常:

    java 复制代码
    @ServiceActivator(inputChannel = "demo-topic.errors")
    public void handleError(ErrorMessage error) {
        System.err.println("Error occurred: " + error.getPayload());
    }

以上代码实现了 Spring Cloud Alibaba 2025 与 Kafka 的基本集成,涵盖消息发送、监听及配置。根据实际需求调整主题、序列化方式和错误处理逻辑。

相关推荐
Regulus-Moon17 小时前
Quorum:用一个不等式换掉分布式锁
数据结构·论文阅读·分布式·算法·系统架构
这个昵称不容易18 小时前
租房管理系统设计与实现:16 张表、185 个接口的 SpringBoot 前后台项目
java·springboot·毕设
挖掘狂人1 天前
消息队列怎么保证消费不重复?
后端·消息队列
codigger1 天前
消息队列怎么保证消费不重复?
程序员·消息队列·编程
Resean02231 天前
SpringCloud 源码分析(二)Nacos 注册中心(上):服务注册流程与注册表模型
java·后端·spring·spring cloud
xieliyu.1 天前
Nacos 是个啥?怎么在自己电脑上跑起来?(一)
后端·spring cloud·微服务·nacos·配置中心·服务注册中心·nacos 入门
鱼宵2 天前
64 消息队列选型
消息队列·架构师·软考
这个昵称不容易2 天前
SpringBoot 基于web的酒店客房管理系统设计与实现:176 个 Java 文件 233 个接口,会员预约到退房一条链
java·springboot·毕设
这个昵称不容易2 天前
在线宠物用品交易网站设计与实现:SpringBoot 商城 158 个接口,附论文与运行截图
java·springboot·毕设
Lansonli2 天前
大数据Spark(九十五):Spark Shuffle 参数调优全解析
大数据·分布式·spark