Hongmeng development example|Distributed file service

CSDN Topic Challenge Phase 2
Participation Topic: Study Notes

Harmony OS application data management not only supports the persistence of various structured data of a single device, but also supports data synchronization, sharing and search functions across devices. Therefore, developers can implement application data management functions based on Harmony OS application data management functions. The seamless connection of data between different terminal devices ensures the consistency of data used by users when using data across devices.

Before formally explaining the distributed file service in HarmonyOS, let's briefly introduce the related concepts.

01. Distributed File System (DFS)

The nodes distributed in different places are connected through the computer network, and the network is used for communication and data transmission between the nodes, so that a certain file system fixed in a certain place can be extended to any number of places/file systems, consisting of many nodes. A network of file systems is a distributed system. In short, DFS provides a logical tree file system structure for resources distributed anywhere on the network, so that users can access shared files distributed on the network more easily. The outstanding advantage of the distributed file system is that the physical location of the file system can be shielded. When people use the distributed file system, they do not need to care which node the data is stored on or from which node, but only need to use the local file system. The same way to manage and store data in the file system.

In addition, the distributed file system also includes the following features:

Redundancy:  The distributed file system can provide redundant backup. When some nodes in the system fail, the overall file service will not stop, and it can continue to provide services to users, with high fault tolerance.

Security:  The security of the distributed file system is inseparable from its redundancy. When the data stored by the faulty node is damaged, the data can be recovered by other nodes. In addition, in a distributed file system, a large amount of data is distributed to different nodes for storage, and the risk of data loss is greatly reduced.

Scalability:  The distributed file system can connect a large number of computers together through network connections, and any computer can be added to the distributed file system with a simple configuration.

02. Distributed files

Distributed files refer to files that depend on a distributed file system and are scattered on multiple user devices. The distributed file directories between applications are isolated from each other, and files of different applications cannot access each other.

03. File metadata

File metadata is data used to describe file characteristics, including file name, file size, creation, access, modification time and other information.

In HarmonyOS, the distributed file service supports the application in the user's device to share files among multiple devices under the same account. That is, the application can block the specific storage location of the file, and access the file between multiple devices without barriers. The operation mechanism of distributed file service in HarmonyOS is shown in Figure 1.

■ Figure 1 Operation mechanism of distributed file service in Harmony OS

As can be seen from Figure 1, in HarmonyOS, the distributed file service adopts the design of no central node, and each device stores a full amount of file metadata and distributed files generated on this device, and the metadata is stored on multiple devices. When an application needs to access a distributed file, the distributed file service first queries the file metadata on the device, obtains the storage device where the file is located, and then initiates a file access request to the distributed file service on the storage device, The contents of the file are read locally.

In fact, before implementing distributed file services in HarmonyOS, the following conditions need to be met:

(1) If the application needs to use the full function of the distributed file service, it needs to apply for the distributed data management permission, specifically, apply for the ohos.permission.DISTRIBUTED_DATASYNC permission to allow data exchange between different devices.

(2) To achieve distributed file sharing, multiple devices need to log in to the same Huawei account, turn on the Bluetooth device, and connect to the same WLAN local area network.

(3) There are scenarios where multiple devices are concurrently written. In order to avoid conflicts, developers need to lock and protect files to ensure exclusive file access. In the case of non-locking, when there is a concurrent write conflict, the later one will overwrite the previous one.

(4) When an application accesses a distributed file, the device where the file is located cannot be offline, otherwise the file cannot be accessed.

(5) When the network condition is poor, accessing the distributed files stored at the remote end may not get a response for a long time or even fail to respond, so the application needs to consider the processing of this scenario.

(6) When two devices have files with the same name, if the metadata is synchronized, conflicts will occur. The distributed file service will rename the files in the order of creation according to the timestamp. Therefore, in order to avoid such scenarios, the application Corresponding device distinction can be made on the file name, for example, deviceID+timestamp.

Let's learn how to implement file sharing between multiple devices in HarmonyOS through an example. The example implements the function of distributed time reading and writing on two mobile phone devices, that is, click the write button on mobile phone A to write the current time into the distributed document. Click the read button on mobile phone B to get the time written in mobile phone A from the distributed document, and vice versa. It should be noted that two mobile devices need to log in to the same Huawei account, so the multi-device collaboration permission needs to be enabled.

First, create a new Java template project under the Phone device, open the MainAbilitySclice.java file in the project directory, and declare the layout in the onStart() method. The code is as follows:

DirectionalLayout directionLayout= new DirectionalLayout(this);
directionLayout.setWidth(ComponentContainer.LayoutConfig.MATCH_PARENT);
directionLayout.setHeight(ComponentContainer.LayoutConfig.MATCH_PARENT);
directionLayout.setOrientation(Component.VERTICAL);
directionLayout.setPadding(32, 32, 32, 32);

 Add a Text component to the layout to display the prompt information and the read time. The code is as follows:

Text text= new Text(this);
text.setText("初始文本"); //设置初始显示文本
text.setTextSize(50);
DirectionalLayout.LayoutConfig layoutConfig = newDirectionalLayout.LayoutConfig (ComponentContainer.LayoutConfig.MATCH_CONTENT,ComponentContainer.LayoutConfig.MATCH_CONTENT);
layoutConfig.alignment = LayoutAlignment.HORIZONTAL_CENTER;
text.setLayoutConfig(layoutConfig);
directionLayout.addComponent(text);

 In this example, the two devices implement time reading and writing through their respective Button components. Therefore, two Button components need to be added. First, add the Button component that writes the time. The code is as follows:

//实现写入功能的Button,用来读取当前时间,并写入分布式文档中
Button button1 = new Button(this);
layoutConfig.setMargins(0, 50,0,0);
button1.setLayoutConfig(layoutConfig);
button1.setText("写入现在时间");
button1.setTextSize(50);
ShapeElement background1 = new ShapeElement();
background1.setRgbColor(new RgbColor(0xFF51A8DD));
background1.setCornerRadius(25);
button1.setBackground(background1);
button1.setPadding(10, 10, 10, 10);
button1.setClickedListener(new Component.ClickedListener() {
      @Override
      public void onClick(Component Component) {
           goWrite(text); //单击Button,实现写入功能
      }
});
directionLayout.addComponent(button1);

 Add a Button component to read the time, the code is as follows:

//实现读取功能的Button,从分布式文档中读取已经写入的时间
Button button2 = new Button(this);
layoutConfig.setMargins(0, 50,0,0);
button2.setLayoutConfig(layoutConfig);
button2.setText("读取上一个时间");
button2.setTextSize(50);
ShapeElement background2 = new ShapeElement();
background2.setRgbColor(new RgbColor(0xFF5100DD));
background2.setCornerRadius(25);
button2.setBackground(background1);
button2.setPadding(10, 10, 10, 10);
button2.setClickedListener(new Component.ClickedListener() {
      @Override
//单击Button,实现读取功能
      public void onClick(Component Component) {
           goRead(text);
      }
});
directionLayout.addComponent(button2);

 The write function is implemented by the goWrite() method, and the implementation process is analyzed. The code is as follows:

//goWrite():写入button1的onClick事件执行的方法
private void goWrite(Text text) {
     String sharedFileName = sharedFileName(this); //获取分布式文件路径
     SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
     String str=simpleDateFormat.format(new Date().getTime()); //获取时间戳并转换成标准形式

//将时间写入分布式文件
     try{
          FileWriter fileWriter = new FileWriter(sharedFileName,false);
          fileWriter.write(str);
          fileWriter.close();
     } catch (IOException e) {
            e.printStackTrace();
     }
     text.setText("写入的时间:"+str); text.invalidate();
}

 The read function is implemented by the goRead() method, and the implementation process code is as follows:

//goRead():读取button2的onClick事件执行的方法
private void goRead(Text text) {
     String sharedFileName = sharedFileName(this); //获取分布式文件路径

  //读取分布式文件中的数据,若读到则输出,若没读到则输出没读到
     try{
            FileReader fileReader = new FileReader(sharedFileName);
            BufferedReader br = new BufferedReader(fileReader);
            String b = br.readLine();
            text.setText("读取到的上一个写入的时间:"+b);
            text.invalidate();
            fileReader.close();
        } catch (IOException e) {
            e.printStackTrace();
            text.setText("没读到");
            text.invalidate();
        }
}

 Both of them obtain the distributed file path through the shareFileName() method. The code is as follows:

File distDir = context.getDistributedDir(); //获取分布式文件目录
     //在分布式文件目录下新建一个名为note.txt的文件,读写都在这个文件中进行
     String filePath = distDir+File.separator+"note.txt";
     return filePath; //返回新建文件的路径
}

It should be noted that you can use the Context.getDistributedDir() interface to obtain your own distributed directory, and then through the libc or JDK interface, you can create, delete, read and write files or directories in this directory. In this example, a read-write file note.txt is created in the obtained distributed directory.

The verification is based on two mobile devices. Before starting the functional verification, the two mobile phones need to log in to the same Huawei account, and need to enable the multi-device collaboration permission and enable the multi-device collaborative connection. For the specific setting process, please refer to the previous introduction to the multi-device collaboration permission setting.

After the setup is complete, perform functional verification. First, read directly without writing, the reading result is shown in Figure 2, and the reading content is empty without writing.

■ Figure 2 Read directly without writing 

The current time is written by Phone A, and the current time is read by Phone B. The read and write effects are shown in Figure 3.

 ■ Figure 3 Phone A writes the current time, and Phone B reads the time written by A

When the current time is written by Phone B and read by Phone A, the read and write effects are shown in Figure 4.

■ Figure 4 Phone B writes the current time, and Phone A reads the time written by B

So far, the distributed file service function has been successfully implemented.

 

Guess you like

Origin blog.csdn.net/qq_41640218/article/details/127004330