Todos los productos
Search
Centro de documentos

IoT Platform:Ejemplo de conexión con el SDK de Go

Última actualización: Sep 03, 2026

Este tema proporciona un ejemplo de un cliente Go que usa el protocolo AMQP para conectarse a Alibaba Cloud IoT Platform y recibir mensajes de una suscripción del lado del servidor.

Requisitos previos

Debe haber obtenido un ID de grupo de consumidores y haberse suscrito a los mensajes de topic obligatorios.

Preparar el entorno de desarrollo

Este ejemplo usa Go 1.12.7.

Descargar el SDK

Use el siguiente comando para importar el SDK de AMQP para Go.

import "pack.ag/amqp"

Para obtener más información sobre cómo usar el SDK, consulte package amqp.

Ejemplo de código

package main
import (
	"os"
    "context"
    "crypto/hmac"
    "crypto/sha1"
    "encoding/base64"
    "fmt"
    "pack.ag/amqp"
    "time"
)
// For parameter descriptions, see the AMQP client connection guide.
const consumerGroupId = "${YourConsumerGroupId}"
const clientId = "${YourClientId}"
// iotInstanceId: The instance ID.
const iotInstanceId = "${YourIotInstanceId}"
// The endpoint. For more information, see the AMQP client connection guide.
const host = "${YourHost}"
func main() {
	// If you leak the project code, your AccessKey may be exposed. This compromises the security of all resources in your account. 
	// The following code provides an example on how to use an environment variable to obtain the AccessKey. This method is for reference only.
	accessKey := os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")
	accessSecret := os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
    address := "amqps://" + host + ":5671"
    timestamp := time.Now().Nanosecond() / 1000000
    // For information about how to construct the user name, see the AMQP client connection guide.
    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 the signature. For information about how to construct the password, see the AMQP client connection guide.
    password := base64.StdEncoding.EncodeToString(hmacKey.Sum(nil))
    amqpManager := &AmqpManager{
        address:address,
        userName:userName,
        password:password,
    }
    // To accept messages or cancel operations, derive the context from context.Background().
    ctx := context.Background()
    amqpManager.startReceiveMessage(ctx)
}
// Business function. This is a custom implementation. The function is executed asynchronously. Consider the resource consumption of your system.
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 {
        // Blocks to receive messages. If the context is background, the process is not interrupted.
        message, err := am.receiver.Receive(ctx)
        if nil == err {
            go am.processMessage(message)
            message.Accept()
        } else {
            fmt.Println("amqp receive data error:", err)
            // If the operation is actively canceled, exit the program.
            select {
            case <- childCtx.Done(): return
            default:
            }
            // If the operation is not actively canceled, re-establish the connection.
            err := am.generateReceiverWithRetry(childCtx)
            if nil != err {
                return
            }
        }
    }
}
func (am *AmqpManager) generateReceiverWithRetry(ctx context.Context) error {
    // Back off and reconnect. Start with 10 ms and double the interval up to 20s.
    duration := 10 * time.Millisecond
    maxDuration := 20000 * time.Millisecond
    times := 1
    // In case of an exception, back off and reconnect.
    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 connection and session states cannot be determined because the package is not visible. Restart the connection to retrieve the states.
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 occurs, the connection closes and session creation fails. 
        // If the connection remains open, the session is created successfully.
        if err == nil {
            am.receiver = receiver
            return nil
        }
    }
    // Clean up 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
}

Configure los parámetros del código anterior como se describe en la siguiente tabla. Para obtener más información, consulte Connect an AMQP client to IoT Platform.

Importante

Especifique valores de parámetro válidos. De lo contrario, el cliente AMQP no podrá conectarse a IoT Platform.

Parámetro

Descripción

accessKey

Inicie sesión en la consola de IoT Platform, pase el mouse sobre su foto de perfil y haga clic en AccessKey Management para obtener el AccessKey ID y el AccessKey secret.

Nota

Si usa un usuario de Resource Access Management (RAM), otorgue al usuario de RAM el permiso AliyunIOTFullAccess. Este permiso es obligatorio para gestionar IoT Platform. Sin él, la conexión fallará. Para obtener información sobre cómo otorgar permisos, consulte RAM user access.

accessSecret

consumerGroupId

El ID del grupo de consumidores en la instancia de IoT Platform.

Inicie sesión en la consola de IoT Platform. En la instancia correspondiente, vaya a Message Forwarding > Server-side Subscription > Consumer Group List para consultar su ID de grupo de consumidores.

iotInstanceId

El ID de la instancia. Consulte el ID de la instancia actual en la página Instance Overview de la consola de IoT Platform.

  • Si existe un ID, introdúzcalo.

  • Si la página Instance Overview no existe o no hay ningún ID disponible, pase un valor vacío, por ejemplo iotInstanceId = "".

clientId

El ID del cliente. Debe definir este ID. La longitud máxima es de 64 caracteres. Se recomienda usar un identificador único, como el UUID, la dirección MAC o la dirección IP del servidor donde se encuentra su cliente AMQP.

Una vez que el cliente AMQP esté conectado e iniciado, inicie sesión en la consola de IoT Platform. En la pestaña Consumer Groups de la página Message Forwarding > > > Server-side Subscription de la instancia, haga clic en View junto al grupo de consumidores. La página Consumer Group Details muestra este parámetro. Esto le ayuda a identificar los diferentes clientes.

host

El endpoint de AMQP.

Para obtener información sobre el endpoint de AMQP correspondiente a ${YourHost}, consulte View and configure instance endpoints.

Resultados de ejecución de ejemplo

  • Correcto: Se devuelve un mensaje de registro similar al siguiente. Esto indica que el cliente AMQP se conectó correctamente a IoT Platform y recibió mensajes del dispositivo.

    amqp connect init success
    data received: {"deviceType":"CustomCategory","iotId":"xxx","requestId":"1613726251726","checkFailedData":0,"productKey":"xxx","gmtCreate":"1613726121717,"deviceName":"xxx","items":{"Temperature":{"value":24,"time":1613726121715},"Humidity":{"value":19,"time":1613726121715}}}  properties: map[generateTime:1613726121721 messageId:xxx xxx s:1 topic: /xxx/thing/event/property/post]
    data received: {"deviceType":"CustomCategory","iotId":"xxx","requestId":"1613725651726","checkFailedData":0,"productKey":"xxx","gmtCreate":"1613725521715,"deviceName":"xxx","items":{"Temperature":{"value":28,"time":1613725521712},"Humidity":{"value":19,"time":1613725521712}}}  properties: map[generateTime:1613725521719 messageId:1362689721104473600 qos:1 topic: /xxx/thing/event/property/post]
  • Con errores: Se devuelve un mensaje de registro similar al siguiente, lo que indica que el cliente AMQP no pudo conectarse a IoT Platform.

    Use el registro de errores para comprobar su código y la configuración de red. Resuelva el problema y ejecute el código nuevamente.

    amqp connect retry,times: 1 ,duration: 20ms
    amqp connect retry,times: 2 ,duration: 40ms
    amqp connect retry,times: 3 ,duration: 80ms
    amqp connect retry,times: 4 ,duration: 160ms
    amqp connect retry,times: 5 ,duration: 320ms
    amqp connect retry,times: 6 ,duration: 640ms
    amqp connect retry,times: 7 ,duration: 1.28s
    amqp connect retry,times: 8 ,duration: 2.56s
    amqp connect retry,times: 9 ,duration: 5.12s
    amqp connect retry,times: 10 ,duration: 10.24s
    amqp connect retry,times: 11 ,duration: 20.48s

Referencias

Para obtener más información sobre los códigos de error de los mensajes de suscripción del lado del servidor, consulte Message-related error codes.