1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

AWS SNS/SQSによるメッセージ送受信のサンプル(Go言語)

Posted at

前準備

  1. SNSのトピックを作る
  • 名前は適当
  • タイプは標準
  • 他はすべてデフォルト値でOK。
  1. SQSのキューを作る。名前は適当、他は
  • 名前は適当
  • タイプは標準
  • 他はすべてデフォルト値でOK。
  1. SQSを作ったら、そのSNSサブスクリプションに最初に作ったSNSを追加する

SNSでメッセージを送信

package main

import (
	"flag"
	"fmt"
	"github.com/aws/aws-sdk-go/aws/session"
	"github.com/aws/aws-sdk-go/service/sns"
	"os"
)

func main() {
	profile := flag.String("p", "", "AWSの認証に使うProfile。未指定ならdefault")
	msgPtr := flag.String("m", "", "The message to send to the subscribed users of the topic")
	topicPtr := flag.String("t", "", "The ARN of the topic to which the user subscribes")

	flag.Parse()

	// Initialize a session that the SDK will use to load
	// credentials from the shared credentials file. (~/.aws/credentials).
	sess := session.Must(session.NewSessionWithOptions(session.Options{
		SharedConfigState: session.SharedConfigEnable,
		Profile:           *profile,
	}))

	svc := sns.New(sess)

	result, err := svc.Publish(&sns.PublishInput{
		Message:  msgPtr,
		TopicArn: topicPtr,
	})
	if err != nil {
		fmt.Println(err.Error())
		os.Exit(1)
	}

	fmt.Println(*result.MessageId)
}

SQSでメッセージを受信

package main

import (
	"flag"
	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/aws/session"
	"github.com/aws/aws-sdk-go/service/sqs"
	"os/signal"
	"syscall"

	"fmt"
	"os"
)

func main() {
	profile := flag.String("p", "", "AWSの認証に使うProfile。未指定ならdefault")
	queue := flag.String("q", "", "The name of the queue")
	flag.Parse()

	if *queue == "" {
		fmt.Println("You must supply the name of a queue (-q QUEUE)")
		return
	}

	// Initialize a session that the SDK will use to load
	// credentials from the shared credentials file. (~/.aws/credentials).
	sess := session.Must(session.NewSessionWithOptions(session.Options{
		SharedConfigState: session.SharedConfigEnable,
		Profile:           *profile,
	}))

	svc := sqs.New(sess)

	urlResult, err := svc.GetQueueUrl(&sqs.GetQueueUrlInput{
		QueueName: queue,
	})
	if err != nil {
		fmt.Println(err.Error())
		os.Exit(1)
	}

	go func() {
		queueURL := urlResult.QueueUrl
		timeout := int64(20)

		for {
			msgResult, err := svc.ReceiveMessage(&sqs.ReceiveMessageInput{
				AttributeNames: []*string{
					aws.String(sqs.MessageSystemAttributeNameSentTimestamp),
					aws.String(sqs.MessageSystemAttributeNameSenderId),
				},
				MessageAttributeNames: []*string{
					aws.String(sqs.QueueAttributeNameAll),
				},
				QueueUrl:            queueURL,
				MaxNumberOfMessages: aws.Int64(1),
				VisibilityTimeout:   &timeout,
				WaitTimeSeconds: &timeout, // ロングポーリング
			})

			if err != nil {
				fmt.Println(err.Error())
				os.Exit(1)
			}

			for _, message := range msgResult.Messages {
				fmt.Println(message)
				// 一度受け取ったメッセージはキューから削除。そうしないと何回も受信してしまう
				_, _ = svc.DeleteMessage(&sqs.DeleteMessageInput{
					QueueUrl:      queueURL,
					ReceiptHandle: message.ReceiptHandle,
				})
			}
		}
	}()

	sig := make(chan os.Signal, 1)
	signal.Notify(sig, syscall.SIGTERM, syscall.SIGINT)
	s := <-sig

	fmt.Printf("Signal received: %s \n", s.String())
}
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?