Schema 演化
Apache Fory™ 在 Compatible 模式下支持 schema 演化,允许序列化和反序列化对等方具有不同的类型定义。
Compatible 模式
使用 compatible(true) 启用 schema 演化:
use fory::Fory;
use fory::ForyObject;
use std::collections::HashMap;
#[derive(ForyObject, Debug)]
struct PersonV1 {
name: String,
age: i32,
address: String,
}
#[derive(ForyObject, Debug)]
struct PersonV2 {
name: String,
age: i32,
// address 已移除
// phone 已添加
phone: Option<String>,
metadata: HashMap<String, String>,
}
let mut fory1 = Fory::default().compatible(true);
fory1.register::<PersonV1>(1);
let mut fory2 = Fory::default().compatible(true);
fory2.register::<PersonV2>(1);
let person_v1 = PersonV1 {
name: "Alice".to_string(),
age: 30,
address: "123 Main St".to_string(),
};
// 使用 V1 序列化
let bytes = fory1.serialize(&person_v1);
// 使用 V2 反序列化 - 缺失的字段获得默认值
let person_v2: PersonV2 = fory2.deserialize(&bytes)?;
assert_eq!(person_v2.name, "Alice");
assert_eq!(person_v2.age, 30);
assert_eq!(person_v2.phone, None);
Schema 演化功能
- 添加具有默认值的新字段
- 移除过时字段(在反序列化期间跳过)
- 更改字段可空性(
T↔Option<T>) - 重新排序字段(按名称匹配,而非位置)
- 对缺失字段的类型安全回退到默认值
兼容性规则
- 字段名称必须匹配(区分大小写)
- 不支持类型更改(可空/非可空除外)
- 嵌套结构体类型必须在两端都注册