This article describes how to connect a Go client to IoT Platform over Advanced Message Queuing Protocol (AMQP) and enable the client to receive messages from IoT Platform.

Development environment

Go 1.12.7 is used in this example.

Download the SDK for Go

You can run the following command to import AMQP SDK for Go:

import "pack.ag/amqp"

For more information about how to use the SDK, see package amqp.

Sample code

For more information about the parameters in the following sample code, see Connect an AMQP client to IoT Platform.

package main

import (
    "context"
    "crypto/hmac"
    "crypto/sha1"
    "encoding/base64"
    "fmt"
    "pack.ag/amqp"
    "time"
)
//For more information about the parameters, see the "Connect an AMQP client to IoT Platform" topic.
const accessKey = "${YourAccessKey}"
const accessSecret = "${YourAccessSecret}"
const consumerGroupId = "${YourConsumerGroupId}"
const clientId = "${YourClientId}"
//iotInstanceId: If you use an Enterprise Edition instance, you must specify the instance ID. If you use a public instance, you can enter an empty string ("").
const iotInstanceId = "${YourIotInstanceId}"
//The endpoint. For more information, see the "Connect an AMQP client to IoT Platform" topic.
const host = "${YourHost}"

func main() {
    address := "amqps://"
     + host + ":5671"
    timestamp := time.Now().Nanosecond() / 1000000
    //The structure of the userName parameter. For more information, see the "Connect an AMQP client to IoT Platform" topic.
    userName := fmt.Sprintf("%s|authMode=aksign,signMethod=Hmacsha1,consumerGroupId=%s,authId=%s,iotInstanceId=%s,timestamp=%d|", 
        clientId, consumerGroupId, accessKey, iotInstanceId, timestamp)
    stringToSign := fmt.Sprintf("authId=%s&timestamp=%d", accessKey, timestamp)
    hmacKey := hmac.New(sha1.New, []byte(accessSecret))
    hmacKey.Write([]byte(stringToSign))
    //Calculate a signature. For more information about how to specify the password parameter, see the "Connect an AMQP client to IoT Platform" topic.
    password := base64.StdEncoding.EncodeToString(hmacKey.Sum(nil))

    amqpManager := &AmqpManager{
        address:address,
        userName:userName,
        password:password,
    }

    //If you need to enable or disable the message receiving feature, you can create a context by using the Background() function.
    ctx := context.Background()

    amqpManager.startReceiveMessage(ctx)
}

//The function that implements your business logic. The function is a user-defined function that is asynchronously implemented. Before you configure this function, we recommend that you consider the consumption of system resources.
func (am *AmqpManager) processMessage(message *amqp.Message) {
    fmt.Println("data received:", string(message.GetData()), " properties:", message.ApplicationProperties)
}

type AmqpManager struct {
    address     string
    userName     string
    password     string
    client       *amqp.Client
    session     *amqp.Session
    receiver     *amqp.Receiver
}

func (am *AmqpManager) startReceiveMessage(ctx context.Context)  {

    childCtx, _ := context.WithCancel(ctx)
    err := am.generateReceiverWithRetry(childCtx)
    if nil != err {
        return
    }
    defer func() {
        am.receiver.Close(childCtx)
        am.session.Close(childCtx)
        am.client.Close()
    }()

    for {
        //Block message receiving. If ctx is the new context that is created based on the Background() function, message receiving is not blocked.
        message, err := am.receiver.Receive(ctx)

        if nil == err {
            go am.processMessage(message)
            message.Accept()
        } else {
            fmt.Println("amqp receive data error:", err)

            //If message receiving is manually disabled, exit the program.
            select {
            case <- childCtx.Done(): return
            default:
    
            }

            //If message receiving is not manually disabled, retry the connection.
            err := am.generateReceiverWithRetry(childCtx)
            if nil != err {
                return
            }
        }
    }
}

func (am *AmqpManager) generateReceiverWithRetry(ctx context.Context) error {
    //Retry with exponential backoff, from 10 ms to 20s.
    duration := 10 * time.Millisecond
    maxDuration := 20000 * time.Millisecond
    times := 1

    //If exceptions occur, retry with exponential backoff.
    for {
        select {
        case <- ctx.Done(): return amqp.ErrConnClosed
        default:
    
        }

        err := am.generateReceiver()
        if nil != err {
            time.Sleep(duration)
            if duration < maxDuration {
                duration *= 2
            }
            fmt.Println("amqp connect retry,times:", times, ",duration:", duration)
            times ++
        } else {
            fmt.Println("amqp connect init success")
            return nil
        }
    }
}

//The statuses of the connection and session cannot be determined because the packets are unavailable. Retry the connection to obtain the information.
func (am *AmqpManager) generateReceiver() error {

    if am.session != nil {
        receiver, err := am.session.NewReceiver(
            amqp.LinkSourceAddress("/queue-name"),
            amqp.LinkCredit(20),
        )
        //If a network disconnection error occurs, the connection is ended and the session fails to be created. Otherwise, the connection is established.
        if err == nil {
            am.receiver = receiver
            return nil
        }
    }

    //Delete the previous connection.
    if am.client != nil {
        am.client.Close()
    }

    client, err := amqp.Dial(am.address, amqp.ConnSASLPlain(am.userName, am.password), )
    if err != nil {
        return err
    }
    am.client = client

    session, err := client.NewSession()
    if err != nil {
        return err
    }
    am.session = session

    receiver, err := am.session.NewReceiver(
        amqp.LinkSourceAddress("/queue-name"),
        amqp.LinkCredit(20),
    )
    if err != nil {
        return err
    }
    am.receiver = receiver

    return nil
}
    
Parameter Example Description
accessKey LTAI4GFGQvKuqHJhFa****** Log on to the IoT Platform console, move the pointer over the profile picture, and then click AccessKey Management to obtain the AccessKey ID and AccessKey secret.
Note If you use a RAM user, you must attach the AliyunIOTFullAccess permission policy to the user. This policy allows the user to manage IoT Platform resources. Otherwise, the connection with IoT Platform fails. For more information about how to authorize a RAM user, see RAM user access.
accessSecret iMS8ZhCDdfJbCMeA005sieKe******
consumerGroupId VWhGZ2QnP7kxWpeSSjt****** The consumer group ID.

Log on to the IoT Platform console. Choose Rules > Server-side Subscription > Consumer Groups and view the ID of the required consumer group.

iotInstanceId "" The ID of the instance. Enter an empty string ("").
clientId 12345 The client ID. You must use a unique identifier, such as the UUID, MAC address, or IP address of the client. The client ID must be 1 to 64 characters in length.

Log on to the IoT Platform console. Choose Rules > Server-side Subscription > Consumer Groups, and click View next to the required consumer group. The Consumer Group Details shows the parameter. This parameter allows you to identify clients.

host 233***.iot-amqp.cn-shanghai.aliyuncs.com The AMQP endpoint.

${YourHost} format: ${uid}.iot-amqp.${YourRegionId}.aliyuncs.com.

  • ${uid}: Replace this variable with the ID of your Alibaba Cloud account. You can log on to the IoT Platform console, and move the pointer over the profile picture to view the account ID.
  • ${YourRegionId}: Replace this variable with the ID of the region where your IoT Platform device resides. For more information about region IDs, see Regions and zones.

Sample results

  • Sample success result: After you run the code, the following log data may be returned. The data indicates that the AMQP client is connected to IoT Platform and can receive messages.Success
  • Sample failure result: Failure