简体   繁体   English

如何在我现有的 nodejs 服务器上使用 sqs 消息

[英]How can i consume sqs messages at my existing nodejs server

I want to receive and trigger email when new message receive at SQS, Now I already have nodejs server running, How can I make it work?我想在 SQS 收到新消息时接收并触发 email,现在我已经运行了 nodejs 服务器,我该如何让它工作? I dont really want to trigger that function.我真的不想触发 function。 But I want that when there's new message in SQS this consumer will consume and do the business logic of sending email.但我希望当 SQS 中有新消息时,该消费者将消费并执行发送 email 的业务逻辑。

But I am not getting any trigger at my function.但我的 function 没有得到任何触发。 Note: I am not calling this function, I want that it automatically trigger when new message is available at SQS.注意:我没有调用这个 function,我希望它在 SQS 有新消息时自动触发。

const AWS = require('aws-sdk');
const mongoose = require('mongoose');

//
// Configure the aws details
//
AWS.config.update({
    region: process.env['AWS_REGION'],
    accessKeyId: process.env['AWS_ACCESS_KEY_ID'],
    secretAccessKey: process.env['AWS_SECRET_ACCESS_KEY']
  });


const sqs = new AWS.SQS({apiVersion: '2012-11-05'});

var queueURL = "https://sqs.us-east-1.amazonaws.com/xxxxx/demo-lambda-to-email-sqs"



var params = {
    AttributeNames: [
        "SentTimestamp"
     ],
    MaxNumberOfMessages: 1,
    MessageAttributeNames: [
       "All"
    ],
    QueueUrl: queueURL,
    VisibilityTimeout: 20,
    WaitTimeSeconds: 0
   };

   sqs.receiveMessage(params, function(err, data) {
    if (err) {
      console.log("Receive Error", err);
    } else if (data.Messages) {
      console.log('--------------------------- MESSAGE RECEIVED -------------')
      var deleteParams = {
        QueueUrl: queueURL,
        ReceiptHandle: data.Messages[0].ReceiptHandle
      };
      sqs.deleteMessage(deleteParams, function(err, data) {
        if (err) {
          console.log("Delete Error", err);
        } else {
          console.log("Message Deleted", data);
        }
      });
    }
  });

SQS is a queuing service, for this reason it needs to be consumed via a pull based mechanism not a push based. SQS 是一种排队服务,因此需要通过基于拉的机制而不是基于推的机制来使用它。

This function can only be invoked if you have functionality that will poll the SQS queue, then trigger the function when a message comes in.这个 function 只能在您具有轮询 SQS 队列的功能时调用,然后在消息进入时触发 function。

If you do not want to maintain a consumer script, you should look at migrating this script into a Lambda function.如果您不想维护使用者脚本,则应考虑将此脚本迁移到 Lambda function 中。 When this option is used the Lambda Service will act as the consumer of the queue and trigger the Lambda function only when a message is added.使用此选项时,Lambda 服务将充当队列的消费者,并仅在添加消息时触发 Lambda function。

More information about Using AWS Lambda with SQS Queues is available in the documentation.文档中提供了有关将 AWS Lambda 与 SQS 队列结合使用的更多信息。

You are only call it once without using long polling.您只需调用一次而不使用长轮询。 So it starts and its gets an empty response.所以它开始了,它得到一个空的响应。 So you need a pull based mechanism, a basic implementation could run receiveMessage inside a SetInterval.所以你需要一个基于拉的机制,一个基本的实现可以在 SetInterval 中运行 receiveMessage。 Something like:就像是:

setInterval(function() {
    sqs.receiveMessage(params, function(err, data){
      // your logic here!
    });
}, 10000);
// Run every 10s

WaitTimeSeconds greater than 1s enables long polling and helps reduce the cost of using Amazon SQS by eliminating the number of empty responses.大于 1 秒的 WaitTimeSeconds 支持长轮询,并通过消除空响应的数量来帮助降低使用 Amazon SQS 的成本。

The following code calls SQS every 30 seconds asking for messages.以下代码每 30 秒调用一次 SQS 请求消息。 Every call waits up to 20 seconds to receive messages.每个呼叫最多等待 20 秒以接收消息。

const AWS = require('aws-sdk')
AWS.config.update({
    region: 'us-east-1',
    accessKeyId: '...',
    secretAccessKey: '...'
})
const sqs = new AWS.SQS()

receiveMessage = () => sqs.receiveMessage({
    QueueUrl: 'https://sqs.us-east-1.amazonaws.com/.../...',
    WaitTimeSeconds: 20
}, (error, data) => {
    if (error) console.error("ERROR:", error)
    if (data.Messages) data.Messages.forEach(m => console.info(m.Body))
})

setInterval(receiveMessage, 30000)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何让我的 NodeJS 应用程序在服务器上运行? - How can I get my NodeJS application working on a server? 如何在 Nodejs 中使用来自 sse 服务器的数据? - How to consume data from a sse server in Nodejs? 运行Node.js(在Windows R2服务器上):如何减少艰苦的任务消耗的RAM数量? - Running Node.js (on Windows R2 server): How can I reduce the amount of RAM that my grunt tasks consume? 我如何从我的nodejs服务器上的js文件加载我的js函数? - how can i load my js function from js file on my nodejs server? 如何在不严重修改现有应用程序的情况下在服务器上呈现我的反应组件? - How Can I render my react components on the server without heavily modifying my existing app? 当我想查看更改时,如何在不重新启动nodejs的情况下编辑我的服务器文件? - How can I edit on my server files without restarting nodejs when i want to see the changes? 我怎么能说我的 Discord 机器人对直接消息没有反应,只在服务器聊天频道中? - How can I say my Discord bot doesn't react to direct messages, only in a server chat channel? 如何向现有的node.js服务器添加SSL证书? - How can I add an SSL certificate to my already existing node.js server? 如何将现有的Angular 2应用程序链接到Nodejs Server? - How to link an existing Angular 2 app to Nodejs Server? Rshiny:如何调用我的 JS 身份验证 function 以便 Rshiny 应用程序可以使用结果? - Rshiny: How can I call my JS authentication function such that the Rshiny app can consume the result?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM