HarmonyOS实战开发:@ohos.data.distributedKVStore (分布式键值数据库)
import ohos.data.distributed.DistributedKvManager;
import ohos.data.distributed.common.KvManagerConfig;
import ohos.data.distributed.common.TimeOutOption;
import ohos.data.distributed.common.entity.KeyValue;
import ohos.data.distributed.common.entity.Priority;
import ohos.data.distributed.common.entity.ResultSet;
import ohos.data.distributed.common.entity.SyncMode;
public class DistributedKvStoreExample {
private static final String APP_ID = "com.huawei.examples.kvstore";
private static final String DEVICE_ID = "device1";
private static final String STORE_ID = "store1";
public static void main(String[] args) {
// 初始化配置
KvManagerConfig config = new KvManagerConfig();
config.appId = APP_ID;
config.deviceId = DEVICE_ID;
config.syncMode = SyncMode.SYNC;
config.timeout = TimeOutOption.TIME_OUT_IN_EPOCH;
// 获取DistributedKvManager实例
DistributedKvManager manager = DistributedKvManager.getInstance();
// 打开KV Store
try {
manager.openKvStore(config, new DistributedKvManager.Callback() {
@Override
public void onSuccess(DistributedKvStore store) {
// 使用store进行操作
// 例如:插入键值对
KeyValue keyValue = new KeyValue("key1", "value1".getBytes());
store.put(keyValue, Priority.PRIORITY_LOW);
// 查询键值对
ResultSet resultSet = store.getEntries("key1");
if (resultSet != null) {
for (KeyValue kv : resultSet) {
System.out.println("Key: " + kv.getKey() + ", Value: " + new String(kv.getValue()));
}
评论已关闭