Appearance
分布式数据管理
KV-Store 和 分布式数据库的分布式数据同步机制。
1. 分布式 KV-Store
1.1 核心特性
| 特性 | 说明 |
|---|---|
| 自动同步 | 多设备间自动同步数据 |
| 冲突解决 | 最后写入优先(LWW) |
| 断网处理 | 断网缓存,联网后同步 |
| 安全认证 | 设备间自动认证 |
1.2 多设备同步
typescript
import { kVStore } from '@kit.ArkData';
// 创建分布式 KV-Store
let store: kVStore.KVStore = await kVStore.createKVStore({
name: 'distributedKV',
type: 'persistent',
encrypt: false,
autoSync: true, // 启用自动同步
syncPolicy: kVStore.SyncPolicy.GLOBAL // 全局同步策略
});
// 写入数据(自动同步到所有设备)
await store.put('userId', '12345');
await store.put('theme', 'dark');
await store.put('fontSize', 18);
// 监听数据变化(包括其他设备的变更)
store.on('dataChange', (key: string, value: any) => {
console.log(`数据变化: ${key} = ${value}`);
// 自动更新 UI
if (key === 'theme') {
this.theme = value as string;
} else if (key === 'fontSize') {
this.fontSize = value as number;
}
});2. 分布式数据库
2.1 概念
分布式数据库 = 多设备共享关系型数据库
设备 A 设备 B
┌─ RDB ──┐ ┌─ RDB ──┐
│ 用户表 │◄── 同步 ────►│ 用户表 │
│ 订单表 │◄── 同步 ────►│ 订单表 │
│ 消息表 │◴── 同步 ────►│ 消息表 │
└───────┘ └───────┘2.2 使用场景
✅ 适合:
├─ 多设备数据共享(消息/文档/通讯录)
├─ 数据一致性要求高的场景
└─ 跨设备协作
❌ 不适合:
├─ 单设备数据 → 用普通 RDB
└─ 非结构化数据 → 用文件存储3. 数据同步策略
3.1 同步策略
| 策略 | 说明 |
|---|---|
| 全局同步 | 所有设备共享同一份数据 |
| 按需同步 | 设备按需拉取数据 |
| 冲突解决 | 最后写入优先 (LWW) |
3.2 冲突处理
typescript
// KV-Store 冲突:最后写入优先 (Last Write Wins)
// 两个设备同时修改同一 Key
// → 最后写入的值胜出
// 解决方案:使用时间戳或版本号
interface SyncedValue {
value: string
timestamp: number
deviceId: string
}
// 写入时附加时间戳
await store.put('config', {
value: 'dark',
timestamp: Date.now(),
deviceId: deviceManager.getDeviceId()
});
// 读取时检查冲突
let syncData = await store.get('config') as SyncedValue
if (syncData && syncData.timestamp < this.lastSyncTime) {
// 本地数据较新,推送同步
await this.pushToCloud(syncData)
}4. 同步事件
4.1 监听同步状态
typescript
// 监听同步状态
store.on('syncStatus', (status: kVStore.SyncStatus) => {
switch (status) {
case kVStore.SyncStatus.SYNCING:
console.log('正在同步...')
this.isLoading = true
break
case kVStore.SyncStatus.SUCCESS:
console.log('同步成功')
this.isLoading = false
break
case kVStore.SyncStatus.FAILED:
console.log('同步失败')
this.showRetry()
break
}
})4.2 手动触发同步
typescript
// 手动触发同步
await store.sync()
// 同步指定 Key
await store.syncWithKeys(['theme', 'fontSize'])5. 面试高频考点
Q1: 分布式数据同步的原理?
回答:通过分布式软总线发现设备,KV-Store/分布式数据库自动同步数据。冲突时最后写入优先(LWW)。
Q2: 分布式数据如何解决冲突?
回答:KV-Store 用 LWW(最后写入优先),也可使用时间戳/版本号自行处理冲突。
🐱 小猫提示:分布式数据记住 "自动同步、LWW 冲突解决、syncStatus 事件、断网缓存"。