简体   繁体   English

如何使用 nodejs 将消息发送到 RabbitMQ 队列

[英]How do I send messages to RabbitMQ Queue, using nodejs

I am currently building a load balancing tool to take different stress measurements of how servers handle http protocol requests.我目前正在构建一个负载平衡工具,以对服务器如何处理 http 协议请求进行不同的压力测量。 Currently, I can send just a ton, but I cannot process them all.目前,我只能发送一吨,但我无法处理它们。 That is why I am looking to put it all into a message queue like rabbit, using AMQP.这就是为什么我希望使用 AMQP 将其全部放入像兔子一样的消息队列中。

My current code https://github.com/yugely/Stork我当前的代码https://github.com/yugely/Stork

I am currently using an event loop and a timeout to adequately do what I am intending to accomplish.我目前正在使用事件循环和超时来充分完成我打算完成的工作。

I want to use RabbitMQ by using one of my current loggers to "emit" a message into the message queue.我想通过使用我当前的记录器之一来使用 RabbitMQ 将消息“发送”到消息队列中。 I don't know how to modularize it so I don't have to constantly create channels as all the tutorials seem to just copy paste each other without going into how to use it in external files.我不知道如何模块化它,所以我不必经常创建频道,因为所有教程似乎只是相互复制粘贴,而没有讨论如何在外部文件中使用它。

I'm hoping someone can either lead me to what I may be duping.我希望有人可以引导我做我可能被欺骗的事情。 I'm unsure of how to even ask this question.我什至不确定如何问这个问题。 I have been looking at RabbitMQ and AMQP to handle a message queue for a project.我一直在研究 RabbitMQ 和 AMQP 来处理项目的消息队列。 The issue I am facing is that I don't know how to send a message to rabbit mq.我面临的问题是我不知道如何向rabbit mq 发送消息。 Let me illustrate what I am understanding by doing a copypasta of the first tutorial on the rabbitmq site:让我通过在 rabbitmq 站点上复制第一个教程来说明我的理解:

send.js发送.js

var amqp = require('amqplib/callback_api');

amqp.connect('amqp://localhost', function(error0, connection) {
    if (error0) {
        throw error0;
    }
    connection.createChannel(function(error1, channel) {
        if (error1) {
            throw error1;
        }

        var queue = 'hello';
        var msg = 'Hello World!';

        channel.assertQueue(queue, {
            durable: false
        });
        /*
         How do I do this outside the functions so receive gets it? How can I call a method/function to send a message to an existing queue through an existing channel?
        */
        channel.sendToQueue(queue, Buffer.from(msg));

        console.log(" [x] Sent %s", msg);
    });
    setTimeout(function() {
        connection.close();
        process.exit(0);
    }, 500);
});

receive.js接收.js

var amqp = require('amqplib/callback_api');

amqp.connect('amqp://localhost', function(error0, connection) {
    if (error0) {
        throw error0;
    }
    connection.createChannel(function(error1, channel) {
        if (error1) {
            throw error1;
        }

        var queue = 'hello';

        channel.assertQueue(queue, {
            durable: false
        });

        console.log(" [*] Waiting for messages in %s. To exit press CTRL+C", queue);
        /*
    How do I set up a consumer outside this function? 
         */
        channel.consume(queue, function(msg) {
            console.log(" [x] Received %s", msg.content.toString());
        }, {
            noAck: true
        });
    });
});
  1. For the sender, do I just always create a new channel for every message?对于发件人,我是否总是为每条消息创建一个新频道?

  2. All the tutorials accept arguments when you run the "node" terminal command.当您运行“node”终端命令时,所有教程都接受参数。 The only way I can currently see this working is to use the "child process" library, but that would be bad news bears right?我目前看到这个工作的唯一方法是使用“子进程”库,但那将是坏消息,对吧? As wouldn't that create another nodejs cluster?那不会创建另一个nodejs集群吗?

  3. If I have to use a client to send messages, am I able to use axios?如果我必须使用客户端发送消息,我可以使用 axios 吗? (I've seen some people claiming they are able to but I don't know for sure). (我看到有些人声称他们能够做到,但我不确定)。 Since it will be using the amqp protocol, what is the amqp client?既然将使用 amqp 协议,那么 amqp 客户端是什么?

  4. Or are these queues like instantiated in the entry file?或者这些队列是否在入口文件中实例化? Like you set up the queue when you run your entry point command and then allow the different "events" to send messages to the queue?就像您在运行入口点命令时设置队列,然后允许不同的“事件”向队列发送消息一样?

How can I modularize this?我该如何模块化?

Just to illustrate, here is my current axios code只是为了说明,这是我当前的 axios 代码

RadioFlyer.js RadioFlyer.js

    await axios(flight.journal.actions[modkey]).then(function (response) {
        reaction.key.type = messageType.HTTPResponse.Okay
        reaction.message = response === undefined ?  response : "no response"
        let smaug = typeof reaction.message.status === "undefined" ?  reaction.message : reaction.message.status
        flight.journal.reactions.push(reaction)
        let pulse = {
            id: flight.id + "-" + index,
                timestamp: Date.now(),
            body: {
            payload: {
                protocol : reaction.protocol,
                    type: messageType.HTTPResponse.Okay,
                    url: flight.journal.actions[modkey].baseURL,
                    status: smaug
                }
            }
        }
       /*
        Can I emit a messaging event to my logger
        */
        //emit
        seidCar.HTTPLogger.emit("logHttp", reaction)
        //emit
        seidCar.HeartbeatLogger.emit("pulse", pulse)
    }).catch(function (error) {
      reaction.key.type = messageType.HTTPResponse.Error
      reaction.message = error.response === undefined ?  error.code : error.response

      let smaug = typeof reaction.message.status === "undefined" ?  reaction.message : reaction.message.status
      let pulse = {
            id: flight.id + "-" + index,
            timestamp: Date.now(),
            body: {
                payload: {
                    protocol : reaction.protocol,
                    type: messageType.HTTPResponse.Error,
                    url: flight.journal.actions[modkey].baseURL,
                    status: smaug
                }
            }
        }
      let err = {
          id: flight.id+"-"+index+"-ERROR",
          timestamp : Date.now(),
          fatal : false,
          potentialFix : "Examine Http Call with id: " + flight.id + "-" + index,
          body: {
              payload: {
                  protocol : reaction.protocol,
                  type: messageType.HTTPResponse.Error,
                  url: flight.journal.actions[modkey].baseURL,
                  status: smaug
              }
          }
      }
      flight.journal.reactions.push(reaction)
      //emit
      seidCar.HTTPLogger.emit("logHttp", reaction)
      //emit
      seidCar.ErrorLogger.emit("logError", err)
        //emit
        seidCar.HeartbeatLogger.emit("pulse", pulse)
    })

And have my logger handler the sending to the queue?并让我的记录器处理程序发送到队列?

HTTPLogger.js HTTPLogger.js


/*
Can I now send the message to the queue here, in this file?
*/
const HTTPEventLogger = require("events")
const emitter = new HTTPEventLogger()
const errorEmitter = require("./ErrorLogger").Emitter

class HTTPLogger extends HTTPEventLogger {
  logHttp(message) {
      switch (message.key.type) {
        case "ERROR":
          if (message !== undefined) {
            console.log(message)
          } else {
            errorEmitter.emit("tossIt", {
              error:"HTTP error Message is undefined in ~/Homestasis/Agent/HTTPLoggerjs.",
              poi:"check for recent additions to pilot agents in ~/Pilots/Agent",
              timestamp: Date.now(),
              potentialFix:"look to where you are emitting the message. Function Scope"
            })
          }
          break;
        case "OKAY":
          if (message !== undefined) {
            console.log(message)//bState.message.status)
          } else {
            errorEmitter.emit("tossIt", {
              error:"HTTP okay Message is undefined in ~/Homestasis/Agent/HTTPLoggerjs.",
              poi:"check for recent additions to pilot agents in ~/Pilots/Agent",
              timestamp: Date.now(),
              potentialFix:"look to where you are emitting the message. Function Scope"
            })
          }
          break;
        default:
          errorEmitter.emit("tossIt", "this is a tossIt error log. No http key type was caught bSate = " + bState)
      }
  }
}
var logger = new HTTPLogger()
emitter.on("logHttp",logger.logHttp)

exports.Emitter = emitter

Thats how I'd like to send the message.这就是我想发送消息的方式。

I'd like to be able to receive it much the same way我希望能够以同样的方式接收它

I'm not sure how to implement it given how I perceive it currently working and I am missing a key part of the equation.鉴于我如何看待它目前的工作方式,我不确定如何实施它,而且我错过了等式的关键部分。 Thank you for your time!感谢您的时间!

I decided to not use RabbitMQ.我决定不使用RabbitMQ。

For node, RSMQ is what I am going with.对于节点,RSMQ 是我要使用的。 I realized I fundamentally needed to shift how I viewed message queues working practically to get them to work practically.我意识到我从根本上需要改变我对消息队列实际工作的看法,以使它们实际工作。 I am using RSMQ, as I can understand how it fits into how I built my project out.我正在使用 RSMQ,因为我可以理解它如何适合我构建我的项目的方式。 I was going with ZeroMQ at first (I still may, the pliability of sockets on steroids).起初我打算使用 ZeroMQ(我仍然可以,类固醇套接字的柔韧性)。 But, I do like the actual features and stuff when I actually think about using it like a "mainline nerve".但是,当我真正考虑像“主线神经”一样使用它时,我确实喜欢实际的功能和东西。

The way I want to build it out goes as such:我想构建它的方式是这样的:

Axios Makes the call, fires off an event to the httplogger which fires off an event to the message queue. Axios 进行调用,触发一个事件到 httplogger,触发一个事件到消息队列。 So:所以:

RadioFlyer.js > HttpLogger.js > RSMQ-Messagequeue.js > next things > and next... RadioFlyer.js > HttpLogger.js > RSMQ-Messagequeue.js > 下一步 > 和下一步...

RSMQ-Messagequeue.js acts as a "middle man" or an intermediary to put the stops on the wheels when overloaded. RSMQ-Messagequeue.js 充当“中间人”或中介,在超载时停止工作。

The pros of RSMQ is that I also intend to implement a Redis Cache (I could implement ZeroMQ and do much the same), but I like that RSMQ allows for more queue options, instead of 1 queue with many topics. RSMQ 的优点是我还打算实现一个 Redis 缓存(我可以实现 ZeroMQ 并做很多相同的事情),但我喜欢 RSMQ 允许更多队列选项,而不是 1 个具有许多主题的队列。

There is a more fleshed out answer.有一个更充实的答案。

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

相关问题 如何确定应该使用哪种套接字从RabbitMQ队列中获取消息? - How can I determine what sort of socket I should use to get messages from a RabbitMQ queue? 如何将消息发送到我的队列和发布请求? - How can I send messages to my queue and a post request? 如何使用google-api-nodejs-client nodejs在同一线程上发送电子邮件 - How do i send a email on same thread using google-api-nodejs-client nodejs 如何使用NodeJS Gmail API提取邮件? - How do I fetch messages with the NodeJS Gmail API? RabbitMQ在网站上向用户发送消息 - RabbitMQ send messages to users on website 如何在没有nodejs的情况下使用javascript连接到rabbitmq - how to connect to rabbitmq using javascript without nodejs 如何使用 ActiveMQ-Artemis 从 Java 程序向 Javascript STOMP 客户端发送消息? - How do I send messages from Java program to a Javascript STOMP client using ActiveMQ-Artemis? 使用 Nodejs 向客户端发送消息 - Send messages to client with Nodejs 如何使用IP地址从一个Node.js应用程序向另一个请求发送请求? - How do I send a request from One Nodejs application to another using an IP address? 如何将消息从Javascript发送到Java? - How do I send messages from Javascript to Java?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM