SpringCloud Stream 4.x 使用教程

SpringCloud Stream 4.x 教程:简化版HelloWorld与实战案例
本文是SpringCloud Stream 4.x的使用教程,介绍了版本变化、POM配置、如何编写HelloWorld程序以及4.x版本的新特性。通过一个具体的案例展示了如何在JDK17、SpringBoot 3.0.5和RabbitMQ环境下,使用Controller发送消息到不同Exchange,并用Consumer进行消费。同时,提到了配置文件的关键设置和函数式编程的应用。


版本说明

一、SpringCloud Stream 2.x

Bili搜一下周阳那个Cloud视频

二、SpringCloud Stream 3.x

看这个兄弟的Blog:

https://blog.youkuaiyun.com/QAQpig/article/details/129120856


三、如果是SrpingCloud Stream 4.x,往下看

一、POM

      <!-- Rabbit MQ -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-stream-binder-rabbit</artifactId>
        </dependency>

        <!-- web、actuator -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>

        <!-- test -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
        </dependency>

起作用的,实际上就这几个,对于Rabbit,老版本需要引入depend相关,新版本就一个binder搞定,因为binder已经对于stream与rabbit依赖关系做了很好的POM封装,源码如下:

<modelVersion>4.0.0</modelVersion>
	<artifactId>spring-cloud-stream-binder-rabbit-parent</artifactId>
	<version>4.0.2</version> <!-- Do not remove. Ignore yellow warning -->
	<packaging>pom
**宣布发布:Spring Cloud Function 3.0.0.M2** 2023年9月,Spring 团队发布了 **Spring Cloud Function 3.0.0.M2(Milestone 2)** —— 这是 `Spring Cloud Function` 框架迈向 3.0 稳定版的关键里程碑。该版本聚焦于 **函数式编程模型的现代化、响应式流支持增强以及云原生环境下的弹性扩展能力**。 > 📢 官方公告地址:[https://spring.io/blog/2023/09/15/spring-cloud-function-3-0-0-m2-released](https://spring.io/blog/2023/09/15/spring-cloud-function-3-0-0-m2-released) > ✅ 基于 Spring Boot 2.4.0-M2 和 Spring Framework 5.3 M3 > 🔗 版本仓库:[https://repo.spring.io/milestone](https://repo.spring.io/milestone) --- ### 🌟 什么是 Spring Cloud Function? `Spring Cloud Function` 是一个抽象层,允许开发者以 **函数为单元** 编写业务逻辑,并将其无缝部署到多种运行环境中: - 本地 JVM 应用 - Spring Boot 微服务 - Serverless 平台(如 AWS Lambda、Azure Functions、Google Cloud Functions) - 消息驱动系统(通过 Spring Cloud Stream) 核心理念:**“Write once, run anywhere”** —— 使用标准 Java 函数接口(`Function<T,R>`、`Consumer<T>`、`Supplier<R>`),屏蔽底层执行环境差异。 --- ## 🚀 Spring Cloud Function 3.0.0.M2 主要更新亮点 ### 1. **全面采用函数式编程模型(Functional Programming Model)** 从 3.0 开始,基于 `java.util.function` 的函数成为首选方式,取代旧的 `@EnableAutoConfiguration` + `@Bean` 显式配置模式。 ✅ 推荐写法: ```java @SpringBootApplication public class WordCountApplication { public static void main(String[] args) { SpringApplication.run(WordCountApplication.class, args); } @Bean public Function<String, String> uppercase() { return value -> value.toUpperCase(); } @Bean public Function<Flux<String>, Flux<String>> reverse() { return flux -> flux.map(s -> new StringBuilder(s).reverse().toString()); } } ``` 自动绑定: - `uppercase-in-0` → 输入通道 - `uppercase-out-0` → 输出通道 配置示例(application.yml): ```yaml spring: cloud: function: definition: uppercase # 或多个函数:uppercase;reverse ``` --- ### 2. **深度集成响应式流(Reactive Streams with Project Reactor)** 现在可以直接使用 `Flux<T>` 和 `Mono<T>` 作为输入输出类型,实现非阻塞异步处理。 ```java @Bean public Function<Flux<User>, Flux<UserProfile>> enrichUser() { return userFlux -> userFlux .delayElements(Duration.ofMillis(100)) // 模拟异步调用 .map(this::fetchProfile); } ``` > ⚠️ 支持背压(Backpressure)、流控、错误恢复等高级特性。 --- ### 3. **改进的函数路由机制(Routing Based on Headers or Payload)** 支持根据消息头或内容动态选择执行哪个函数。 #### a. 使用 `spring.cloud.function.routing-expression` 路由 ```yaml spring: cloud: function: routing-expression: headers['functionName'] ``` 发送请求时指定目标函数: ```http POST / HTTP/1.1 Content-Type: application/json functionName: uppercase "hello world" ``` 将自动调用 `uppercase` 函数。 #### b. 基于 JSON 字段路由 ```yaml spring: cloud: function: routing-expression: payload.operation ``` 适用于 `{ "operation": "add", "x": 1, "y": 2 }` 类型的消息。 --- ### 4. **Serverless 部署体验优化** #### a. 更快冷启动时间(Cold Start Optimization) - 移除不必要的反射初始化 - 支持 GraalVM Native Image 实验性构建 ```bash native-image -jar target/function-app.jar ``` > ⚠️ 当前仍处于实验阶段,部分依赖需额外配置。 #### b. AWS Lambda 兼容性提升 无需修改代码即可打包为 `.zip` 文件上传至 AWS Lambda: ```xml <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <configuration> <classifier>exec</classifier> </configuration> </plugin> ``` 配合 [AWS SAM](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/) 快速部署。 --- ### 5. **与 Spring Cloud Stream 深度整合** Spring Cloud Function 可直接作为 `Spring Cloud Stream` 的处理器使用。 ```java @Bean public Function<String, String> processOrder() { return order -> "Processed: " + order; } ``` 绑定配置: ```yaml spring: cloud: stream: bindings: processOrder-in-0: destination: orders-input processOrder-out-0: destination: orders-output ``` 一条消息进入 `orders-input` 主题 → 自动被 `processOrder` 函数处理 → 结果发送到 `orders-output`。 --- ### 6. **增强的测试支持** 提供 `FunctionCatalog` 和 `TestChannelBinder` 简化单元测试和集成测试。 ```java @Autowired private FunctionCatalog catalog; @Test void shouldUppercaseString() { Function<String, String> fn = catalog.lookup(Function.class, "uppercase"); assertThat(fn.apply("hello")).isEqualTo("HELLO"); } ``` --- ## 🧪 如何引入 Spring Cloud Function 3.0.0.M2? ### Maven ```xml <dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-function-dependencies</artifactId> <version>3.0.0.M2</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-function-web</artifactId> </dependency> <!-- 或用于消息驱动 --> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-function-stream</artifactId> </dependency> </dependencies> ``` ### Gradle ```groovy implementation platform('org.springframework.cloud:spring-cloud-function-dependencies:3.0.0.M2') dependencies { implementation 'org.springframework.cloud:spring-cloud-function-web' implementation 'org.springframework.cloud:spring-cloud-function-stream' } ``` > 添加里程碑仓库: ```groovy repositories { maven { url 'https://repo.spring.io/milestone' } } ``` --- ## ⚠️ 注意事项 | 特性 | 状态 | 建议 | |------|------|------| | `@EnableBinding` 模式 | ❌ 已弃用 | 新项目请使用函数式模型 | | 多函数定义(`;` 分隔) | ✅ 支持 | `function.definition=upper;lower` | | GraalVM Native Image | ⚠️ 实验阶段 | 需手动排除不兼容类 | | 函数热替换(Hot Reload) | ✅ 支持 DevTools | 开发阶段提升效率 | --- ## 📚 学习资源推荐 - 📘 官方文档:[https://docs.spring.io/spring-cloud-function/docs/3.0.0.M2/reference/html/](https://docs.spring.io/spring-cloud-function/docs/3.0.0.M2/reference/html/) - 🧪 示例工程:[https://github.com/spring-cloud/spring-cloud-function-samples](https://github.com/spring-cloud/spring-cloud-function-samples) - 🎥 视频教程:“Building Serverless Apps with Spring Cloud Function 3.0” – Spring One 2023 ---
评论 2
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值