使用 AsyncAPI 3.0 描述事件契约的完整示例。
解读
在国内 DDD 落地实践中,事件驱动架构(EDA) 已成为解耦限界上下文的主流手段。面试官抛出“用 AsyncAPI 3.0 描述事件契约”,并不是想听你背语法,而是考察三件事:
- 能否把领域事件准确抽象成消息契约(含业务语义、版本、实例级标识);
- 是否熟悉国内主流 MQ(RocketMQ、Kafka) 与 AsyncAPI 的映射习惯;
- 能否在契约里体现 DDD 的防腐层、限界上下文、聚合根等约束,让契约既服务业务,又方便持续集成。
因此,答案必须给出可落地的 YAML,并穿插解释设计权衡,才能拿到高分。
知识点
- AsyncAPI 3.0 核心对象:asyncapi、info、servers、channels、operations、messages、components、tags、correlationId、messageId、schemaFormat(推荐 application/vnd.aai.asyncapi+json;version=3.0.0)。
- 领域事件命名规范:<聚合根英文复数>.<业务动词>PastTense,例如 OrderPlaced、InventoryDeducted,与统一语言保持一致。
- 消息头设计:必须携带租户ID(tenantId)、聚合根ID(aggregateId)、事件版本(eventVersion)、发送时区(cnTimezoneOffset),方便国内多租户、灰度、对账。
- payload 约束:使用OpenAPI 3.0 Schema子集,禁止出现数据库主键、技术中间件字段;金额用Integer(单位为分),避免浮点精度纠纷。
- channels 命名:与 RocketMQ Topic 命名规范对齐,格式为 {businessDomain}.{subDomain}.{eventName}.{version},全部小写,中划线分隔,例如 retail.order.order-placed.v1。
- 消息幂等键:在 headers 里声明idempotentKey(业务单号+事件类型),方便消费方做幂等表防重。
- correlationId:链路追踪使用阿里云 EagleEye TraceId或美团 CAT RootId格式,方便对接国内 APM。
- 安全:国内等保 2.0 要求,servers 节点必须声明SASL_PLAINTEXT或SASL_SSL,并给出 scram-sha-512 示例。
- 版本演进:使用channels 级别版本,同一聚合根事件向后兼容只增加可选字段,不删不改;不兼容升级必须升版本号并新建通道,避免夜间重平衡影响交易高峰。
答案
以下示例描述“订单限界上下文”发布的OrderPlaced领域事件,消费方是“库存上下文”与“履约上下文”。YAML 可直接放入 Git 仓库的contracts/retail.order.order-placed.v1.asyncapi.yml,通过Maven asyncapi-plugin生成 RocketMQ 代码脚手架。
asyncapi: 3.0.0
id: 'urn:retail:order:order-placed:v1'
info:
title: 订单已放置事件
version: 1.0.0
description: 订单聚合根下单成功后发布,用于驱动库存扣减与履约排班
contact:
name: 零售域架构组
url: https://confluence.xxx.com/display/RET/OrderBC
defaultContentType: application/json
servers:
prod:
host: 'rocketmq-cluster.xxx.com:9876'
protocol: kafka-sasl-plaintext # 国内很多公司用 Kafka 协议接入 RocketMQ 5.x
security:
- type: scramSha512
description: 统一账号中心申请
channels:
retail.order.order-placed.v1:
address: 'retail-order-order-placed-v1'
messages:
OrderPlaced:
$ref: '#/components/messages/OrderPlaced'
operations:
publishOrderPlaced:
action: send
channel:
$ref: '#/channels/retail.order.order-placed.v1'
messages:
- $ref: '#/components/messages/OrderPlaced'
components:
messages:
OrderPlaced:
name: OrderPlaced
title: 订单已放置
summary: 用户提交订单且聚合根持久化成功后发布
contentType: application/json
headers:
type: object
required:
- eventId
- eventType
- tenantId
- aggregateId
- eventVersion
- idempotentKey
- correlationId
- cnTimezoneOffset
properties:
eventId:
type: string
format: uuid
description: 事件实例级唯一标识,用于对账
eventType:
type: string
const: retail.order.order-placed
tenantId:
type: string
pattern: '^T[0-9]{4}$'
description: 国内多租户编码,T0001 为自营
aggregateId:
type: string
pattern: '^O[0-9]{15}$'
description: 订单聚合根ID,O+15位雪花
eventVersion:
type: string
const: '1.0'
idempotentKey:
type: string
description: '单号+事件类型,消费方幂等表主键'
correlationId:
type: string
format: uuid
description: 链路追踪,对接 EagleEye
cnTimezoneOffset:
type: integer
description: 东八区偏移,+8
payload:
type: object
required:
- orderId
- userId
- totalAmount
- itemLines
- placedAt
properties:
orderId:
type: string
pattern: '^O[0-9]{15}$'
userId:
type: string
pattern: '^U[0-9]{10}$'
totalAmount:
type: integer
minimum: 1
description: 订单应付金额,单位分
itemLines:
type: array
minItems: 1
items:
type: object
required:
- skuId
- quantity
- unitPrice
properties:
skuId:
type: string
pattern: '^S[0-9]{8}$'
quantity:
type: integer
minimum: 1
unitPrice:
type: integer
minimum: 1
description: 单价,单位分
placedAt:
type: string
format: date-time
description: 聚合根业务时间,非数据库时间
tags:
- name: 订单域
description: 零售核心域
- name: 领域事件
description: DDD 事件驱动
使用方式:
- 把文件 push 到 Git,Merge Request 必须过契约测试(Spring Cloud Contract + Testcontainers Kafka)。
- 通过国网或阿里云平台的云原生网关自动注册 Topic,无需人工在 MQ 控制台建。
- 消费方引入
asyncapi-codegen,生成OrderPlacedListener接口,实现库存聚合根的事件处理器,并在@EventHandler方法里用idempotentKey做幂等。
拓展思考
- 双轨制版本:如果业务需要“可回滚”,可在 channels 里同时暴露
retail.order.order-placed.v1和retail.order.order-placed.v1.1,利用RocketMQ 消费组隔离,实现蓝绿发布。 - 事件溯源:把 payload 里再包一层
eventData与metadata,metadata 携带聚合根版本号(aggregateVersion),方便后续切换为EventStore做溯源。 - 合规脱敏:国内《个人信息保护法》要求,若事件离开生产库,需对
userId做可逆加密,可在 headers 加cipherKeyId指向 KMS。 - 性能调优:当订单大促峰值 10w TPS 时,把
totalAmount字段拆成压缩结构(64 位 long 存储分+币种),并在 AsyncAPI 的schemaFormat里声明application/vnd.apache.avro+json,降低 40% 流量。 - 组织级治理:在企业级事件总线门户中,通过 AsyncAPI 的
tags自动生成领域地图,一眼看出“订单域”依赖哪些下游,防止循环依赖导致核心域腐化。