Created
August 29, 2019 09:17
-
-
Save RafPe/4e6849cd9a54bc0ce3a9cc0d8c2c7d41 to your computer and use it in GitHub Desktop.
SQS Polling with golang channels
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"github.com/aws/aws-sdk-go/aws" | |
"github.com/aws/aws-sdk-go/aws/session" | |
"github.com/aws/aws-sdk-go/service/sqs" | |
"fmt" | |
) | |
var ( | |
sqsSvc *sqs.SQS | |
) | |
func pollMessages(chn chan<- *sqs.Message) { | |
for { | |
output, err := sqsSvc.ReceiveMessage(&sqs.ReceiveMessageInput{ | |
QueueUrl: aws.String("https://sqs.eu-central-1.amazonaws.com/123456/rafpe"), | |
MaxNumberOfMessages: aws.Int64(2), | |
WaitTimeSeconds: aws.Int64(15), | |
}) | |
if err != nil { | |
fmt.Println("failed to fetch sqs message %v", err) | |
} | |
for _, message := range output.Messages { | |
chn <- message | |
} | |
} | |
} | |
func handleMessage(msg *sqs.Message) { | |
fmt.Println("RECEIVING MESSAGE >>> ") | |
fmt.Println(*msg.Body) | |
} | |
func deleteMessage(msg *sqs.Message) { | |
sqsSvc.DeleteMessage(&sqs.DeleteMessageInput{ | |
QueueUrl: aws.String("https://sqs.eu-central-1.amazonaws.com/123456/rafpe"), | |
ReceiptHandle: msg.ReceiptHandle, | |
}) | |
} | |
func main() { | |
// 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{Config: aws.Config{Region: aws.String("eu-central-1")}, Profile: "xyz"})) | |
sqsSvc = sqs.New(sess) | |
chnMessages := make(chan *sqs.Message, 2) | |
go pollMessages(chnMessages) | |
for message := range chnMessages { | |
handleMessage(message) | |
deleteMessage(message) | |
} | |
} |
thanks for this! you're an angel
The best example. Much better than the official Amazon examples. Thank you very much!
Happy could help 😊 sharing is caring
Very good, thanks for sharing with us!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This was super useful! Thank you @RafPe 👍