Spring Cloud——Function

本文介绍了SpringCloudFunction的背景、版本发展及其实现原理,探讨了如何利用它在Serverless场景下简化开发,特别适合已有SpringBoot经验的开发者。

Function

        依赖说明:通过函数促进业务逻辑的实现,并支持跨无服务器提供商的统一编程模型,以及独立运行(本地或在PaaS中)的能力。

          SpringCloud Function作为SpringCloud家族成员最早在2017年提出,项目主要负责人为Mark Fisher,目前已经来到了3.0版本。SpringCloud Function的出现旨在为快速发展的Serverless市场提供一个Spring的接入路径,使用SpringCloud Function进行无服务(我这里直接称为函数式编程)的项目开发可以大大节约成本,同时对于SpringBoot熟悉的人可以迅速上手。


参考:

SpringCloud Function实践入门

Spring系列学习之Spring Cloud Function微服务功能目标实现


POM

<!--Function-->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-function-context</artifactId>
</dependency>

XXX

**宣布发布: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 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

十年梦归尘

愿意支持一下不(*^▽^*)

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值