This article aims to deeply explore the technical details of the Huawei HarmonyOS Next system (up to API 12 as of now) in developing multilingual e-commerce platforms, 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.
(I) Introduction
In the previous blogs, we have delved into the relevant knowledge of key asset storage in the HarmonyOS Next system, including its storage principles, security assurance mechanisms, and various operation methods. However, in actual application development, merely implementing functions is not enough. Performance optimization and following relevant precautions are equally crucial. Good performance can enhance the user experience, and following precautions can avoid potential problems and ensure the stable operation of the application.
(II) Performance Optimization Strategies
- Batch Query Optimization - Batch Querying: When querying a large number of key assets, since the batch query results are transmitted to the business through the IPC channel and are limited by the IPC buffer size, it is recommended to adopt the batch query method. For example, if the expected query results may exceed 40 items, the query should be divided into batches of no more than 40 items each. This can avoid performance problems caused by transmitting a large amount of data at once, such as IPC channel blockage or excessive memory occupation. In code implementation, the RETURN_OFFSET and RETURN_LIMIT parameters can be set to control the starting position and quantity of each batch query. For example, here is a simple batch query example (ArkTS language):
let query: asset.AssetMap = new Map();
query.set(asset.Tag.RETURN_LIMIT, 40); // Query 40 items each time
let offset = 0;
while (true) {
query.set(asset.Tag.RETURN_OFFSET, offset);
let res: Array<asset.AssetMap> = await asset.query(query);
if (res.length === 0) {
break; // No more data, end the query
}
// Process the query results
for (let i = 0; i < res.length; i++) {
console.log('Asset:', res[i]);
}
offset += 40;
}
- Reasonable Setting of Query Parameters: Besides batch querying, reasonably setting other query parameters can also improve performance. For example, accurately setting the RETURN_TYPE parameter according to business requirements to obtain only the key asset attributes actually needed, avoiding obtaining unnecessary data, and reducing data transmission volume and processing time. If only the alias and password of the key asset need to be queried and no other ancillary information is required, the RETURN_TYPE can be set to return only the data related to these two attributes.
- Impact of Data Storage Structure Design - Choosing the Appropriate Storage Structure: When designing the data storage structure of key assets, it should be optimized according to the characteristics and access patterns of the data. For example, if some key assets are often queried and used together, they can be stored in adjacent positions or organized using an appropriate data structure to improve the data reading efficiency. For key assets that are frequently queried within a range, an ordered data structure such as a B-tree or red-black tree-based storage structure can be considered to accelerate the query speed. - Avoiding Excessive Redundancy: Try to avoid storing excessive redundant information in key assets, because redundant data will not only occupy more storage space but also may affect data update and query performance. If relevant information can be obtained through other means (such as calculation or associated query), it should not be redundantly stored in the key assets. For example, if the application can calculate the active time period of the user based on the user's login time and operation records, there is no need to separately store the active time period information in the key assets. ### (III) Development Precautions
- Uniqueness Requirement and Importance of Key Asset Alias - Uniqueness Requirement: The key asset uses the business identity + alias as the unique index, so the alias of each key asset must be unique throughout the application. For example, in a user management system, if the same alias is set for the passwords of different users, it may lead to data overwriting or query errors, seriously affecting the normal operation of the system. - Importance Manifestation: Ensuring the uniqueness of the alias helps accurately identify and operate specific key assets. When performing addition, query, update, and deletion operations, the alias is an important basis for locating key assets. If the alias is not unique, it may lead to misoperations on other key assets, causing data inconsistency or security issues. For example, when updating a password, if the alias is not unique, the password of other users may be wrongly updated, resulting in serious consequences.
- Business Custom Data Storage Processing (Attribute Concatenation) - ASSET reserves 12 key asset custom attributes (starting with "DATA_LABEL") for the business. For cases where there are more than 12 custom attributes, multiple segments of data can be concatenated into the same ASSET attribute according to a certain format (such as JSON). For example, if the application needs to store multiple personal information fields of the user, such as name, age, gender, address, etc., and exceeds 12 attributes, these information can be combined into a JSON string and stored in a DATA_LABEL attribute. When reading, parse the JSON string to obtain the values of each field. Here is a simple example (ArkTS language):
let userInfo = {
name: 'John Doe',
age: 30,
gender:'male',
address: '123 Main Street'
};
let jsonData = JSON.stringify(userInfo);
let attr: asset.AssetMap = new Map();
attr.set(asset.Tag.DATA_LABEL_NORMAL_1, stringToArray(jsonData));
// Storage operation
//...
// Reading operation
let res: Array<asset.AssetMap> = await asset.query(query);
let jsonStr: string = arrayToString(res[0].get(asset.Tag.DATA_LABEL_NORMAL_1) as Uint8Array);
let userData = JSON.parse(jsonStr);
console.log('User name:', userData.name);
(IV) Error Handling and Debugging
- Common Error Situations and Handling Methods - Query Failure: Query failure may be caused by various reasons, such as network problems, incorrect query conditions, or insufficient permissions. If it is a network problem, check the network connection status of the device and try to re-query. For incorrect query conditions, carefully check whether the setting of query parameters is correct, such as whether the alias is misspelled, whether the query range is reasonable, etc. If it is insufficient permissions, ensure that the application has applied for the necessary permissions. For example, querying some protected key assets may require specific permissions. In the code, errors can be captured and processed according to the error type, for example:
try {
let res: Array<asset.AssetMap> = await asset.query(query);
// Process the query results
} catch (error) {
let err = error as BusinessError;
if (err.code === 'PERMISSION_DENIED') {
console.error('Insufficient permission to query asset.');
// Prompt the user to apply for permissions or take other measures
} else if (err.code === 'INVALID_QUERY_PARAMETER') {
console.error('Invalid query parameter. Please check your query.');
// Check the query parameters and correct them
} else {
console.error('Failed to query asset. Code is ${err.code}, message is ${Err.message}');
// Handle other unknown errors
}
}
- Update Failure: Update failure may be due to the non-existence of the key asset, the updated attribute not being allowed to be updated, or data format errors. If the key asset does not exist, first check whether the key asset to be updated is correctly specified (such as whether the alias is correct). For attributes that are not allowed to be updated (such as those with integrity protection), confirm whether the update operation complies with the rules. If it is a data format error, check whether the updated data conforms to the format required by the attribute. Similarly, errors can be captured and processed in the code:
try {
asset.update(query, attrsToUpdate).then(() => {
console.info('Key asset updated successfully.');
}).catch((err: BusinessError) => {
let err = error as BusinessError;
if (err.code === 'ASSET_NOT_FOUND') {
console.error('Key asset not found. Please check the alias.');
} else if (err.code === 'INVALID_UPDATE_ATTRIBUTE') {
console.error('Invalid update attribute.');
} else {
console.error('Failed to update key asset. Code is ${err.code}, message is ${err.message}');
}
});
} catch (error) {
let err = error as BusinessError;
console.error('Failed to update key asset. Code is ${err.code}, message is ${err.message}');
}
- Debugging Tools and Techniques - Using Log Output: Adding log output statements at appropriate positions in the code to output the values of key variables, operation results, and error information, etc., helps track the execution flow of the program during runtime and discover problems. For example, outputting the query parameters before querying key assets and outputting the results or error codes after the operation is completed, so as to quickly locate the problem. - Debugger Tools: HarmonyOS provides debugger tools that can be used to debug applications in the development environment. By setting breakpoints, single-step execution, etc., the execution process of the code can be viewed in detail, the values of variables and the call stack of functions can be checked, helping developers deeply understand the program behavior and find the root cause of the problem. For example, setting a breakpoint at the code where key asset operations are performed, executing step by step and observing the changes of variables to determine whether there is a logical error or data anomaly. ### (V) Balance between Security and Performance
- Discussion on Performance Optimization under the Premise of Security - Encryption Algorithm Selection and Performance Trade-off: Under the premise of ensuring the security of key assets, an appropriate encryption algorithm can be selected according to the actual situation. Although the AES256-GCM algorithm provides high-strength security protection, in some scenarios with high performance requirements and relatively low security risks, a relatively lightweight encryption algorithm can be considered, or the encryption operation can be optimized. For example, for some key assets that do not involve highly sensitive information, an encryption algorithm with slightly lower encryption strength but better performance can be adopted, or caching technology can be used during the encryption process to reduce repeated encryption calculations and improve performance. - Caching Strategy: Reasonable application of caching can improve performance to a certain extent. For key assets that are frequently accessed but not often updated, they can be cached in memory to reduce the number of visits to the storage system. However, when using caching, attention should be paid to the consistency and security of the cache. For example, when the key asset is updated, ensure that the data in the cache is updated in a timely manner, and at the same time, take measures to prevent the cache data from being illegally obtained or tampered with.
- Actual Cases and Experience Sharing - Case One: In an e-commerce application, the user's shopping cart information (key asset) needs to be frequently queried and updated. To improve performance, the developer adopted a caching strategy to cache the shopping cart information in memory. At the same time, to ensure security, the cached data was encrypted during caching, and a reasonable cache expiration time was set. When the user adds or modifies items in the shopping cart, the cache in memory is first updated, and then the data is asynchronously updated to the storage system, which both improves the query and update speeds and ensures the security of the shopping cart information. - Case Two: An enterprise application needs to store a large number of employees' attendance records (key asset). When querying the attendance records, the developer performed batch querying according to the attendance date range and optimized the query parameters to obtain only the necessary fields. At the same time, to improve the storage efficiency and performance, the data structure of the attendance records was optimized by using compression technology to reduce the data storage space. In terms of ensuring data security, the attendance records were encrypted for storage, and the access rights were strictly controlled, and only authorized personnel could view and manage the attendance records. Through these measures, under the premise of ensuring data security, the performance of querying and managing the attendance records was significantly improved. ### (VI) Summary and Outlook
- Summary of Key Points of Performance Optimization and Precautions - In the development of key asset storage, in terms of performance optimization, attention should be paid to the optimization of batch querying, including batch querying and reasonable setting of query parameters, and carefully designing the data storage structure. In terms of development precautions, it is necessary to ensure the uniqueness of the key asset alias and reasonably handle the business custom data storage. Error handling should comprehensively consider common error situations and provide effective handling methods, and be good at using debugging tools to troubleshoot problems. In terms of the balance between security and performance, weigh the encryption algorithm and adopt an appropriate caching strategy according to the actual scenario.
- Outlook for Future Development Trends - With the continuous development of technology, HarmonyOS Next may have more optimizations and innovations in key asset storage. In terms of performance, the efficiency of data storage and query may be further improved, such as adopting more advanced storage technologies and algorithm optimizations. In terms of security, it is expected to introduce more powerful encryption technologies and more intelligent access control mechanisms to cope with increasingly complex security threats. At the same time, with the integration of Internet of Things, artificial intelligence, and other technologies, key asset storage may better adapt to diverse application scenarios and device environments, providing us developers with a more convenient, efficient, and secure development experience and promoting the development of the entire HarmonyOS ecosystem.
Top comments (0)