0
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?

Lambda->SQS->Lambdaをした。
SDK for JavaScript (v3)で構築。Web上にはv2の情報など多くあったので、探すのに時間かかったん。。
これしてたら半日終わった...orz

やりたかったこと

Lambda1から大量のキューを発行してLambda2がキューを受け取って順序関係なく処理をする。

前提

  • Lambdaが使える
  • SQSキューが作成されている
  • Lambdaに実行ロール,アクセス権限が設定されている(SQSとか..)

実際のコード

LambdaからSQSMessageを発行

SQSMessage発行する側
import { SendMessageCommand, SQSClient } from "@aws-sdk/client-sqs";
 
// SQSキューを作成すると発行されるよ
const SQSQueueUrl = "https://sqs.ap-northeast-1.amazonaws.com/0000222224444/xxxxxxxxxx";

const region = 'ap-northeast-1'
const sqsClient = new SQSClient({
  region,
});

export const handler = async (event) => {
  const queueMessage = JSON.stringify({foo: "bar"})
  const sendedSQSOutput = await sqsClient.send(
    new SendMessageCommand({
      QueueUrl: SQSQueueUrl,
      // DelaySeconds: 3,
      // やり方2通り?
      MessageAttributes: {
        foo: {
          DataType: "String",
          StringValue: "bar",
        },
      },
      MessageBody: queueMessage,
    })  
  )

  return {
    statusCode: 200,
    body: "成功",
  };
}

MessageAttributesMessageBodyの両方に値を乗っけられる
LambdaSQSのアクセス権をつけないとエラーになるよ

受け取り側Lambda

受け取り側のコード
 export const handler = async (event) => {
 
   // レスポンス
  console.log(event.Records[0]);
  
  const response = {
    statusCode: 200,
    body: "成功",
  };
  return response;
};

レスポンスevent.Records[0]の中身

event.Records[0]
{
  messageId: '06c893f9-xxxx-47f6-xxxx-01c0e29c4ab5',
  receiptHandle: 'xxxxxxx',
  body: '{"foo":"bar"}',
  attributes: {
    ApproximateReceiveCount: '1',
    AWSTraceHeader: 'Root=1-xxxxxxx-xxx;Parent=xx;Sampled=0;Lineage=xxx:0',
    SentTimestamp: '1707641273576',
    SenderId: 'xxxx:xxxxxxx',
    ApproximateFirstReceiveTimestamp: '1707641273584'
  },
  messageAttributes: {
    foo: {
      stringValue: 'bar',
      stringListValues: [],
      binaryListValues: [],
      dataType: 'String'
    }
  },
  md5OfMessageAttributes: 'xxxxxxxxxxxxxxxxx',
  md5OfBody: 'xxxxxxxxxxxxxxxxx',
  eventSource: 'aws:sqs',
  eventSourceARN: 'arn:aws:sqs:ap-northeast-1:xxxxxxxx:xxxxxxxxxxx',
  awsRegion: 'ap-northeast-1'
}

さいごに

今回初めてSQSを使用した
間違い等あればコメント下さい!(=^x^=)

リソース

https://docs.aws.amazon.com/ja_jp/lambda/latest/dg/with-sqs.html
https://docs.aws.amazon.com/ja_jp/sdk-for-javascript/v3/developer-guide/javascript_sqs_code_examples.html

0
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
0
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?