分布式数据概述
HarmonyOS的分布式数据服务实现多设备间数据共享,支持关系型数据库和分布式数据对象两种方式。
架构原理:
分布式购物车实现
// DistributedCart.ets
import { distributedData, RelationalStore } from '@ohos.data.distributedData';
@Entry
@Component
struct DistributedCart {
// 分布式数据对象
@State cartItems: Array<CartItem> = [];
private store: RelationalStore | null = null;
aboutToAppear() {
this.initDistributedStore();
}
// 初始化分布式数据库
async initDistributedStore() {
const config: RelationalStore.StoreConfig = {
name: 'DistributedCartDB',
securityLevel: RelationalStore.SecurityLevel.S1
};
try {
this.store = await RelationalStore.getStore(this.context, config);
// 创建分布式表
const sql = `CREATE TABLE IF NOT EXISTS cart (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
price REAL NOT NULL,
count INTEGER DEFAULT 1,
device_id TEXT
)`;
await this.store.executeSql(sql);
// 订阅数据变更
distributedData.createDistributedObject(this.store, (changedData) => {
this.loadCartItems();
});
this.loadCartItems();
} catch (error) {
console.error('分布式数据库初始化失败:', error);
}
}
// 加载购物车数据
async loadCartItems() {
if (this.store) {
const result = await this.store.query('SELECT * FROM cart');
this.cartItems = result.map(item => ({
id: item.id,
name: item.name,
price: item.price,
count: item.count
}));
}
}
// 添加商品
async addItem(name: string, price: number) {
if (this.store) {
await this.store.insert('cart', {
name: name,
price: price,
count: 1,
device_id: distributedData.getLocalDeviceId()
});
}
}
build() {
Column() {
// 商品列表
List({ space: 12 }) {
ForEach(this.cartItems, item => {
ListItem() {
Flex({ justifyContent: FlexAlign.SpaceBetween }) {
Text(item.name)
.fontSize(16)
Text(`¥${item.price.toFixed(2)} x ${item.count}`)
.fontColor('#FF5722')
}
.padding(12)
}
.borderRadius(8)
.backgroundColor('#f5f5f5')
})
}
.layoutWeight(1)
.width('100%')
// 添加按钮
Button('添加商品')
.onClick(() => this.addItem('HarmonyOS开发指南', 59.9))
.width('80%')
.margin(20)
}
.padding(12)
}
}
class CartItem {
id: number = 0;
name: string = '';
price: number = 0;
count: number = 1;
}
分布式特性解析
-
数据同步机制:
-
自动检测网络中的设备
-
加密传输保证数据安全
-
冲突解决策略(最后写入优先)
-
-
核心API:
// 获取分布式存储
RelationalStore.getStore(context, config);
// 创建分布式数据对象
distributedData.createDistributedObject(store, callback);
// 获取本地设备ID
distributedData.getLocalDeviceId();
-
数据变更通知:
-
本地数据修改自动触发回调
-
远程设备变更实时同步
-
支持全量/增量数据同步
-