SuperAPI AI 工具集

bff-spring

智能体与模型

查看项目

更新于 10-16 09:10

技能介绍

用途

bff-spring(apigen-bff)用于在 Spring Boot 应用中实现 BFF(Backend For Frontend)模式,即为不同客户端类型提供定制化的接口响应。它解决多端场景下接口字段冗余、服务调用分散、限流策略难区分的问题。

主要能力

  1. 客户端类型检测:支持枚举 ClientType,包含 WEB、MOBILE_IOS、MOBILE_ANDROID、TABLET、TV、IOT、PARTNER。通过请求头 X-Client-Type 检测,缺失时可回退到 User-Agent 解析(fallback 默认 WEB)。ClientType 提供 isMobile() 与 requiresCompression() 判断方法。

  2. 响应裁剪(Response Tailoring):按客户端类型过滤返回字段。ResponseTailoringServiceImpl 使用 ObjectMapper 将对象转为 Map,按 fieldMappings 中允许的字段集合过滤后再转回原类型。

  3. 服务编排聚合(Query Composition):QueryCompositionServiceImpl 通过 CompletableFuture 并行调用多个下游服务,支持 includes 参数选择需要的服务,带超时(示例配置 5 秒)与失败降级(handleFailure 返回 ServiceResult.failure)。

  4. 多客户端限流:CombinedRateLimitServiceImpl 为每种客户端类型维护独立令牌桶,按配置的每分钟请求数限流,超限抛出 RateLimitExceededException。

  5. 注解驱动:@BffEndpoint 支持指定允许的 clients、include 列表与 aggregate 开关;@TailorForClient 支持指定客户端、字段列表与压缩选项。BffEndpointAspect 切面负责校验客户端限制并执行限流。

  6. 聚合响应模型:AggregatedResponse 记录包含 data、errors、metadata,提供 Builder 构建方式与 hasErrors() 判断。

使用方式

通过配置项启用与调整行为:

apigen:
  bff:
    enabled: true
    client-detection:
      header: X-Client-Type
      fallback: WEB
rate-limits:
  web:
    requests-per-minute: 1000
  mobile:
    requests-per-minute: 500
  iot:
    requests-per-minute: 100
response-tailoring:
  enabled: true
  compress-mobile: true
composition:
  timeout: 5s
  parallel-enabled: true

控制器继承 BaseBffController,使用 detectClient 检测客户端,使用 tailorResponse 裁剪响应;在方法上添加 @BffEndpoint(aggregate = true) 或 @TailorForClient 注解。示例 DashboardBffController 根据 include 参数(profile、notifications、orders)聚合数据,并对移动端调整通知数量(移动端 5 条,其他 20 条)。

适用场景

适用于需要为 Web、移动端、IoT 等多类客户端提供同一业务但不同字段结构、不同限流策略的 Spring Boot 后端项目;适合需要并行聚合多个微服务结果并控制超时的场景。

限制

资料未提供该技能的安装命令、依赖坐标、版本要求、价格或收费信息。示例代码中的具体服务(UserService、OrderService、NotificationService)为示意,未提供完整实现。相关技能为 bff-concepts(BFF 模式概念)与 spring-boot-4(Spring Boot 4.0 模式)。