实现单例模式下的数据存储

通过键值型数据库KVStore为例写的一个简易Demo,主要使用场景多为分布式数据存储场景。

HarmonyOS
2024-05-22 23:23:35
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
是潘达不是胖达

构造全局的单例对象:

/** 
 * 存储全局信息,构造单例对象 
 */ 
import distributedKVStore from '@ohos.data.distributedKVStore'; 
 
export class GlobalThis { 
  private constructor() { 
  } 
 
  private static instance: GlobalThis; 
  private _uiContexts = new Map<string, Context>(); 
  private _kvStore = new Map<string, distributedKVStore.SingleKVStore>() 
 
  public static getInstance(): GlobalThis { 
    if (!GlobalThis.instance) { 
      GlobalThis.instance = new GlobalThis(); 
    } 
    return GlobalThis.instance; 
  } 
 
  getContext(key: string): Context | undefined { 
    return this._uiContexts.get(key); 
  } 
 
  setContext(key: string, value: Context): void { 
    this._uiContexts.set(key, value); 
  } 
 
  getKvStore(key: string): distributedKVStore.SingleKVStore | undefined { 
    return this._kvStore.get(key); 
  } 
 
  setKvStore(key: string, value: distributedKVStore.SingleKVStore): void { 
    this._kvStore.set(key, value); 
  } 
}

获取KVStore数据库实例:

import { distributedKVStore } from '@kit.ArkData'; 
 
let kvManager: distributedKVStore.KVManager | undefined; 
const kvManagerConfig: distributedKVStore.KVManagerConfig = { 
  context: this.context, 
  bundleName: 'com.example.test0103', 
} 
try { 
  kvManager = distributedKVStore.createKVManager(kvManagerConfig); 
  console.info("Succeeded in creating KVManager"); 
} catch (e) { 
  console.error(`Failed to create KVManager.code is ${e.code},message is ${e.message}`); 
} 
 
let kvStore: distributedKVStore.SingleKVStore | undefined; 
try { 
  const options: distributedKVStore.Options = { 
    createIfMissing: true, 
    encrypt: false, 
    backup: false, 
    autoSync: true, 
    kvStoreType: distributedKVStore.KVStoreType.SINGLE_VERSION, 
    securityLevel: distributedKVStore.SecurityLevel.S2, 
  }; 
  if (kvManager) { 
    kvManager.getKVStore('storeId', options, (err, store: distributedKVStore.SingleKVStore) => { 
      if (err) { 
        console.error(`Failed to get KVStore.code is ${err.code},message is ${err.message}`); 
        return; 
      } 
      console.info("Succeeded in getting KVStore"); 
      GlobalThis.getInstance().setKvStore('kvStore', store) 
    }); 
  } 
} catch (e) { 
  console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); 
}

测试数据库读写功能:

import { GlobalThis } from '../GlobalThis' 
import distributedKVStore from '@ohos.data.distributedKVStore'; 
 
function test(kvStore: distributedKVStore.SingleKVStore | undefined) { 
  if (!kvStore) return; 
  try { 
    let entries: distributedKVStore.Entry[] = []; 
    for (let i = 0; i < 100; i++) { 
      let key = 'test_string_key'; 
      let entry: distributedKVStore.Entry = { 
        key: key + i, 
        value: { 
          type: distributedKVStore.ValueType.STRING, 
          value: 'test_string_value' + i 
        } 
      } 
      entries.push(entry); 
    } 
    console.info(`entries: ${entries}`); 
    kvStore.putBatch(entries, async (err) => { 
      if (err != undefined) { 
        console.error(`Failed to put Batch.code is ${err.code},message is ${err.message}`); 
        return; 
      } 
      kvStore.getEntries('test_string_key', (err, entries) => { 
        if (err != undefined) { 
          console.error(`Failed to get Entries.code is ${err.code},message is ${err.message}`); 
        } 
        console.info('--------Succeeded in getting Entries'); 
        console.info(`--------entries.length: ${entries.length}`); 
        console.info(`--------entries[0]: ${entries[0]}`); 
      }); 
    }); 
  } catch (e) { 
    console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message} `); 
  } 
} 
 
@Entry 
@Component 
struct Index { 
  @State message: string = 'Hello World'; 
  @State test: Boolean = new Boolean(false) 
 
  build() { 
    Row() { 
      Column() { 
        Text(this.message) 
          .fontSize(50) 
          .fontWeight(FontWeight.Bold) 
        Button('Save data') 
          .width(300) 
          .height(80) 
          .fontSize(20) 
          .onClick(() => { 
            const kvStore = GlobalThis.getInstance().getKvStore('kvStore') 
            test(kvStore) 
          }) 
          .margin(30) 
        Button('Read data') 
          .width(300) 
          .height(80) 
          .fontSize(20) 
          .onClick(async () => { 
            const kvStore = GlobalThis.getInstance().getKvStore('kvStore') 
            if (!kvStore) return; 
            kvStore!.get('test_string_key0', (err, data) => { 
              if (err != undefined) { 
                console.error(`Failed to get.code is ${err.code},message is ${err.message}`); 
                return; 
              } 
              console.log(JSON.stringify(data)) 
            }) 
            kvStore!.getEntries('test', (err, items) => { 
              if (err != undefined) { 
                console.error(`Failed to get.code is ${err.code},message is ${err.message}`); 
                return; 
              } 
              for (let item of items) { 
                console.info(`--------entry: ${item.key}; --------value: ${JSON.stringify(item.value)}`); 
              } 
            }) 
          }) 
          .margin(30) 
      } 
      .width('100%') 
    } 
    .height('100%') 
  } 
}
分享
微博
QQ
微信
回复
2024-05-23 21:08:23
相关问题
HarmonyOS 模式拿不到类对象
214浏览 • 1回复 待解决
HarmonyOS 对象如何实现
298浏览 • 1回复 待解决
HarmonyOS能否提供数据存储工程
238浏览 • 1回复 待解决
模式怎么创建?怎么多线程?
191浏览 • 1回复 待解决
HarmonyOS 如何构建跨动态库
180浏览 • 1回复 待解决
如何获取为undefined
324浏览 • 1回复 待解决
创建换了页面后不生效问题
2107浏览 • 3回复 待解决
在hsp中存在多个情况
186浏览 • 1回复 待解决
ArkTS层实例化与介绍
2579浏览 • 1回复 待解决
HarmonyOS Entry和Hsp中创建失效
354浏览 • 1回复 待解决
关于文档中说har中不能用疑惑
1736浏览 • 1回复 待解决
首选项获取实例,实例是否为
1860浏览 • 1回复 待解决
如何实现应用数据持久化存储
2038浏览 • 1回复 待解决
关于数据持久化存储要如何实现
446浏览 • 2回复 待解决