当前位置:网站首页>Using cloud DB to build app quick start -server

Using cloud DB to build app quick start -server

2022-06-11 15:47:00 Gauss squirrel Club

Java

Cloud DB Provide a variety of cloud database data management methods , You can go to AppGallery Connect Console management data , You can also directly manage the data in the cloud side database on the server . You only need to integrate the cloud database service in the server-side service Server SDK, You can call the interface it provides , Complete the development of relevant service functions .Server SDK It will guarantee the communication and communication security between your server and cloud database .

Use Server SDK Management data , The following preparations need to be completed :

  • You are already in AppGallery Connect Open Cloud database on the console , And successfully created the object type .
  • You've got the sample code , Please from Sample code obtain .

Configure the development environment

  1. Add authentication credentials , For details, see Project level credentials .
  2. add to Server SDK To application level build.gradle file .

    stay < Project name >/app/build.gradle In file dependencies Partially add Server SDK.

    dependencies {
        //  add to Cloud DB SDK
        implementation 'com.huawei.agconnect.server:agconnect-database-server-sdk:1.0.3.300'
    }
  3. At the application level build.gradle Set in file Java The source code compatibility mode is JDK1.8 edition .
    compileOptions {
        sourceCompatibility = 1.8
        targetCompatibility = 1.8
    }

Add object type file

When you are developing local applications , You can directly put AppGallery Connect Exported from the console java Add the format file to the local development environment , There is no need to create the object type again .

  1. Export for Server End-to-end service development java Format object type file , Please see the Export object type .
  2. All that will be exported java Add the format file to the local development environment , If it already exists , Please overwrite the original file . file location :<database>/src/main/java/com/huawei/agc/clouddb/quickstart/model.

initialization

After adding the object type file , You can start developing Server End services . Developing Server Before the end of the service , You need to initialize the corresponding data processing location AGCClient, And create Cloud DB zone Instance and CloudDBZoneConfig object , Set the name of the cloud side storage area for data operations .

  1. take Configure the development environment The authentication credentials obtained in are placed in your customized directory , And pass ClientNameEnum Specify the corresponding data processing location , call getClientName Method to get the initialized AGCClient example .
    String credentialPath = "agc-apiclient.json";
    AGCClient.initialize(ClientNameEnum.CLOUDDB_CN.getClientName(), AGCParameter.builder()
    .setCredential(CredentialParser.toCredential(credentialPath))
    .build(), Constants.Region.REGION_CN);
    AGCClient The corresponding relationship of initialization parameters is shown in the following table .

    ClientNameEnum

    Constants.Region

    CLOUDDB_CN

    REGION_CN

    CLOUDDB_RU

    REGION_RU

    CLOUDDB_SG

    REGION_SG

    CLOUDDB_DE

    REGION_DE

  2. adopt getInstance(AGCClient agcClient) Method to obtain the corresponding data processing location AGConnectCloudDB example .
    AGCClient agcClient = AGCClient.getInstance(CLOUDDB_CN.getClientName());
    agConnectCloudDB = AGConnectCloudDB.getInstance(agcClient);
  3. establish CloudDBZoneConfig Configuration object , And set the cloud side Cloud DB zone name , open Cloud DB zone example , Please refer to CloudDBZoneConfig.
    CloudDBZoneConfig cloudDBZoneConfig = new CloudDBZoneConfig("QuickStartDemo");
    mCloudDBZone = agConnectCloudDB.openCloudDBZone(cloudDBZoneConfig);

Write data

This section mainly introduces how to Server Perform data writing operations in the end service , So that you know how to use Server SDK Realize data writing . Use executeUpsert() Method to write data .BookInfo For defined object types , See also Add and export object types .

public void upsertBookInfo(BookInfo bookInfo) {
    if (mCloudDBZone == null) {
        LOGGER.warn("CloudDBClient is null, try re-initialize it");
        return;
    }
    try {
        CompletableFuture<Integer> result = mCloudDBZone.executeUpsert(bookInfo);
        System.out.println(result.get());
    } catch (AGConnectCloudDBException | ExecutionException | InterruptedException e) {
        LOGGER.warn("upsertBookInfo: " + e.getMessage());
    }
}

View the data

adopt executeQuery() and get() Method to query data asynchronously .

public void queryBooks(CloudDBZoneQuery<BookInfo> query) {
    if (mCloudDBZone == null) {
        LOGGER.warn("CloudDBClient is null, try re-initialize it");
        return;
    }
    try {
        CompletableFuture<CloudDBZoneSnapshot<BookInfo>> result = mCloudDBZone.executeQuery(query);
        CloudDBZoneSnapshot<BookInfo> snapshot = result.get();
        processQueryResult(snapshot);
    } catch (AGConnectCloudDBException | InterruptedException | ExecutionException e) {
        LOGGER.warn("queryBooks: " + e.getMessage());
    }
}

Through query and orderByDesc() Methods and limit() Method combination to realize the descending sorting of data , And limit the number of query data displays .

private void queryWithOrder() {
    CloudDBZoneQuery<BookInfo> query = CloudDBZoneQuery.where(BookInfo.class);
    try {
        query.orderByDesc("price");
        query.limit(10);
        CompletableFuture<CloudDBZoneSnapshot<BookInfo>> result = mCloudDBZone.executeQuery(query);
        processQueryResult(result.get());
    } catch (AGConnectCloudDBException | InterruptedException | ExecutionException e) {
        LOGGER.warn("queryWithOrder: " + e.getMessage());
    }
}

JavaScript

Cloud DB Provide a variety of cloud database data management methods , You can go to AppGallery Connect Console management data , You can also directly manage the data in the cloud side database on the server . You only need to integrate the cloud database service in the server-side service Server SDK, You can call the interface it provides , Complete the development of relevant service functions .Server SDK It will guarantee the communication and communication security between your server and cloud database .

Use Server SDK Management data , The following preparations need to be completed :

  • You are already in AppGallery Connect Open Cloud database on the console , And successfully created the object type .
  • You've got the sample code , Please from Sample code obtain .

Configure the development environment

  1. Add authentication credentials , For details, see Project level credentials .
  2. Execute the following command , install Server SDK Into your project , And add dependencies to your project package.json In file .
    npm install --save @agconnect/database-server
  3. Import... In your project AGC modular .
    const clouddb = require('@agconnect/database-server/dist/index.js');
    const agconnect = require('@agconnect/common-server');

Add object type file

When you are developing local applications , You can directly put AppGallery Connect Exported from the console js Add the format file to the local development environment , There is no need to create the object type again .

  1. Export for Server End-to-end service development js Format object type file , Please see the Export object type .
  2. All that will be exported js Add the format file to the local development environment , If it already exists , Please overwrite the original file . file location :<database>/src/model.

initialization

After adding the object type file , You can start developing Server End services . Developing Server Before the end of the service , You need to initialize AGCClient, And set the name of the cloud side storage area for data operation , Get store instance .

  1. take Configure the development environment The authentication credentials obtained in are placed in your customized directory , And initialization AGCClient example .
    const credentialPath = "resource\\agc-apiclient-xxxx.json";
    agconnect.AGCClient.initialize(agconnect.CredentialParser.toCredential(credentialPath));
    const agcClient = agconnect.AGCClient.getInstance();
  2. adopt getInstance() Method initialization AGConnectCloudDB example .
    clouddb.AGConnectCloudDB.initialize(agcClient);
  3. establish CloudDBZoneConfig Configuration object , And set the cloud side Cloud DB zone name , open Cloud DB zone example , Please refer to CloudDBZoneConfig.
    const zoneName = 'QuickStartDemo';
    const cloudDBZoneConfig = new clouddb.CloudDBZoneConfig(zoneName);
    const mCloudDBZone = clouddb.AGConnectCloudDB.getInstance().openCloudDBZone(cloudDBZoneConfig);

Write data

This section mainly introduces how to Server Perform data writing operations in the end service , So that you know how to use Server SDK Realize data writing . Use executeUpsert() Method to write data .BookInfo For defined object types , See also Add and export object types .

async upsertBookInfos(bookInfo) {
    if (!this.mCloudDBZone) {
        console.log("CloudDBClient is null, try re-initialize it");
        return;
    }
    try {
        const resp = await this.mCloudDBZone.executeUpsert(bookInfo);
    } catch (error) {
        console.warn('upsertBookInfo=>', error)
    }
}

View the data

adopt executeQuery() Query data .

async queryBooks(cloudDBZoneQuery) {
    if (!this.mCloudDBZone) {
        console.log("CloudDBClient is null, try re-initialize it");
        return;
    }
    try {
        const resp = await this.mCloudDBZone.executeQuery(cloudDBZoneQuery);
        this.processQueryResult(resp.getSnapshotObjects());
    } catch (error) {
        console.warn('queryBooks=>', error)
    }
}

Through query and orderByDesc() Methods and limit() Method combination to realize the descending sorting of data , And limit the number of query data displays .

async queryBooksWithOrder() {
    if (!this.mCloudDBZone) {
        console.log("CloudDBClient is null, try re-initialize it");
        return;
    }
    try {
        const cloudDBZoneQuery = clouddb.CloudDBZoneQuery.where(BookInfo).orderByDesc("price").limit(3);
        const resp = await this.mCloudDBZone.executeQuery(cloudDBZoneQuery);
        this.processQueryResult(resp.getSnapshotObjects());
    } catch (error) {
        console.warn('queryBooks=>', error)
    }
}
原网站

版权声明
本文为[Gauss squirrel Club]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/162/202206111535104736.html