Spring Cloud Stream使用

Spring Cloud Stream作为事件驱动架构,它提供了对Kafka 、Rabbit的抽象封装,适用于需要 消息流管理、微服务通信 的场景。

1. 引入相关依赖

xml 复制代码
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-stream-kafka</artifactId>
    <version>3.1.0</version>
</dependency>
 <dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-stream-rabbit</artifactId>
    <version>3.2.9</version>
  </dependency>

2. 配置 application.yml

  • kafka-steam流配置
yaml 复制代码
spring:
  cloud:
    stream:
      bindings:
        stream-output:
          destination: my-topic # 生产者发送的消息会发往这个主题
          contentType: application/json
        stream-input:
          destination: my-topic # 消费者从这个主题读取消息
          group: my-group      # 消费者组
          contentType: application/json
      kafka:
        binder:
          brokers: localhost:9092 # Kafka broker 地址
          autoCreateTopics: true  # 自动创建主题(如果 Kafka 上没有该主题时)
  • rabbit-steam流配置
yaml 复制代码
spring:
  cloud:
    stream:
      # 进行rabbit的相关绑定配置
      rabbit:
        bindings:
          stream-output:
            # 进行生产端端配置
            producer:
              #定义 RoutingKey 的表达式配置
              routing-key-expression: '''stream-key'''
          stream-input:
            # 进行消费端配置
            consumer:
              # 设置一个RoutingKey信息
              bindingRoutingKey: stream-key
      # 在此处配置要绑定的rabbitmq的服务信息;
      binders:
        # 表示定义的名称,用于于binding整合
        default-rabbit:
          # 消息组件类型
          type: rabbit
          # 设置rabbitmq的相关的环境配置
          environment:
            spring:
              rabbitmq:
                host: 127.0.0.1
                port: 5672
                username: guest
                password: guest
                virtual-host: /
      # 服务的整合处理
      bindings:
        # 设定通道的名称
        stream-output:
          # 设定Exchange名称定义
          destination: queue.stream.messages
          # 设定消息类型,对象类型,如果是文本则设置"text/plain"
          content-type: application/json
          # 设置要绑定的消息服务的定义名称
          binder: default-rabbit
          # 进行操作的分组,表示持久化
          group: stream-group
        # 设定通道的名称
        stream-input:
          # 设定Exchange名称定义
          destination: queue.stream.messages
          # 设定消息类型,对象类型,如果是文本则设置"text/plain"
          content-type: application/json
          # 设置要绑定的消息服务的定义名称
          binder: default-rabbit
          # 进行操作的分组,表示持久化
          group: stream-group

3. 定义生产者

通过定义一个输出通道(@Output)来实现生产者

java 复制代码
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.stream.function.StreamBridge;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class MessageProducer {

    @Autowired
    private StreamBridge streamBridge; // 用来发送消息
    
    //@Autowired
    //private MyProcessor myProcessor;

    @GetMapping("/send")
    public String sendMessage() {
        String message = "Hello from Spring Cloud Stream!";
        // 通过 StreamBridge 发送消息到 Kafka
        streamBridge.send("stream-output", MessageBuilder.withPayload(message).build());
		//myProcessor.output().send(MessageBuilder.withPayload(message).build());
        return "Message sent: " + message;
    }
}

4. 定义消费者

java 复制代码
import org.springframework.cloud.stream.annotation.EnableBinding;
import org.springframework.cloud.stream.annotation.StreamListener;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;

@Component
@EnableBinding(MyProcessor.class)
//@EnableBinding(Sink.class)
public class MessageConsumer {

    // 定义消费通道并监听消息
    //@StreamListener(Sink.INPUT)
    @StreamListener(target = MyProcessor.INPUT)
    public void handleMessage(Message<String> message) {
        String receivedMessage = message.getPayload();
        System.out.println("Received message: " + receivedMessage);
    }
}

5. 定义绑定接口

java 复制代码
import org.springframework.cloud.stream.annotation.Input;
import org.springframework.cloud.stream.annotation.Output;
import org.springframework.messaging.MessageChannel;

public interface MyProcessor {

    String OUTPUT = "stream-output";  // 生产者输出通道
    String INPUT = "stream-input";   // 消费者输入通道

    @Output(OUTPUT) 
    MessageChannel output();  // 生产者输出通道

    @Input(INPUT) 
    SubscribableChannel input();   // 消费者输入通道
}
相关推荐
常利兵2 小时前
Kotlin 延迟初始化:lateinit与by lazy的华山论剑
spring boot·后端·状态模式
杜子不疼.2 小时前
Spring Cloud 熔断降级详解:用 “保险丝“ 类比,Sentinel 实战教程
人工智能·spring·spring cloud·sentinel
沙雕不是雕又菜又爱玩2 小时前
基于springboot的超市收银系统
java·spring boot·intellij-idea
江湖十年2 小时前
AI Agent 生态再添一员,Kratos 带着他的武器 Blades 走来了!
人工智能·后端·go
l软件定制开发工作室2 小时前
Spring开发系列教程(32)——Spring Boot开发
java·spring boot·后端·spring
iPadiPhone2 小时前
性能优化的“快车道”:Spring @Async 注解深度原理与大厂实战
java·后端·spring·面试·性能优化
彭于晏Yan2 小时前
JsonProperty注解的access属性
java·spring boot
Mr.朱鹏2 小时前
分布式-redis集群架构
java·redis·分布式·后端·spring·缓存·架构
醇氧2 小时前
PowerPoint 批量转换为 PDF
java·spring boot·spring·pdf·powerpoint