ARC 4接入真实业务工程第 15–18 章

第 16 章 —— 使用 Spring Boot 装配 Runtime

本章目标: 本章完成后,开发者能够用 dsm.* 属性创建 Runtime 和命名集合 bean,理解自动装配的失败门禁,并验证应用上下文和生命周期。

学习目标

  1. 说明 DsmProperties、DsmAutoConfiguration 与集合 bean 的装配顺序。
  2. 配置 clusterId、serviceId、membership 和三类集合。
  3. 通过 bean name 注入 typed collection handle 或领域适配器。
  4. 让错误配置在启动期 fail fast。

前置条件

  • 已完成第 15 章的领域端口与 composition root。
  • 熟悉 Spring Boot configuration properties 和 bean 生命周期。
  • 能区分「上下文启动成功」与「多节点网络已验证」。

案例进度

履约应用不再手写所有 builder。application.yml 描述 Runtime 与集合,auto-configuration 先创建 membership 和 Runtime,再注册命名集合 bean,最后把它们注入 DSM 领域适配器。

从配置到业务端口

Spring Boot 从属性到领域适配器的装配

核心顺序不能倒置:集合注册需要已存在的 Runtime;领域适配器需要已注册的 handles;上下文关闭时 lifecycle 需要停止 Runtime。

最小属性合同

第 16 章资产给出三类集合的完整配置。关键字段如下:

dsm:
  cluster-id: fulfillment
  service-id: fulfillment-control-plane
  cluster:
    mode: standalone
  collections:
    - bean-name: routeHintsCollection
      tenant-id: shared
      application-id: gateway
      collection-id: route-hints
      schema-id: route-hints/v1
      type: REGISTER
      consistency-tier: REGISTER
      entity-type: com.example.RouteHint

真实类名和 codec/merger/entity factory 需要存在。完整资产使用占位的 com.example.* 教学类型,因此用于配置评审,不直接冒充可启动应用;实际启动证据来自固定源码中的 DsmAutoConfigurationTest 与 SpringBootDsmApplicationTest。

Bean 名称有两种

auto-configuration 为 locator 建立规范名,例如:

dsmCollection:shared/gateway/route-hints

配置中的 bean-name 再提供业务友好别名,例如 routeHintsCollection。两者指向同一个注册结果。业务适配器应使用显式 qualifier/bean name,避免容器仅凭原始泛型推断目标 bean。

Record codec 的便利与边界

设置 entity-type 且类型是 record 时,自动装配可以派生 RecordCodec。非 record 实体没有显式 codec-bean 会启动失败。CRDT 还需要提供 state codec、initial state 与 merger;Lease 需要提供 entity factory。

这种 fail fast 很重要:配置缺项若等到第一条远端消息才暴露,故障位置已经离装配错误太远。

启动门禁

DsmAutoConfigurationTest 固定了这些失败或成功行为:

配置 结果
缺少 cluster-id 启动失败
locator 重复 启动失败
non-record 缺 codec 启动失败
CRDT 缺 merger 启动失败
Lease 参数非法 启动失败
自定义 ClusterMembership bean 不被默认实现覆盖
上下文关闭 Runtime lifecycle 停止

反例与故障注入

复制第 16 章配置资产,删除 CRDT merger bean 或让两个集合使用相同 locator。预期结果是上下文直接拒绝启动并指出配置边界,错误不应延迟到业务功能执行阶段。

实验

cd submodule/dsm
mvn -q -pl dsm-spring-boot-autoconfigure -am \
  -Dtest=DsmAutoConfigurationTest,DsmSpringBootSmokeTest \
  -Dsurefire.failIfNoSpecifiedTests=false test

再运行真实示例应用上下文:

cd submodule/dsm-examples/basic-usage-examples
./mvnw -q -Dtest=SpringBootDsmApplicationTest test

实验验收卡

字段 内容
运行命令 上述 auto-configuration 与 Basic Usage 聚焦测试
输入或故障 三类集合属性、缺失 codec/merger、重复 locator、上下文关闭
可观察结果 Runtime 启动;规范名与别名 bean 可取;错误配置 fail fast;关闭时停止
证据等级 E2:真实 Spring ApplicationContext 与单进程 Runtime
本实验未证明 多实例发现、真实网络复制、生产密钥或部署就绪

回顾

  • Spring Boot 只替代装配,不改变集合语义和失败边界。
  • Runtime 需要先于集合,集合需要先于领域适配器。
  • locator 规范名和业务别名都应明确、稳定、可测试。
  • 配置错误应在启动期失败,而不是运行中静默降级。

下一步

第 17 章拆开两层身份:clusterId/serviceId 控制通信域,locator 控制同一 Runtime 内的集合域。

证据链接