インスタンスからgo用のAWS SDK でSQSに届くメッセージを取得したい。
先にgo getしておきましょう。
go get github.com/aws/aws-sdk-go/...
package main
import (
"flag"
"fmt"
"log"
"os"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/sqs"
)
//
// GetMessage will get messages in SQS queue.
//
func GetMessage() {
params := &sqs.ReceiveMessageInput{
QueueUrl: aws.String(queueUrl),
// Number of messages are got in one time.
MaxNumberOfMessages: aws.Int64(10),
// If there are no messages, keeping connection in 20 sec.
WaitTimeSeconds: aws.Int64(20),
}
// Get messages by using aws sdk
resp, err := svc.ReceiveMessage(params)
log.Printf("messages count: %d", len(resp.Messages))
if len(resp.Messages) == 0 {
fmt.Println("empty queue.")
} else {
// If message(s) are found, filtering them and delete them.
for _, m := range resp.Messages {
//
// note:
// svc.ReceiveMessage will return many same messages( their number of defined by MaxNumberOfMessages),
// so deleting target all messages. ( I don't sure why ReceiveMessage do so... )
//
fmt.Printf("Found target message:\n%s\n", m.GoString())
if err := DeleteMessage(m); err != nil {
fmt.Println(err)
}
}
}
return
}
// DeleteMessage is deleting target message.
func DeleteMessage(msg *sqs.Message) error {
params := &sqs.DeleteMessageInput{
QueueUrl: aws.String(queueUrl),
ReceiptHandle: aws.String(*msg.ReceiptHandle),
}
_, err := svc.DeleteMessage(params)
if err != nil {
fmt.Println(err)
return err
}
return nil
}
func main() {
targetRegion = "ap-northeast-1"
queueUrl = "https://sqs.ap-northeast-1.amazonaws.com/XXXXXXXXXXXXXXX/TestQue"
sess, err := session.NewSession(&aws.Config{
Region: aws.String(targetRegion)},
)
if err != nil {
log.Println(err)
panic(1)
}
// to create session
svc = sqs.New(sess)
// to get messages
GetMessage()
}
ReciveMessageでなぜか同じメッセージが沢山入ってくる なんでだろう。ドキュメント読んでもそれらしきことは書いてないのだが、、、使い方間違ってるのかな。