5
6

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 5 years have passed since last update.

ローカルテスト用にaws-sdkでElasticMQに接続するNode.jsサンプル

Posted at

SQS = require('aws-sdk').SQS

# クライアントを生成
client = new SQS
  accessKeyId: 'アクセスキーIDを記述...'  # ElasticMQの場合は不使用
  secretAccessKey: 'シークレットアクセスキーを記述...'  # ElasticMQの場合は不使用
  apiVersion: '2012-11-05'
  region: 'リージョンを記述...'  # ElasticMQの場合は不使用

# キュー名
queueName = 'キュー名を記述...'

# ローカル開発環境用(ElasticMQ)
queueUrl = "http://localhost:9324/queue/#{queueName}"
# 本番環境用(AWS SQS)
# queueUrl = "https://sqs.リージョン.amazonaws.com/xxxxxxxxxx/#{queueName}"

# ElasticMQ用にコレを設定する必要がある
client.setEndpoint 'http://localhost:9324'

# キューを作成
client.createQueue {QueueName: queueName}, (err) ->

  if err
    console.log "### エラー", err
    return

  # 送信用パラメータ
  sendParams =
    QueueUrl: queueUrl
    MessageBody: 'This is a test'
    DelaySeconds: 0

  # メッセージ送信
  client.sendMessage sendParams, (err) ->
    if err
      console.log "### エラー", err
      return

    # 受信用オプション
    recvOptions =
      QueueUrl: queueUrl
      MaxNumberOfMessages: 10
      VisibilityTimeout: 60
      WaitTimeSeconds: 20

    # メッセージ受信
    client.receiveMessage recvOptions, (err, data) ->
      if err
        console.log "### エラー", err
        return

      # メッセージがあれば
      if data?.Messages?.length > 0

        # メッセージ件数分処理
        for message, i in data.Messages
          console.log "### メッセージ[#{i}]", message.Body

          # 削除用パラメータ
          delOptions =
            QueueUrl: queueUrl
            ReceiptHandle: message.ReceiptHandle

          # メッセージ削除(ElasticMQは必要ない??)
          client.deleteMessage delOptions, (err, data) ->
            if err
               console.log "### エラー", err
               return


5
6
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
5
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?