Skip to content

Function 详解:函数式编程模型

  Spring Cloud Function 是 Spring Cloud 提供的一个函数式编程模型,让你用 java.util.function 中的标准接口(SupplierFunctionConsumer)来编写业务逻辑,框架自动处理 HTTP 暴露、消息驱动等适配工作。

一、核心理念:写一次,到处运行

┌──────────────────────────────────────────────────────────────────┐
│                Spring Cloud Function 核心价值                     │
│                                                                  │
│  你只需要写一个函数:                                              │
│                                                                  │
│  @Bean                                                           │
│  public Function<String, String> uppercase() {                    │
│      return String::toUpperCase;                                  │
│  }                                                               │
│                                                                  │
│  框架自动适配:                                                    │
│  ┌──────────────┐  ┌──────────────┐  ┌──────────────┐            │
│  │  HTTP REST   │  │   Stream     │  │   AWS Lambda │            │
│  │  /uppercase  │  │  (消息队列)   │  │  (Serverless)│            │
│  └──────────────┘  └──────────────┘  └──────────────┘            │
│                                                                  │
│  同一段代码,无需修改,即可在不同"运行环境"中执行                    │
└──────────────────────────────────────────────────────────────────┘

二、三大核心类型

类型Java 接口语义使用场景
SupplierSupplier<T>生产者,0 入 1 出定时任务、数据源、事件生成
FunctionFunction<T, R>处理器,1 入 1 出数据转换、业务处理
ConsumerConsumer<T>消费者,1 入 0 出数据持久化、日志记录、通知
Supplier<T>        Function<T, R>        Consumer<T>
     │                   │                    │
     │  () → T           │  T → R             │  T → ()
     │                   │                    │
     ▼                   ▼                    ▼
┌─────────┐       ┌─────────────┐       ┌─────────┐
│ 无输入   │       │ 输入 → 输出  │       │ 无输出   │
│ 有输出   │       │   (转换)    │       │ 有输入   │
└─────────┘       └─────────────┘       └─────────┘

三、快速上手

3.1 依赖

xml
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-function-web</artifactId>
</dependency>

3.2 定义函数

java
@SpringBootApplication
public class FunctionApplication {

    public static void main(String[] args) {
        SpringApplication.run(FunctionApplication.class, args);
    }

    @Bean
    public Function<String, String> uppercase() {
        return String::toUpperCase;
    }

    @Bean
    public Function<String, String> reverse() {
        return s -> new StringBuilder(s).reverse().toString();
    }

    @Bean
    public Consumer<String> log() {
        return s -> System.out.println("收到消息:" + s);
    }

    @Bean
    public Supplier<String> ping() {
        return () -> "pong";
    }
}

3.3 自动暴露为 HTTP 端点

函数定义                              HTTP 端点
─────────────────────────────────────────────────
uppercase  → Function<String,String> → POST /uppercase  Body: "hello"   → "HELLO"
reverse    → Function<String,String> → POST /reverse    Body: "hello"   → "olleh"
log        → Consumer<String>        → POST /log        Body: "hello"   → (无返回)
ping       → Supplier<String>        → GET  /ping                        → "pong"

3.4 组合函数

yaml
spring:
  cloud:
    function:
      definition: uppercase|reverse   # 管道:先 uppercase,再 reverse
POST /uppercase|reverse  Body: "hello"
  → uppercase("hello")   → "HELLO"
  → reverse("HELLO")     → "OLLEH"
  → 返回 "OLLEH"

四、与 Stream 集成

Function 是 Spring Cloud Stream 的函数式编程模型基础

java
// 旧:注解式(Stream 2.x)
@EnableBinding(Sink.class)
public class MessageHandler {
    @StreamListener(Sink.INPUT)
    public void handle(String message) {
        System.out.println(message);
    }
}

// 新:函数式(Stream 3.x+,推荐)
@Bean
public Consumer<String> handle() {
    return message -> System.out.println(message);
}
yaml
spring:
  cloud:
    function:
      definition: handle
    stream:
      bindings:
        handle-in-0:                    # 输入绑定:{函数名}-in-{index}
          destination: my-topic
          group: my-group

绑定命名规则:

Supplier<T>   → 输出绑定:{函数名}-out-{index}
Function<T,R> → 输入绑定:{函数名}-in-{index}
                输出绑定:{函数名}-out-{index}
Consumer<T>   → 输入绑定:{函数名}-in-{index}

五、多函数组合方案

java
// 场景:订单处理流水线
// 订单消息 → 校验 → 转换 → 入库 → 通知

@Bean
public Function<OrderDTO, Order> validate() {
    return dto -> {
        if (dto.getAmount() <= 0) throw new BusinessException("金额无效");
        return new Order(dto);
    };
}

@Bean
public Function<Order, Order> enrich() {
    return order -> {
        order.setCreateTime(LocalDateTime.now());
        return order;
    };
}

@Bean
public Consumer<Order> save() {
    return order -> orderRepository.save(order);
}
yaml
spring:
  cloud:
    function:
      definition: validate|enrich|save      # 管道组合

六、面试要点

Q1:Spring Cloud Function 的设计目标?

  写一次,到处运行。用标准的 java.util.function 接口编写业务逻辑,框架自动适配不同的运行环境(HTTP、消息队列、Serverless)。核心价值在于解耦业务逻辑和运行环境。

Q2:Supplier、Function、Consumer 的区别?

  Supplier(0 入 1 出)是生产者,不需要输入直接产生数据;Function(1 入 1 出)是处理器,接收输入返回输出;Consumer(1 入 0 出)是消费者,接收输入无返回值。

Q3:与 Stream 的注解式编程有什么区别?

  Stream 3.x 全面转向函数式。旧版用 @StreamListener 注解,与 Spring Cloud Stream 框架强耦合。新版用 Function bean,与框架解耦,可独立测试,代码更简洁。

Q4:函数管道组合是什么意思?

  通过 | 连接多个函数,形成处理管道:uppercase|reverse|log。每个函数的输出作为下一个函数的输入,实现无侵入的函数组合。