All Products
Search
Document Center

IoT Platform:Example of server-side modifications for instance migration

Last Updated:Jun 16, 2026

After an instance migration, you must redirect cloud API calls for related services to the target Enterprise Edition instance. To do this, develop methods to update the device instance ID in your database and pass the updated Enterprise Edition instance ID when calling cloud APIs to control device services. This example uses a Java development environment.

Background information

For more information about instance migration, see Must-reads before you start.

To subscribe to instance migration data, see Configure data forwarding rules.

Development environment

The development environment requires:

Example code description

Feature

Description

Update device data

Parses instance migration messages subscribed from a public instance through the rules engine. It then processes data forwarding messages for successfully migrated devices and updates the instance ID in the database based on the device information.

Control device services

Modifies the API call method for device control services. When calling a cloud API, query the Enterprise Edition instance ID from the database table, set the IotInstanceId request parameter to this instance ID, and then call the API.

Example code for updating device data

The method for updating device data depends on the SDK for AMQP client access. For an AMQP client access example, see Java SDK access example.

To update the method that processes instance migration messages, replace the processMessage method with the following code. The updateDeviceInstanceId(productKey, deviceName, targetInstanceId) and recoverDeviceInstanceId(productKey, deviceName) methods update data in the database. You must develop these methods as needed.

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 instance ID of the successfully migrated device.
            String targetInstanceId = object.getString("targetInstance");

            // Process the successfully migrated devices and update their instance IDs to the target Enterprise instance ID.
            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 instance ID of the successfully migrated device in the database based on the productKey, deviceName, and target.
                    // updateDeviceInstanceId(productKey, deviceName, targetInstanceId)


                }
            }

            // Process the successfully rolled-back devices and restore their original instance IDs.
            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 instanceId in the database based on the productKey and deviceName. The recovery policy depends on the business scenario.
                    // 1. If the original business that called the public instance did not store an instance ID, restore the instance ID to null.
                    // 2. If the original business that called the public instance stored a specific instance ID value, restore the instance ID to its original default value.
                    // recoverDeviceInstanceId(productKey, deviceName)
                }
            }
        } catch (Exception e) {
            logger.error("processMessage occurs error ", e);
        }
    }

Example code for controlling device services

The method for calling device-related business APIs depends on the IoT Platform cloud SDK. For more information, see Java SDK usage notes.

The following code uses the Pub API as an example and adds the pub(client, productKey, deviceName) API call method. You must implement the getInstanceId(productKey, deviceName) method based on your requirements.

  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 not empty, pass the parameter to set the instance ID. Note that only Enterprise instances require this parameter. Public instances do not.
        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 and organize information from the database based on the productKey and deviceName.
        // instanceId = query(productKey, deviceName);

        return instanceId;
    }