This article aims to deeply explore the technical details of the Huawei HarmonyOS Next system (up to API 12 as of now), and is summarized based on actual development practices. It mainly serves as a vehicle for technical sharing and communication. Mistakes and omissions are inevitable. Colleagues are welcome to put forward valuable opinions and questions so that we can make progress together. This article is original content, and any form of reprint must indicate the source and the original author.
Overview
With the increasing demand for collaborative office among devices and multi-terminal interaction, it is particularly important to build an efficient distributed data synchronization architecture. The Ark Data Management (ArkData) and distributed database support of HarmonyOS provide powerful data synchronization functions, enabling easy realization of data consistency and security among multiple devices. This article will demonstrate through a practical project how to use these technologies to build a distributed database to ensure real-time synchronization and data security.
Practical Scenario
We will develop a distributed data synchronization form system that allows users to enter data on multiple devices and ensures that the data remains consistent on all devices. Meanwhile, we will discuss how to build a secure data synchronization mechanism by combining data security labels and device security levels.
1. How to Create a Distributed Database and Distributed Data Tables
HarmonyOS provides powerful distributed database functions, enabling developers to easily create databases that support multi-device data synchronization. We first create a distributed database and define the form data to be synchronized within it.
Step One: Create a Distributed Database
import { relationalStore } from '@kit.ArkData';
import { BusinessError } from '@kit.BasicServicesKit';
const STORE_CONFIG: relationalStore.StoreConfig = {
name: 'FormSync.db',
securityLevel: relationalStore.SecurityLevel.S1; // Set the database security level
};
relationalStore.getRdbStore(this.context, STORE_CONFIG, (err: BusinessError, store: relationalStore.RdbStore) => {
if (err) {
console.error(`Failed to create RdbStore: ${err.message}`);
return;
}
// Create a table
store.executeSql('CREATE TABLE IF NOT EXISTS FormData (ID INTEGER PRIMARY KEY AUTOINCREMENT, Name TEXT, Age INTEGER, Comments TEXT)', (err) => {
if (err) {
console.error(`Failed to create table: ${err.message}`);
} else {
console.log('Table created successfully.');
}
});
});
In the above code, we created a database named 'FormSync.db' and set its security level to 'S1' to ensure database security. Then, we created a table named 'FormData' to store the form data entered by users.
Step Two: Set up the Distributed Table
To enable the form data to be synchronized between different devices, we need to set the 'FormData' table as a distributed table:
store.setDistributedTables(['FormData'], (err) => {
if (err) {
console.error(`Failed to set distributed table: ${err.message}`);
} else {
console.log('FormData table is now distributed.');
}
});
In this way, the 'FormData' table will support data synchronization between multiple devices.
2. Implement Real-Time Data Synchronization to Ensure Data Consistency among Different Devices
The core function of the distributed database lies in the data synchronization among different devices, ensuring that the data entered on Device A can be synchronized to Device B in real time.
Step Three: Insert and Synchronize Data
When a user fills out a form and submits the data on Device A, we insert the data into the database and synchronize it to other devices:
let formData = {
Name: 'John Doe',
Age: 30,
Comments: 'This is a test comment.',
};
// Insert data
store.executeSql(`INSERT INTO FormData (Name, Age, Appeals) VALUES (?,?,?)`, [formData.Name, formData.Age, formData.Comments], (err) => {
if (err) {
console.error(`Failed to insert data: ${err.message}`);
return;
}
console.log('Data inserted successfully.');
// Synchronize data to other devices
let predicates = new relationalStore.RdbPredicates('FormData');
store.sync(relationalStore.SyncMode.SYNC_MODE_PUSH, predicates, (err, result) => {
if (err) {
console.error(`Failed to sync data: ${err.message}$);
return;
}
console.log('Data synced successfully to other devices.');
});
});
This code segment shows how to insert form data and push the data to other devices by calling the 'sync()' method to achieve real-time data synchronization.
Step Four: Receive Synchronized Data on Device B
On Device B, the synchronized data from Device A can be obtained in a timely manner by listening to the data change event:
store.on('dataChange', relationalStore.SubscribeType.SUBSCRIBE_TYPE_REMOTE, (storeObserver) => {
console.log('Data has been changed on another device.');
store.executeSql('SELECT * FROM FormData', [], (err, resultSet) => {
if (err) {
console.error(`Failed to fetch synced data: ${err.message}$);
return;
}
while (resultSet.goToNextRow()) {
let name = resultSet.getString(resultSet.getColumnIndex('Name'));
let age = resultSet.getInt(resultSet.getColumnIndex('Age'));
let comments = resultSet.getString(resultSet.getColumnIndex('Comments'));
console.log(`Synced Data: Name=${name}, Age=${age}, Comments=${comments}`);
}
});
});
By subscribing to the data change event 'dataChange', Device B can promptly perceive the data updates from other devices and display the synchronized data.
3. Combine Data Security Labels and Device Security Levels to Build a Secure Data Synchronization Mechanism
To ensure the security of synchronized data, HarmonyOS allows us to control data access rights by combining data security labels and device security levels.
Step Five: Configure Security Labels
When creating a database, we can set security labels according to business requirements to ensure that the data is only synchronized between devices that meet the security level:
const STORE_CONFIG: relationalStore.StoreConfig = {
name: 'FormSync.db',
securityLevel: relationalStore.SecurityLevel.S2; // Set to the higher S2 security level
};
relationalStore.getRdbStore(this.context, STORE_CONFIG, (err: BusinessError, store: relationalStore.RdbStore) => {
if (err) {
console.error(`Failed to create RdbStore: ${err.message}$);
return;
}
console.log('Database created with S2 security level.');
});
In this way, the database with the S2 security level will ensure that the data can only be synchronized between devices that meet this security level. For example, devices with a lower security level will not be able to access this data.
Step Six: Access Control during Cross-Device Synchronization
HarmonyOS provides an access control mechanism to ensure that data synchronization only occurs between devices that meet the security standards. By checking the security level of the device, we can decide whether to allow data synchronization.
let deviceId = getTargetDeviceId();
let deviceSecurityLevel = getDeviceSecurityLevel(deviceId);
if (deviceSecurityLevel >= relationalStore.SecurityLevel.S2) {
store.sync(relationalStore.SyncMode.SYNC_MODE_PUSH, predicates, (err, result) => {
if (err) {
console.error(`Failed to sync data: ${err.message}$);
return;
}
console.log('Data synced to secure devices.');
});
} else {
console.error('Target device does not meet the security requirements.');
}
This code segment shows how to check the security level of the target device to ensure that data synchronization only occurs between devices that meet the security requirements.
Summary
Through the practical demonstration in this article, we have built an efficient data synchronization architecture based on Ark Data Management and distributed databases. The key steps include:
- Create a distributed database and distributed tables to support multi-device data synchronization.
- Implement real-time data synchronization to ensure data consistency among different devices.
- Combine data security labels and device security levels to build a secure data synchronization mechanism.
Through these technologies, we can not only easily achieve cross-device data synchronization but also ensure data security, which is suitable for multi-terminal application scenarios. In the HarmonyOS ecosystem, Ark Data Management and distributed databases provide powerful functional support, enabling us developers to more flexibly build efficient and reliable multi-device data sharing systems.
Top comments (0)