producer.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. package services
  2. import (
  3. "context"
  4. "encoding/json"
  5. "io"
  6. "log"
  7. "math/rand"
  8. "time"
  9. "github.com/aws/aws-sdk-go-v2/aws"
  10. "github.com/aws/aws-sdk-go-v2/service/sqs"
  11. "github.com/aws/aws-sdk-go-v2/service/sqs/types"
  12. "github.com/fgm/izidic"
  13. )
  14. func ProducerService(dic *izidic.Container) (any, error) {
  15. cli := dic.MustService("sqs").(*sqs.Client)
  16. w := dic.MustParam(PWriter).(io.Writer)
  17. return func(ctx context.Context, qName string) {
  18. senderHandler(ctx, w, cli, qName)
  19. }, nil
  20. }
  21. func senderHandler(ctx context.Context, _ io.Writer, client *sqs.Client, qURL string) {
  22. pinger := time.NewTicker(2 * time.Second)
  23. for range pinger.C {
  24. sendOne(ctx, client, qURL)
  25. }
  26. }
  27. func sendOne(ctx context.Context, client *sqs.Client, qURL string) {
  28. data := map[string]int{"a": rand.Int()}
  29. data["b"] = data["a"] + 1
  30. bs, _ := json.Marshal(data)
  31. body := string(bs)
  32. ma := map[string]types.MessageAttributeValue{
  33. "x": {
  34. DataType: aws.String("String"),
  35. StringValue: aws.String("a string value"),
  36. },
  37. "y": {
  38. DataType: aws.String("Number"),
  39. StringValue: aws.String("42"),
  40. },
  41. "retry": {
  42. DataType: aws.String("String"),
  43. StringValue: aws.String("1"),
  44. },
  45. }
  46. smr := sqs.SendMessageInput{
  47. MessageBody: &body,
  48. QueueUrl: &qURL,
  49. DelaySeconds: 0,
  50. MessageAttributes: ma,
  51. MessageDeduplicationId: nil,
  52. MessageGroupId: nil,
  53. MessageSystemAttributes: nil,
  54. }
  55. smo, err := client.SendMessage(ctx, &smr)
  56. if err != nil {
  57. log.Printf("failed producing message: %v", err)
  58. } else if smo.MessageId == nil {
  59. log.Println("message produced with a nil ID")
  60. } else {
  61. log.Printf("message %s produced with %#v", *smo.MessageId, data)
  62. }
  63. }