All Products
Search
Document Center

IoT Platform:Contoh modifikasi sisi server untuk migrasi instans

Last Updated:Jun 17, 2026

Setelah migrasi instans, Anda harus mengalihkan panggilan API cloud untuk layanan terkait ke instans Edisi Perusahaan target. Untuk melakukannya, kembangkan metode guna memperbarui ID instans perangkat di database dan sertakan ID instans Edisi Perusahaan yang telah diperbarui saat memanggil API cloud untuk mengontrol layanan perangkat. Contoh ini menggunakan lingkungan pengembangan Java.

Informasi latar belakang

Untuk informasi selengkapnya mengenai migrasi instans, lihat Hal-hal yang wajib dibaca sebelum memulai.

Untuk berlangganan data migrasi instans, lihat Konfigurasikan aturan penerusan data.

Lingkungan pengembangan

Lingkungan pengembangan memerlukan:

Deskripsi kode contoh

Fitur

Deskripsi

Perbarui data perangkat

Mengurai pesan migrasi instans yang telah dilanggan dari instans publik melalui mesin aturan. Kemudian memproses pesan penerusan data untuk perangkat yang berhasil dimigrasikan dan memperbarui ID instans di database berdasarkan informasi perangkat tersebut.

Kontrol layanan perangkat

Memodifikasi metode pemanggilan API untuk layanan kontrol perangkat. Saat memanggil API cloud, kueri ID instans Edisi Perusahaan dari tabel database, atur parameter permintaan IotInstanceId ke ID instans tersebut, lalu panggil API-nya.

Kode contoh untuk memperbarui data perangkat

Metode untuk memperbarui data perangkat bergantung pada SDK untuk akses client AMQP. Untuk contoh akses client AMQP, lihat Contoh akses SDK Java.

Untuk memperbarui metode yang memproses pesan migrasi instans, ganti metode processMessage dengan kode berikut. Metode updateDeviceInstanceId(productKey, deviceName, targetInstanceId) dan recoverDeviceInstanceId(productKey, deviceName) memperbarui data di database. Anda harus mengembangkan metode ini sesuai kebutuhan.

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);
        }
    }

Kode contoh untuk mengontrol layanan perangkat

Metode untuk memanggil API bisnis terkait perangkat bergantung pada SDK cloud IoT Platform. Untuk informasi selengkapnya, lihat Catatan penggunaan SDK Java.

Kode berikut menggunakan API Pub sebagai contoh dan menambahkan metode pemanggilan API pub(client, productKey, deviceName). Anda harus mengimplementasikan metode getInstanceId(productKey, deviceName) sesuai kebutuhan Anda.

  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;
    }