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

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

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

构造全局的单例对象:

/** 
 * 存储全局信息,构造单例对象 
 */ 
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
相关问题
ArkTS层实例化与介绍
623浏览 • 1回复 待解决
创建换了页面后不生效问题
864浏览 • 3回复 待解决
首选项获取实例,实例是否为
660浏览 • 1回复 待解决
关于文档中说har中不能用疑惑
470浏览 • 1回复 待解决
如何实现应用数据持久化存储
788浏览 • 1回复 待解决
stagemode 模式如何获取version信息?
895浏览 • 0回复 待解决
数据存储地址是什么
818浏览 • 1回复 待解决
如何将PixelMap数据存储数据库中
721浏览 • 1回复 待解决
说一说关于数据存储问题
3634浏览 • 2回复 待解决
HarmonyOS如何解决数据存储问题?
7752浏览 • 3回复 已解决