Java SDK connection example

Updated at:
Copy as MD

This topic describes how to connect a Java Message Service (JMS) client that uses the AMQP protocol to Alibaba Cloud IoT Platform to receive server-side subscription messages.

Prerequisites

You have obtained a consumer group ID and subscribed to the required topic messages.

Prepare the development environment

The following development environment is used in this example:

Download the Apache Qpid JMS client

For more information about how to use Qpid JMS, see Qpid JMS 0.57.0.

In this example, you can add the following dependencies to your Maven project to download the Qpid JMS client.

<!-- AMQP 1.0 Qpid client -->
 <dependency>
   <groupId>org.apache.qpid</groupId>
   <artifactId>qpid-jms-client</artifactId>
   <version>0.57.0</version>
 </dependency>
 <!-- Utility for Base64-->
 <dependency>
   <groupId>commons-codec</groupId>
  <artifactId>commons-codec</artifactId>
  <version>1.10</version>
</dependency>

Example

Assume that Company A and Company B have Alibaba Cloud accounts A and B, respectively. Company A uses its account to configure a server-side subscription in IoT Platform.

  • For Alibaba Cloud account A or a Resource Access Management (RAM) user that is granted permissions directly by the account

    Note

    For a directly authorized RAM user, you must grant the user the permission to use the AMQP server-side subscription feature (iot:sub). Otherwise, the connection fails. For more information about how to grant permissions, see RAM authorization for IoT Platform.

    To improve data security, we recommend that you grant specific operation permissions to RAM users using RAM roles. For more information, see the following section.

    To develop an AMQP client that receives server-side subscription messages, see Receive server-side subscription messages using your account.

  • For a RAM user that is granted permissions using a RAM role

    The RAM user can belong to either Alibaba Cloud account A or Alibaba Cloud account B. This allows a RAM user from the same account (Alibaba Cloud account A) or a different account (Alibaba Cloud account B) to develop an AMQP client that connects to the IoT Platform instance of account A to receive server-side subscription messages.

    To develop an AMQP client that receives server-side subscription messages, see Receive server-side subscription messages as a RAM user authorized by a RAM role.

Receive server-side subscription messages using your account

  1. Download the demo code package and decompress it.

  2. Open IntelliJ IDEA and import the amqp-demo sample project from the demo package.

    The pom.xml file already contains the required Maven dependencies for the Qpid JMS client.

  3. In the AmqpClient.java file in the src/main/java/com.aliyun.iotx.demo directory, you can modify the AMQP connection parameters as described in the following table.

    Important
    • Ensure that you enter the correct parameter values. Otherwise, the AMQP client fails to connect.

    • The sample code in this demo includes code that terminates the program (Thread.sleep(60 * 1000);). The program runs for one minute and then stops. In a production environment, you can set the runtime as needed.

    For more information about the parameters, see AMQP client connection guide.

    Parameter

    Description

    accessKey

    The AccessKey ID and AccessKey secret of the Alibaba Cloud account or the RAM user.

    Log on to the IoT Platform console. Move the pointer over your profile picture and click AccessKey Management to obtain the AccessKey ID and AccessKey secret.

    accessSecret

    consumerGroupId

    The ID of the consumer group in the IoT Platform instance.

    Log on to the IoT Platform console. In the corresponding instance, go to Message Forwarding > Server-side Subscription > Consumer Group List to view your consumer group ID.

    iotInstanceId

    The instance ID. You can view the ID of the current instance on the Instance Overview page in the IoT Platform console.

    • If an ID exists, you must enter it.

    • If the Instance Overview page or the ID does not exist, leave this parameter empty. For example, iotInstanceId = "".

    clientId

    The client ID. You must define this ID. The ID can be up to 64 characters in length. We recommend that you use a unique identifier, such as the UUID, MAC address, or IP address of the server where your AMQP client is located.

    After the AMQP client is connected and starts, log on to the IoT Platform console. On the Consumer Groups tab of the Message Forwarding > > > Server-side Subscription page for the instance, click View next to the consumer group. The Consumer Group Details page displays this parameter. This helps you identify different clients.

    connectionCount

    The number of connections for the AMQP client. The maximum value is 128. This parameter is used to scale out real-time message pushes.

    On the Consumer Group Details page, connected clients are displayed in the ${clientId}+"-"+number format. The minimum value for number is 0.

    host

    The AMQP endpoint.

    For information about the AMQP endpoint that corresponds to ${YourHost}, see View and configure instance endpoints.

  4. Run the AmqpClient.java program.

    • Success: A log message similar to the following is returned. This indicates that the AMQP client is connected to IoT Platform and has received a message.

      topic = /***********/******/thing/event/property/post,
      message = 2**************7,
      content = {"temperature":29,"humidity":29,"time":1617357297270}

      Parameter

      Description

      topic

      The topic used to report device properties.

      messageId

      The message ID.

      content

      The message content.

    • Failure: The AMQP client fails to connect to IoT Platform if an issue exists with the code or the network environment.

      Check your code or network environment based on the log message. Then, fix the issue and run the code again.

Receive server-side subscription messages as a RAM user authorized by a RAM role

Prerequisites

The RAM user has been granted permissions by a RAM role to perform server-side subscription operations for the IoT Platform instance of Alibaba Cloud account A. For more information, see Grant permissions to a RAM user of the same account for server-side subscriptions and Grant permissions to a RAM user of a different account for server-side subscriptions.

Example

  1. Download the demo code package and decompress it.

  2. Open IntelliJ IDEA and import the amqp-sts-demo sample project from the demo package.

    The pom.xml file already contains the required Maven dependencies for the Qpid JMS client.

  3. In the src/main/java/com/aliyun/iotx/demo directory, open the AmqpStsTokenClient.java file and modify the AMQP connection information according to the following table.

    Important
    • Ensure that you enter the correct parameter values. Otherwise, the AMQP client fails to connect.

    • A Security Token Service (STS) token is valid for a maximum of one hour. You must periodically update the connection parameters for the AMQP client to ensure that it can reconnect. For more information about how to modify the parameters, see the scheduledExecutorService.scheduleAtFixedRate section in the sample code.

    • The sample code includes the Thread.sleep(6000 * 1000); line. This causes the program to terminate one minute after it starts. In a real-world scenario, you can set the runtime as needed.

    For more information about the parameters, see AMQP client connection guide.

    Parameter

    Description

    CONNECTION_COUNT

    The number of connections for the AMQP client. The maximum value is 128. This parameter is used to scale out real-time message pushes.

    On the Consumer Group Details page of the IoT Platform instance of the current account, connected clients are displayed in the "clientId-"+number format. The minimum value for number is 0.

    DURATION_SECONDS

    The validity period of the token for the connection. The value cannot exceed 1 hour. The value ranges from 15 to 60 minutes.

    STS_ENDPOINT

    The endpoint of the STS. For more information, see Endpoints.

    STS_ACCESS_KEY

    The AccessKey ID and AccessKey secret of the RAM user that assumes the RAM role of Alibaba Cloud account A.

    STS_ACCESS_SECRET

    STS_ROLE_ARN

    The Alibaba Cloud Resource Name (ARN) of the RAM role to assume under Alibaba Cloud account A. The format is acs:ram::<account-id>:role/<role-name>.

    The <role-name> part is the role name in lowercase. After you create the role, you can click the role name to view the ARN in the Basic Information section.

    CONSUMER_GROUP_ID

    The ID of the consumer group for the server-side subscription under Alibaba Cloud account A.

    You can view the consumer group ID on the Message Forwarding > Server-side Subscription > Consumer Group List tab for the instance in the IoT Platform console.

    IOT_INSTANCE_ID

    The ID of the IoT Platform instance under Alibaba Cloud account A.

    You can view the instance ID on the Instance Overview tab in the IoT Platform console.

    • If an ID exists, you must enter it.

    • If the Instance Overview tab or the ID does not exist, leave this parameter empty. For example, IOT_INSTANCE_ID = "".

    HOST

    The AMQP endpoint of the IoT Platform instance under Alibaba Cloud account A. For more information, see View and configure instance endpoints.

  4. Run the AmqpStsTokenClient.java program.

    • Success: A log message similar to the following is returned. This indicates that the AMQP client is connected to IoT Platform and has received a message.

      topic = /***********/******/thing/event/property/post,
      message = 2**************7,
      content = {"temperature":29,"humidity":29,"time":1617357297270}

      Parameter

      Description

      topic

      The topic used to report device properties.

      messageId

      The message ID.

      content

      The message content.

    • Failure: The AMQP client fails to connect to IoT Platform if an issue exists with the code or the network environment.

      Check your code or network environment based on the log message. Then, fix the issue and run the code again.

References

For more information about error codes for server-side subscription messages, see Message-related error codes.