All Products
Search
Document Center

Simple Message Queue (formerly MNS):SDK for Go

Last Updated:Sep 02, 2024

This topic describes the versions and usage notes of the SDK for Go. This topic also provides sample code.

Version 1.0.3

  • Release date

    2024-05-31

    SDK download

  • New features

    • You are allowed to set the transport attribute of the HTTP client.

    • The version number and operating system information are added to the client information.

    • A new method of initializing a client is provided. You can obtain the configuration information from environment variables.

Version 1.0.2

  • Release date

    2021-03-05

    SDK download

  • New features

    The OpenService operation is provided.

Version 1.0.1

  • Release date

    2021-01-15

    SDK download

  • New features

    • The timeout settings are supported.

    • Request IDs are provided in responses.

Version 1.0.0

  • Release date

    2019-04-30

    SDK download

  • New features

    • The following queue management operations are supported:

      • Create, modify, query, and delete queues.

      • Send, view, receive, and delete messages, and change the value of the NextVisibleTime parameter.

    • The following topic management operations are supported:

      • Create, modify, and delete topics.

      • Create and delete subscriptions.

      • Send messages.

Usage notes

  1. After you download the SDK for Go of the latest version, decompress the package and go to the aliyun-mns-go-sdk-master directory.

  2. Open the app.conf.example file and configure the url, access_key_id, and access_key_secret parameters.

  3. Go to the sample directory in which all sample code is stored.

Sample code

Queue-based messaging model

The following sample code provides an example on how to create a queue, send messages, receive messages, delete messages, and delete a queue.

package main

import (
    "encoding/json"
    "fmt"
    "io/ioutil"
    "log"
    "net/http"
    _ "net/http/pprof"
    "time"

    "github.com/gogap/logs"
    "github.com/aliyun/aliyun-mns-go-sdk"
)

type appConf struct {
    Url             string `json:"url"`
    AccessKeyId     string `json:"access_key_id"`
    AccessKeySecret string `json:"access_key_secret"`
}

func main() {
    go func() {
        log.Println(http.ListenAndServe("localhost:8080", nil))
    }()

    conf := appConf{}

    if bFile, e := ioutil.ReadFile("app.conf.example"); e != nil {
        panic(e)
    } else {
        if e := json.Unmarshal(bFile, &conf); e != nil {
            panic(e)
        }
    }

    client := ali_mns.NewAliMNSClient(conf.Url,
        conf.AccessKeyId,
        conf.AccessKeySecret)
    queueManager := ali_mns.NewMNSQueueManager(client)
    // Create a queue named test. 
    err := queueManager.CreateQueue("test", 0, 65536, 345600, 30, 0, 3)

    time.Sleep(time.Duration(2) * time.Second)

    if err != nil && !ali_mns.ERR_MNS_QUEUE_ALREADY_EXIST_AND_HAVE_SAME_ATTR.IsEqual(err) {
        fmt.Println(err)
        return
    }
    msg := ali_mns.MessageSendRequest{
        MessageBody:  "hello <\"aliyun-mns-go-sdk\">",
        DelaySeconds: 0,
        Priority:     8}
    queue := ali_mns.NewMNSQueue("test", client)
    // Send messages. 
    for i := 1; i < 10000; i++ {
        ret, err := queue.SendMessage(msg)

        go func() {
            fmt.Println(queue.QPSMonitor().QPS())
        }()

        if err != nil {
            fmt.Println(err)
        } else {
            logs.Pretty("response:", ret)
        }

        endChan := make(chan int)
        respChan := make(chan ali_mns.MessageReceiveResponse)
        errChan := make(chan error)
        go func() {
            select {
            case resp := <-respChan:
                {
                    logs.Pretty("response:", resp)
                    logs.Debug("change the visibility: ", resp.ReceiptHandle)
                    if ret, e := queue.ChangeMessageVisibility(resp.ReceiptHandle, 5); e != nil {
                        fmt.Println(e)
                    } else {
                        logs.Pretty("visibility changed", ret)
                        logs.Debug("delete it now: ", ret.ReceiptHandle)
                        if e := queue.DeleteMessage(ret.ReceiptHandle); e != nil {
                            fmt.Println(e)
                        }
                        endChan <- 1
                    }
                }
            case err := <-errChan:
                {
                    fmt.Println(err)
                    endChan <- 1
                }
            }
        }()
        // Receive messages. 
        queue.ReceiveMessage(respChan, errChan, 30)
        <-endChan
    }
}

Topic-based messaging model

The following sample code provides an example on how to create a queue, create a topic, subscribe to a topic, and publish messages.

package main

import (
    "encoding/json"
    "fmt"
    "io/ioutil"
    "time"

    "github.com/gogap/logs"
    "github.com/aliyun/aliyun-mns-go-sdk"
)

type appConf struct {
    Url             string `json:"url"`
    AccessKeyId     string `json:"access_key_id"`
    AccessKeySecret string `json:"access_key_secret"`
}

func main() {
    conf := appConf{}

    if bFile, e := ioutil.ReadFile("app.conf.example"); e != nil {
        panic(e)
    } else {
        if e := json.Unmarshal(bFile, &conf); e != nil {
            panic(e)
        }
    }

    client := ali_mns.NewAliMNSClient(conf.Url,
        conf.AccessKeyId,
        conf.AccessKeySecret)

    // Create a queue named testQueue. 
    queueManager := ali_mns.NewMNSQueueManager(client)
    err := queueManager.CreateSimpleQueue("testQueue")
    if err != nil && !ali_mns.ERR_MNS_QUEUE_ALREADY_EXIST_AND_HAVE_SAME_ATTR.IsEqual(err) {
        fmt.Println(err)
        return
    }

    // Create a topic named testTopic. 
    topicManager := ali_mns.NewMNSTopicManager(client)
    // topicManager.DeleteTopic("testTopic")
    err = topicManager.CreateSimpleTopic("testTopic")
    if err != nil && !ali_mns.ERR_MNS_TOPIC_ALREADY_EXIST_AND_HAVE_SAME_ATTR.IsEqual(err) {
        fmt.Println(err)
        return
    }

    // Subscribe to a topic. In this example, the endpoint parameter is set to the queue name, which is testQueue. 
    topic := ali_mns.NewMNSTopic("testTopic", client)
    sub := ali_mns.MessageSubsribeRequest{
        Endpoint: topic.GenerateQueueEndpoint("testQueue"),
        NotifyContentFormat: ali_mns.SIMPLIFIED,
    }

    // topic.Unsubscribe("SubscriptionNameA")
    err = topic.Subscribe("SubscriptionNameA", sub)
    if err != nil && !ali_mns.ERR_MNS_SUBSCRIPTION_ALREADY_EXIST_AND_HAVE_SAME_ATTR.IsEqual(err) {
        fmt.Println(err)
        return
    }

    time.Sleep(time.Duration(2) * time.Second)

    // Publish messages to a topic. 
    msg := ali_mns.MessagePublishRequest{
        MessageBody: "hello topic <\"aliyun-mns-go-sdk\">",
    }
    _, err = topic.PublishMessage(msg)
    if err != nil {
        fmt.Println(err)
        return
    }

    // Receive messages from a queue. 
    queue := ali_mns.NewMNSQueue("testQueue", client)

    endChan := make(chan int)
    respChan := make(chan ali_mns.MessageReceiveResponse)
    errChan := make(chan error)
    go func() {
        select {
        case resp := <-respChan:
            {
                logs.Pretty("response:", resp)
                fmt.Println("change the visibility: ", resp.ReceiptHandle)
                if ret, e := queue.ChangeMessageVisibility(resp.ReceiptHandle, 5); e != nil {
                    fmt.Println(e)
                } else {
                    logs.Pretty("visibility changed", ret)
                    fmt.Println("delete it now: ", ret.ReceiptHandle)
                    if e := queue.DeleteMessage(ret.ReceiptHandle); e != nil {
                        fmt.Println(e)
                    }
                    endChan <- 1
                }
            }
        case err := <-errChan:
            {
                fmt.Println(err)
                endChan <- 1
            }
        }
    }()

    queue.ReceiveMessage(respChan, errChan, 30)
    <-endChan
}