lambda是amazon提供的无需管理服务器,可持续扩展,并且按量计费的函数即服务工具即Faas,目前支持 .NET, Go, Java, Nodejs, Python, Ruby语言

sqs(amazon simple queue service)是amazon提供的一种完全托管的消息队列服务,类似于rabbitmq, kafka

目前需要通过lambda(消息生产者)->sqs(消息队列)->lambda(消息消费者) 来保证数据的可靠性

在此我们使用golang来发送消息到sqs,实现代码如下

package main

import (
    "fmt"
    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/aws/credentials"
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/sqs"
)

func main() {
    SendToAwsSqs()
    //SendToAwsSns()
}

// 发送消息到sqs
func SendToAwsSqs() {
    // 区域
    region := "cn-northwest-1"

    // Initial credentials loaded from SDK's default credential chain. Such as
    // the environment, shared credentials (~/.aws/credentials), or EC2 Instance
    // Role. These credentials will be used to to make the STS Assume Role API.
    sess := session.Must(session.NewSession())

    // Create a SNS client with additional configuration
    // 方式一: 使用文件证书位置默认为~/.aws/credentials
    //svc := sns.New(sess, aws.NewConfig().WithRegion(region))
    // 方式二: 使用传参方式
    creds := credentials.NewStaticCredentials(
        "YourKeyId",
        "YourKeySecret",
        "",
    )
    svc := sqs.New(sess, &aws.Config{Credentials: creds, Region:  aws.String(region)})

    // sqs消息队列url
    qURL := "YourSqsUrl"
    result, err := svc.SendMessage(&sqs.SendMessageInput{
        DelaySeconds: aws.Int64(10),
        MessageAttributes: map[string]*sqs.MessageAttributeValue{
            "Title": &sqs.MessageAttributeValue{
                DataType:    aws.String("String"),
                StringValue: aws.String("The Fidding"),
            },
            "Author": &sqs.MessageAttributeValue{
                DataType:    aws.String("String"),
                StringValue: aws.String("Fidding"),
            },
            "WeeksOn": &sqs.MessageAttributeValue{
                DataType:    aws.String("Number"),
                StringValue: aws.String("6"),
            },
        },
        MessageBody: aws.String("FIdding Hello World."),
        QueueUrl:    &qURL,
    })

    if err != nil {
        fmt.Println("Error", err)
        return
    }

    fmt.Println("Success", *result.MessageId)
}

执行后打印的结果为一串uuid

Success {
  MD5OfMessageAttributes: "xxxxxx355ceb7658bcc4ac0xxxxxx",
  MD5OfMessageBody: "xxxxxdb8be7251f5c91090xxxxxxx",
  MessageId: "xxxxx-d81c-4499-b033-6b5axxxxxx"
}

说明消息已经成功发送到队列中了

其他文章

golang使用aws lambda发送消息到sns

happy coding!