All Products
Search
Document Center

IoT Platform:Example on how to configure a server that is related to instance migration

Last Updated:Aug 18, 2023

After you migrate the data of a source public instance to a destination Enterprise Edition instance, all IoT Platform API operations that are related to your business must be performed on the destination Enterprise Edition instance. In this case, you must develop a function that is used to update the ID of the instance to which the devices in a database belong. You must also develop a function that is used to specify the Enterprise Edition instance ID for a device when you call IoT Platform API operations to manage the services of the device. This topic describes how to configure a server in business system in which you want to perform instance migration. In this example, a Java development environment is used.

Background information

For information about instance migration, see Usage notes.

For more information about how to subscribe to instance migration messages, see Configure a data forwarding rule.

Development environment

The following components are used in the Java development environment:

Sample code

Operation

Description

Update device data

Parse instance migration messages to which the source public instance subscribes by using the rules engine. Parse the data forwarding message of migrated devices and update the ID of the instance to which the device in the database belongs.

Manage device services

Configure a request parameter for an API operation that you want to call to manage device services. When you call the API operation, you must query the ID of the instance to which the device whose services you want to manage in a table of the database belongs. Then, specify the ID for the IotInstanceId request parameter of the API operation.

Sample code for updating device data

You must develop a function to update device data based on the SDK that is used to connect an Advanced Message Queuing Protocol (AMQP) client to IoT Platform. For more information about how connect an AMQP client, see Connect a client to IoT Platform by using the SDK for Java.

Replace the definition of the processMessage function that is called to process instance migration messages with the following code. In the code, the updateDeviceInstanceId(productKey, deviceName, targetInstanceId) and recoverDeviceInstanceId(productKey, deviceName) functions are called to update the data of the database. You must configure the functions based on your business scenario.

private static void processMessage(Message message) {
        try {
            byte[] body = message.getBody(byte[].class);
            String content = new String(body);
            String topic = message.getStringProperty("topic");
            String messageId = message.getStringProperty("messageId");
            logger.info("receive message"
                + ",\n topic = " + topic
                + ",\n messageId = " + messageId
                + ",\n content = " + content);

            if (null == content) {
                logger.error("content is null");
            }

            JSONObject object = JSON.parseObject(content);
            String status = object.getString("status");

            // Update the ID of the instance to which the migrated devices belong. 
            String targetInstanceId = object.getString("targetInstance");

            // Replace the ID of the instance to which the migrated devices belong with the ID of the destination Enterprise Edition. 
            if (StringUtils.equals(status, "GRAY_EXECUTING") || StringUtils.equals(status, "ALL_EXECUTING")) {
                JSONArray successDevices = object.getJSONArray("successDevices");

                if (successDevices == null) {
                    return;
                }

                for (int i = 0; i < successDevices.size(); i++) {
                    JSONObject device = successDevices.getJSONObject(i);
                    if (null == device) {
                        return;
                    }

                    String deviceName = device.getString("deviceName");
                    String productKey = device.getString("productKey");

                    // todo: Update the ID of the instance to which the migrated devices in the database belong based on the specified ProductKey, DeviceNames, and destination instance ID. 
                    // updateDeviceInstanceId(productKey, deviceName, targetInstanceId)


                }
            }

            // Restore the ID of the instance to which the devices that are rolled back belong to the ID of the original instance. 
            if (StringUtils.equals("status", "ROLL_BACK_EXECUTING")) {
                JSONArray successDevices = object.getJSONArray("successDevices");
                if (successDevices == null) {
                    return;
                }

                for (int i = 0; i < successDevices.size(); i++) {
                    JSONObject device = successDevices.getJSONObject(i);
                    if (null == device) {
                        return;
                    }

                    String deviceName = device.getString("deviceName");
                    String productKey = device.getString("productKey");

                    // todo: Restore the ID of the instance in the database based on the specified ProductKey and DeviceNames. You must configure a restoration policy based on your business scenario. 
                    // 1. If you do not specify an ID for API calls that are related to the source public instance, the system sets the instance ID to null. 
                    // 2. If you specify an ID for API calls that are related to the source public instance, the system sets the instance ID to the original default value. 
                    // recoverDeviceInstanceId(productKey, deviceName)
                }
            }
        } catch (Exception e) {
            logger.error("processMessage occurs error ", e);
        }
    }

Sample code for managing device services

You must develop a function to call device-related API operations based on IoT Platform SDK for Java. For more information about how to use IoT Platform SDK for Java, see Use IoT Platform SDK for Java,

Develop a function to call the required API operations. In this example, the Pub API operation is called. The following code defines the pub(client, productKey, deviceName) function. In the code, the getInstanceId(productKey, deviceName) function is called to implement business logic. You must develop the function based on your business scenario.

  public static void main(String[] args) {
        String accessKey = "${accessKey}";
        String accessSecret = "${accessSecret}";
        String productKey = "${productKey}";
        String deviceName = "${deviceName}";
        IClientProfile profile = DefaultProfile.getProfile("cn-shanghai", accessKey, accessSecret);
        DefaultAcsClient client = new DefaultAcsClient(profile);

        pub(client, productKey, deviceName);
    }

    private static void pub(DefaultAcsClient client, String productKey, String deviceName) {
        PubRequest request = new PubRequest();
        // Obtain the instance ID from the database. 
        String instanceId = getInstanceId(productKey, deviceName);

        // If the instance ID is obtained, you must specify the instance ID for the instanceId parameter. If you use an Enterprise Edition instance, you must configure this parameter. If you use a public instance, you do not need to configure this parameter. 
        if (!StringUtils.isEmpty(instanceId)) {
            request.setIotInstanceId(instanceId);
        }

        request.setProductKey("${productKey}");
        request.setMessageContent(Base64.encodeBase64String("hello world".getBytes()));
        request.setTopicFullName("/${productKey}/${deviceName}/user/get");
        request.setQos(0); // QoS 0 and QoS 1 are supported. 
        try {
            PubResponse response = client.getAcsResponse(request);
            System.out.println(response.getSuccess());
            System.out.println(response.getCode());
            System.out.println(response.getErrorMessage());
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            System.out.println("ErrCode:" + e.getErrCode());
            System.out.println("ErrMsg:" + e.getErrMsg());
            e.printStackTrace();
        }
    }

    /**
     * Obtain the instance ID from the database. 
     *
     * @param productKey
     * @param deviceName
     * @return
     */
    private static String getInstanceId(String productKey, String deviceName) {
        String instanceId = "";
        // todo: Query data in the database by using the specified ProductKey and DeviceName. 
        // instanceId = query(productKey, deviceName);

        return instanceId;
    }