This article mainly introduces the analysis of how NodeJS operates the message queue RabbitMQ. It has a certain reference value. Now I share it with you. Friends in need can refer to it
1. What is a message queue? ?
Message (Message) refers to the data transmitted between applications. Messages can be very simple, containing only text strings, or more complex, possibly containing embedded objects.
Message Queue (Message Queue) is a communication method between applications. Messages can be returned immediately after being sent. The message system ensures reliable delivery of messages. The message publisher just publishes the message to MQ and doesn't care who gets it, and the message consumer just gets the message from MQ regardless of who publishes it. In this way, neither the publisher nor the user needs to know the existence of the other party.
2. What are the commonly used message queues?
RabbitMQ, RocketMQ, ActiveMQ, Kafka, ZeroMQ, MetaMq.
Even now some NoSQL can also be used as message queues, such as Redis.
3. What are the usage scenarios of message queue?
Asynchronous processing
Application decoupling
Traffic peak clipping
4. Use cases
Large-scale companies will have their own log analysis system. How is the log system implemented?
Illustration: When a user accesses an application, we need to record the user's operation record and the system's exception log. The conventional approach is It saves the logs generated by the system to the server disk, starts scheduled tasks in the server, regularly transfers the log information from the disk to mq (producer), and also regularly takes out the messages in mq and saves them to the corresponding database, such as ElasticSearch or Hive.
5. How to install RabbitMQ?
The above case introduces a usage scenario of MQ. I am using RabbitMQ as an example here. Kafka may be used in real projects.
First install brew (mac as an example)
/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
Install RabbitMQ
brew install rabbitmq
Run RabbitMQ
Enter /usr/local/Cellar/rabbitmq/3.7 .7. Execute
sbin/rabbitmq-server
Start plug-in
Enter /usr/local/Cellar/rabbitmq/3.7.7/sbin
./rabbitmq-plugins enable rabbitmq_management
Log in to the management interface
Open the browser and enter: http://localhost:15672, RabbitMQ defaults to port 15672. Nodejs operates RabbitMQ
You can find several corresponding responses online Node SDK, here we recommend amqplib
1. Producer
/** * 对RabbitMQ的封装 */ let amqp = require('amqplib'); class RabbitMQ { constructor() { this.hosts = []; this.index = 0; this.length = this.hosts.length; this.open = amqp.connect(this.hosts[this.index]); } sendQueueMsg(queueName, msg, errCallBack) { let self = this; self.open .then(function (conn) { return conn.createChannel(); }) .then(function (channel) { return channel.assertQueue(queueName).then(function (ok) { return channel.sendToQueue(queueName, new Buffer(msg), { persistent: true }); }) .then(function (data) { if (data) { errCallBack && errCallBack("success"); channel.close(); } }) .catch(function () { setTimeout(() => { if (channel) { channel.close(); } }, 500) }); }) .catch(function () { let num = self.index++; if (num <= self.length - 1) { self.open = amqp.connect(self.hosts[num]); } else { self.index == 0; } }); } }
2. Consumer
/** * 对RabbitMQ的封装 */ let amqp = require('amqplib'); class RabbitMQ { constructor() { this.open = amqp.connect(this.hosts[this.index]); } receiveQueueMsg(queueName, receiveCallBack, errCallBack) { let self = this; self.open .then(function (conn) { return conn.createChannel(); }) .then(function (channel) { return channel.assertQueue(queueName) .then(function (ok) { return channel.consume(queueName, function (msg) { if (msg !== null) { let data = msg.content.toString(); channel.ack(msg); receiveCallBack && receiveCallBack(data); } }) .finally(function () { setTimeout(() => { if (channel) { channel.close(); } }, 500) }); }) }) .catch(function () { let num = self.index++; if (num <= self.length - 1) { self.open = amqp.connect(self.hosts[num]); } else { self.index = 0; self.open = amqp.connect(self.hosts[0]); } }); }
3. Send a message to MQ through the producer and create a queue
let mq = new RabbitMQ(); mq.sendQueueMsg('testQueue', 'my first message', (error) => { console.log(error) })
After execution, we opened the management platform and found that RabbbitMQ had received a message:
and RabbbitMQ added a new queue testQueue
4. Get messages from the specified queue
let mq = new RabbitMQ(); mq.receiveQueueMsg('testQueue',(msg) => { console.log(msg) })// 输出结果:my first message复制代码
At this time, open the RabbitMQ management platform, and the number of messages has become 0
To summarize: We briefly talked about some knowledge related to message queues and RabbitMQ, and how we produce and consume messages through nodejs.
The above is the entire content of this article. I hope it will be helpful to everyone's study. For more related content, please pay attention to the PHP Chinese website!
Related recommendations:
How to implement the file download function using JavaScript
Call baidu-aip through node.js -SDK realizes the function of ID card recognition
The above is the detailed content of Analysis of how NodeJS operates message queue RabbitMQ. For more information, please follow other related articles on the PHP Chinese website!

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version
Useful JavaScript development tools