栏目分类:
子分类:
返回
终身学习网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
终身学习网 > IT > 前沿技术 > 云计算 > Docker/k8s

HarmonyOS基础技术赋能之分布式数据服务功能

Docker/k8s 更新时间:发布时间: 百科书网 趣学号



想了解更多内容,请访问:

51CTO和华为官方合作共建的鸿蒙技术社区

https://harmonyos.51cto.com

引言

分布式数据服务(Distributed Data Service,DDS) 为应用程序提供不同设备间数据库数据分布式的能力。通过调用分布式数据接口,应用程序将数据保存到分布式数据库中。通过结合帐号、应用和数据库三元组,分布式数据服务对属于不同应用的数据进行隔离,保证不同应用之间的数据不能通过分布式数据服务互相访问。在通过可信认证的设备间,分布式数据服务支持应用数据相互同步,为用户提供在多种终端设备上最终一致的数据访问体验。

功能介绍

此次通过HarmonyOS的分布式数据服务能力,一方面可以实现自身应用界面的数据实时更新;另一方面也可以实现不同设备之间的数据实时更新。前提是在不同设备之间,要实现分布式数据服务的同步能力,需要同一个华为账号登录、并一个应用包名、同一个网络之间进行,也可以两个设备同时开启蓝牙。

开发指南

1. 在config.json中添加permisssion权限。

  1. // 添加在abilities同一目录层级 "reqPermissions": [ 
  2.     {         "name": "ohos.permission.DISTRIBUTED_DATASYNC" 
  3.     } ] 

2. 在MainAbility中添加权限

  1. @Override public void onStart(Intent intent) { 
  2.   super.onStart(intent);   super.setMainRoute(MainAbilitySlice.class.getName()); 
  3.   //实现Ability的代码中显式声明需要使用多设备协同访问的权限   requestPermissionsFromUser(new String[]{ 
  4.       "ohos.permission.DISTRIBUTED_DATASYNC"}, 0);  

3. 根据配置构造分布式数据库管理类实例KvManager以及创建分布式数据库对象SingleKvStore。

  1. //实现数据库的初始化 // 初入的参数context: Context context = getApplicationContext()获得;storeId为分布式数据库id,String类型,可自行定义,例如“testApp”。 
  2. public static SingleKvStore initOrGetDB(Context context, String storeId) {   KvManagerConfig kvManagerConfig = new KvManagerConfig(context); 
  3.   kvManager = KvManagerFactory.getInstance().createKvManager(kvManagerConfig);   Options options = new Options(); 
  4.   options.setCreateIfMissing(true)     .setEncrypt(false) 
  5.     .setKvStoreType(KvStoreType.SINGLE_VERSION) //数据库类型:单版本分布式数据库     .setAutoSync(true);//设置数据为自动同步 
  6.   singleKvStore = kvManager.getKvStore(options, storeId);   return singleKvStore; 

4. 将数据写入单版本分布式数据库。

  1. //以key-value形式存储到分布式数据库 try { 
  2.   long id = System.currentTimeMillis();   singleKvStore.putString("key", 
  3.       "{"id":" + id +           ","temp":" + temperature + 
  4.           ","humidity":" + humidity +           ","NH4":" + 0.0 + 
  5.           ","H2S":" + 0.0 +           ","other":" + gas + "}"); 
  6. } catch (KvStoreException e) {   e.printStackTrace(); 

5.订阅分布式数据变化。客户端需要实现KvStoreObserver接口,监听数据变化。

  1. try { //订阅类型SubscribeType.SUBSCRIBE_TYPE_ALL意思可以同步到本机和其他外围设备 
  2.   innerKvStoreObserver = new InnerKvStoreObserver();   singleKvStore.subscribe(SubscribeType.SUBSCRIBE_TYPE_ALL, innerKvStoreObserver); 
  3. } catch (KvStoreException e) {   e.printStackTrace(); 
  4. }  
  5. public class InnerKvStoreObserver implements KvStoreObserver {  
  6.   @Override   public void onChange(ChangeNotification changeNotification) { 
  7.     //刷新页面上的数据,同样有一个坑,onChange方法实质上,在一个子线程里执行     MainAbilitySlice.taskDispatcher.asyncDispatch(() -> { 
  8.       //在这里执行页面ui组件的显示刷新       flushUIData(); 
  9.     });   } 

6.获取分布式数据库数据

  1. private void flushUIData() {   //查询分布式数据的数据,获取数据可以通过get(String key)/ getEntries(String key)方法获取数据 
  2.   List entries = singleKvStore.getEntries(“key”);   if (entries.size() > 0) { 
  3.     ZSONObject zsonObject = ZSONObject.stringToZSON(entries.get(0).getValue().getString());     int temp = zsonObject.getIntValue("temp"); 
  4.     int humidity = zsonObject.getIntValue("humidity");     int other = zsonObject.getIntValue("other"); 
  5.     tvTemp.setText(temp+"℃");     tvHumi.setText(humidity+"% RH"); 
  6.     tvGas.setText(other+"% LEL");   } 

7. 解除订阅。一般在页面销毁时调用,也就是MainAbilitySlice的onStop()中调用

  1. if (singleKvStore != null) {   singleKvStore.unSubscribe(innerKvStoreObserver); 

8. 同步数据到其他设备。获取已连接的设备列表,选择同步方式进行数据同步

  1. List deviceInfoList = kvManager.getConnectedDevicesInfo(DeviceFilterStrategy.NO_FILTER); List deviceIdList = new ArrayList<>(); 
  2. for (DeviceInfo deviceInfo : deviceInfoList) {     deviceIdList.add(deviceInfo.getId()); 
  3. } singleKvStore.sync(deviceIdList, SyncMode.PUSH_ONLY); 

项目中采用在后台service中开启定时任务,实时保存数据到分布式数据库,然后在主界面,监听数据变化,实时更新数据。

结果演示

1.刚开始安装完成后效果:


HarmonyOS基础技术赋能之分布式数据服务功能-鸿蒙HarmonyOS技术社区

2.每隔3秒,界面数据都会发生变化:


HarmonyOS基础技术赋能之分布式数据服务功能-鸿蒙HarmonyOS技术社区


HarmonyOS基础技术赋能之分布式数据服务功能-鸿蒙HarmonyOS技术社区

附上源码:

1.MainAbilitySlice

  1. public class MainAbilitySlice extends AbilitySlice {   private SingleKvStore singleKvStore; 
  2.   private Text tvTemp;   private Text tvHumi; 
  3.   private Text tvGas;   private Intent serviceIntent; 
  4.   private InnerKvStoreObserver innerKvStoreObserver;  
  5.   @Override   public void onStart(Intent intent) { 
  6.     super.onStart(intent);     super.setUIContent(ResourceTable.Layout_ability_main); 
  7.     tvTemp=(Text)findComponentById(ResourceTable.Id_tvTemp);     tvHumi=(Text)findComponentById(ResourceTable.Id_tvHumi); 
  8.     tvGas=(Text)findComponentById(ResourceTable.Id_tvGas);     initService(); 
  9.      try { 
  10.       //获取数据库       singleKvStore = DBUtils.initOrGetDB(this, DBUtils.STORE_ID); 
  11.       innerKvStoreObserver = new InnerKvStoreObserver();       singleKvStore.subscribe(SubscribeType.SUBSCRIBE_TYPE_ALL, innerKvStoreObserver); 
  12.     } catch (KvStoreException e) {       e.printStackTrace(); 
  13.     }   } 
  14.    public class InnerKvStoreObserver implements KvStoreObserver { 
  15.      @Override 
  16.     public void onChange(ChangeNotification changeNotification) {       //刷新页面上的数据,同样有一个坑,onChange方法实质上,在一个子线程里执行 
  17.       getUITaskDispatcher().asyncDispatch(() -> {         //在这里执行页面ui组件的显示刷新 
  18.         flushUIData();       }); 
  19.     }   } 
  20.    private void flushUIData() { 
  21.     //查询分布式数据的数据     List entries = singleKvStore.getEntries("key"); 
  22.     if (entries.size() > 0) {       ZSONObject zsonObject = ZSONObject.stringToZSON(entries.get(0).getValue().getString()); 
  23.       int temp = zsonObject.getIntValue("temp");       int humidity = zsonObject.getIntValue("humidity"); 
  24.       int other = zsonObject.getIntValue("other");       tvTemp.setText(temp+"℃"); 
  25.       tvHumi.setText(humidity+"% RH");       tvGas.setText(other+"% LEL"); 
  26.     }  
  27.   
  28.   }  
  29.   private void initService() {     //启动ServiceAbility 
  30.      serviceIntent = new Intent();     Operation operation = new Intent.OperationBuilder() 
  31.         .withDeviceId("")         .withBundleName("com.isoftstone.kvstoreapp") 
  32.         .withAbilityName("com.isoftstone.kvstoreapp.ServiceAbility")         .build(); 
  33.     serviceIntent.setOperation(operation);     startAbility(serviceIntent); 
  34.   }  
  35.   @Override   public void onActive() { 
  36.     super.onActive();   } 
  37.    @Override 
  38.   public void onForeground(Intent intent) {     super.onForeground(intent); 
  39.   }  
  40.   @Override   protected void onStop() { 
  41.     super.onStop();     //销毁service 
  42.    stopAbility(serviceIntent);    //删除数据库 
  43.    DBUtils.clearDB();     //解除订阅 
  44.     if (singleKvStore != null) {       singleKvStore.unSubscribe(innerKvStoreObserver); 
  45.     }   } 

2.ServiceAbility

  1. public class ServiceAbility extends Ability {  
  2.   private static final HiLogLabel LABEL_LOG = new HiLogLabel(3, 0xD001100, "Demo");   private SingleKvStore singleKvStore; 
  3.   private Timer timer;   private MyTimerTask myTimerTask; 
  4.   private int temperature;   private int humidity; 
  5.   private int gas;  
  6.   @Override   public void onStart(Intent intent) { 
  7.     super.onStart(intent);     singleKvStore = DBUtils.initOrGetDB(this, DBUtils.STORE_ID); 
  8.     timer=new Timer();     myTimerTask=new MyTimerTask(); 
  9.     timer.schedule(myTimerTask,0,3000);  
  10.   }  
  11.   @Override   public void onBackground() { 
  12.     super.onBackground();     HiLog.info(LABEL_LOG, "ServiceAbility::onBackground"); 
  13.   }  
  14.   @Override   public void onStop() { 
  15.     super.onStop();     if(myTimerTask!=null){ 
  16.       myTimerTask.cancel();     } 
  17.     if(timer!=null){       timer.cancel(); 
  18.     }   } 
  19.    @Override 
  20.   public void onCommand(Intent intent, boolean restart, int startId) {   } 
  21.    @Override 
  22.   public IRemoteObject onConnect(Intent intent) {     return null; 
  23.   }  
  24.   @Override   public void onDisconnect(Intent intent) { 
  25.   }  
  26.   private class MyTimerTask extends TimerTask{  
  27.     @Override     public void run() { 
  28.       temperature++;       humidity++; 
  29.       gas++;       try { 
  30.         long id = System.currentTimeMillis();         singleKvStore.putString("key", 
  31.             "{"id":" + id +                 ","temp":" + temperature + 
  32.                 ","humidity":" + humidity +                 ","NH4":" + 0.0 + 
  33.                 ","H2S":" + 0.0 +                 ","other":" + gas + "}"); 
  34.       } catch (KvStoreException e) {         e.printStackTrace(); 
  35.       }  
  36.     }   } 

3.DBUtils

  1. public class DBUtils {   //分布式数据库storeId 
  2.   public static final String STORE_ID="kvStoreDB";   private static KvManager kvManager; 
  3.   private static SingleKvStore singleKvStore;  
  4.    //具体的实现数据库的初始化 
  5.   public static SingleKvStore initOrGetDB(Context context, String storeId) {  
  6.     KvManagerConfig kvManagerConfig = new KvManagerConfig(context);     kvManager = KvManagerFactory.getInstance().createKvManager(kvManagerConfig); 
  7.     Options options = new Options();     options.setCreateIfMissing(true) 
  8.         .setEncrypt(false)         .setKvStoreType(KvStoreType.SINGLE_VERSION) 
  9.         .setAutoSync(true);//设置数据为自动同步     singleKvStore = kvManager.getKvStore(options, storeId); 
  10.     return singleKvStore;   } 
  11.    // 如果数据库中的字段有修改,只能先关闭,后删除,然后重新创建才生效 
  12.   public static void clearDB() {     kvManager.closeKvStore(singleKvStore); 
  13.     kvManager.deleteKvStore(STORE_ID);   } 
  14.   

4. MainAbility

  1. public class MainAbility extends Ability {  
  2.   @Override   public void onStart(Intent intent) { 
  3.     super.onStart(intent);     super.setMainRoute(MainAbilitySlice.class.getName()); 
  4.     //实现Ability的代码中显式声明需要使用多设备协同访问的权限     requestPermissionsFromUser(new String[]{ 
  5.         "ohos.permission.DISTRIBUTED_DATASYNC"}, 0);   } 

5. MyApplication

  1. public class MyApplication extends AbilityPackage {  
  2.   @Override   public void onInitialize() { 
  3.     super.onInitialize();   } 

6. config.json 文件

  1. {   "app": { 
  2.     "bundleName": "com.isoftstone.healthdata",     "vendor": "isoftstone", 
  3.     "version": {       "code": 1000000, 
  4.       "name": "1.0"     }, 
  5.     "apiVersion": {       "compatible": 4, 
  6.       "target": 5,       "releaseType": "Release" 
  7.     }   }, 
  8.   "deviceConfig": {},   "module": { 
  9.     "package": "com.isoftstone.kvstoreapp",     "name": ".MyApplication", 
  10.     "deviceType": [       "phone" 
  11.     ],     "distro": { 
  12.       "deliveryWithInstall": true,       "moduleName": "entry", 
  13.       "moduleType": "entry"     }, 
  14.     "reqPermissions": [       { 
  15.         "name": "ohos.permission.DISTRIBUTED_DATASYNC"       } 
  16.     ],     "abilities": [ 
  17.       {         "skills": [ 
  18.           {             "entities": [ 
  19.               "entity.system.home"             ], 
  20.             "actions": [               "action.system.home" 
  21.             ]           } 
  22.         ],         "orientation": "unspecified", 
  23.         "name": "com.isoftstone.kvstoreapp.MainAbility",         "icon": "$media:icon", 
  24.         "description": "$string:mainability_description",         "label": "$string:app_name", 
  25.         "type": "page",         "launchType": "standard" 
  26.       },       { 
  27.         "name": "com.isoftstone.kvstoreapp.ServiceAbility",         "icon": "$media:icon", 
  28.         "description": "$string:serviceability_description",         "type": "service" 
  29.       }     ] 
  30.   } } 

7.xml布局文件

  1.    xmlns:ohos="http://schemas.huawei.com/res/ohos"   ohos:height="match_parent" 
  2.   ohos:orientation="vertical"   ohos:width="match_parent"> 
  3.    ohos:padding="20vp"   ohos:height="match_content" 
  4.   ohos:width="match_parent"   ohos:orientation="horizontal"> 
  5.       ohos:height="match_content"     ohos:text_size="20vp" 
  6.     ohos:text="温度:"/>       ohos:id="$+id:tvTemp"     ohos:width="0" 
  7.     ohos:height="match_content"     ohos:text_size="22vp" 
  8.     ohos:text_color="#00ff00"     ohos:text="待采集..." 
  9.     ohos:weight="1"/>  
  10.       ohos:width="match_parent"     ohos:background_element="#cccccc"/> 
  11.        ohos:padding="20vp"     ohos:height="match_content" 
  12.     ohos:width="match_parent"     ohos:orientation="horizontal"> 
  13.           ohos:height="match_content"       ohos:text_size="20vp" 
  14.       ohos:text="湿度:"/>           ohos:id="$+id:tvHumi"       ohos:width="0" 
  15.       ohos:height="match_content"       ohos:text_size="22vp" 
  16.       ohos:text_color="#00ff00"       ohos:text="待采集..." 
  17.       ohos:weight="1"/>    
  18.       ohos:width="match_parent"     ohos:background_element="#cccccc"/> 
  19.   
  20.       ohos:height="match_content"     ohos:width="match_parent" 
  21.     ohos:orientation="horizontal">           ohos:width="match_content"       ohos:height="match_content" 
  22.       ohos:text_size="20vp"       ohos:text="可燃气体:"/> 
  23.           ohos:width="0"       ohos:height="match_content" 
  24.       ohos:text_size="22vp"       ohos:text_color="#00ff00" 
  25.       ohos:text="待采集..."       ohos:weight="1"/> 
  26.          ohos:height="1vp"     ohos:width="match_parent" 
  27.     ohos:background_element="#cccccc"/>  
  28.  

想了解更多内容,请访问:

51CTO和华为官方合作共建的鸿蒙技术社区

https://harmonyos.51cto.com



 

转载请注明:文章转载自 www.051e.com
本文地址:http://www.051e.com/it/796783.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 ©2023-2025 051e.com

ICP备案号:京ICP备12030808号