Table of Contents
1. Message Queue
Home Web Front-end JS Tutorial What is a message queue? How to use message queue in node?

What is a message queue? How to use message queue in node?

Jun 02, 2022 am 10:05 AM
nodejs​ node.js node

What is a message queue? The following article will take you through the basic concepts of message queues and introduce how to use message queues in node. I hope it will be helpful to everyone!

What is a message queue? How to use message queue in node?

1. Message Queue

What is Message Queue

The message queue is a container that saves messages during the message transmission process. It is essentially a queue (first in, first out)

What is a message queue? How to use message queue in node?

##Message refers to the data that needs to be transmitted, which can be some text, string, or object and other information.

Message Queue is a communication service between two applications. The producer of the message can return immediately after storing the data in the message queue without waiting for the message. The receiver responds. That is: Producer ensures that data is inserted into the queue, and there is no need to worry about who will get this message. The receiver of the message only focuses on receiving the message and processing it.

What is a message queue? How to use message queue in node?

What can the message queue do

  • Decoupling As introduced above, the message queue separates the message producer and the message receiver, and neither is affected by the other.

  • Asynchronous Asynchronous is to reduce the response time of requests. The producer of the message only needs to process simple logic and put the data in the message queue to return. , complex logic, such as: database operations, IO operations are handled by the receiver of the message.

  • Peak Shaving When the message queue application is serving, it can save the instantaneous influx of request information into the message queue and return it immediately. The request is then processed based on the data by the recipient of the message.

  • Application Scenarios Applications such as game activities, flash sale activities, orders, etc. will cause a sudden increase in traffic.

2. The concept of message queue

After introducing the basic information of message queue, let’s introduce some of the message queue before developing the message queue. Basic concept~

Producer and consumer of message

producer mentioned above and Consumer provide

links, channels and queues

  • Link (connection): Represents a link between the service program and the message queue.

    A service program can create multiple links.

  • Channel: A channel between message queue links.

    A link can have multiple channels.

  • Queue (queue): The queue that stores data in the message queue. A message queue service can have multiple queues.

To summarize, the relationship between links and channel queues is like this

What is a message queue? How to use message queue in node?

Exchange )

Message queue

When sending a messagemusthave a switch. If not specified, the default switch is used. The role of the switch is to push messages to the corresponding queue. There are a total of 4 types of switches in the message queue

  • Direct: Specify the queue mode. When a message comes, it will only be sent to the specified Queue, and other Queues will not receive it.

  • fanout: Broadcast mode, when a message comes, it will be sent to all queues.

  • topic: Fuzzy matching mode, corresponding forwarding through fuzzy matching.

  • header: Similar to Direct mode.

3.node uses rabbitMQ

##Install rabbitMQ

Installing rabbitMQ can be downloaded and installed through the official website.
    Portal
  • MAC can directly use the brew command to install

    1

    brew install rabbitmq

    Copy after login
  • Start the rabbitmq service after the installation is complete

What is a message queue? How to use message queue in node?Then visit http://localhost:15672/ locally to see the background of the rabbitmq service. The initial account and password are

guest

What is a message queue? How to use message queue in node?

##node project installation amqplib

amqplib is a set of tools for using message queues in node, which allows us to quickly use message queues

地址:https://www.npmjs.com/package/amqplib

创建生产者

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

/** product.js 消费者 */

 

 

const amqplib = require('amqplib');

const config = require('./config');

 

const { connectUrl } = config;

 

(async () => {

  const connection = await amqplib.connect(connectUrl);

 

  const channel = await connection.createChannel();

  const exchangeName = 'testExchange';

  const key = 'testQueue';

  const sendMsg = 'hello rabbitmq';

     

  // 知道交换机类型

  await channel.assertExchange(exchangeName, 'fanout', {

    durable: true,

  });

     

  // 指定一个队列

  await channel.assertQueue(key);

 

  for (let i = 0; i < 100; i++) {

    channel.publish(exchangeName, key, Buffer.from(`${sendMsg} ${i}`));

  }

 

  await channel.close();

  await connection.close();

})();

Copy after login

运行后在后台可以看到新增了一个有100条消息的队列

What is a message queue? How to use message queue in node?

创建消费者

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

/** customer.js 消费者 */

 

const amqplib = require(&#39;amqplib&#39;);

const config = require(&#39;./config&#39;);

 

const { connectUrl } = config;

 

(async () => {

  let connection = await amqplib.connect(connectUrl);

  const exchangeName = &#39;testExchange&#39;;

  const key = &#39;testQueue&#39;;

  // 创建两个通道

  const channel1 = await connection.createChannel();

  const channel2 = await connection.createChannel();

  // 指定一个交换机

  await channel1.assertExchange(exchangeName, &#39;fanout&#39;, {

    durable: true,

  });

  // 指定一个队列

  await channel1.assertQueue(key);

  await channel1.bindQueue(key, exchangeName, key);

  channel1.consume(key, (msg) => {

    console.log(&#39;channel 1&#39;, msg.content.toString());

  });

 

  await channel2.assertExchange(exchangeName, &#39;fanout&#39;, {

    durable: true,

  });

  await channel2.assertQueue(key);

  await channel2.bindQueue(key, exchangeName, key);

  channel2.consume(key, (msg) => {

    console.log(&#39;channel 2&#39;, msg.content.toString());

  });

})();

Copy after login

执行后可以看到,两个通道可以同时工作接收消息

What is a message queue? How to use message queue in node?

更多node相关知识,请访问:nodejs 教程

The above is the detailed content of What is a message queue? How to use message queue in node?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

An article about memory control in Node An article about memory control in Node Apr 26, 2023 pm 05:37 PM

The Node service built based on non-blocking and event-driven has the advantage of low memory consumption and is very suitable for handling massive network requests. Under the premise of massive requests, issues related to "memory control" need to be considered. 1. V8’s garbage collection mechanism and memory limitations Js is controlled by the garbage collection machine

Detailed graphic explanation of the memory and GC of the Node V8 engine Detailed graphic explanation of the memory and GC of the Node V8 engine Mar 29, 2023 pm 06:02 PM

This article will give you an in-depth understanding of the memory and garbage collector (GC) of the NodeJS V8 engine. I hope it will be helpful to you!

Let's talk in depth about the File module in Node Let's talk in depth about the File module in Node Apr 24, 2023 pm 05:49 PM

The file module is an encapsulation of underlying file operations, such as file reading/writing/opening/closing/delete adding, etc. The biggest feature of the file module is that all methods provide two versions of **synchronous** and **asynchronous**, with Methods with the sync suffix are all synchronization methods, and those without are all heterogeneous methods.

How to use express to handle file upload in node project How to use express to handle file upload in node project Mar 28, 2023 pm 07:28 PM

How to handle file upload? The following article will introduce to you how to use express to handle file uploads in the node project. I hope it will be helpful to you!

An in-depth analysis of Node's process management tool 'pm2” An in-depth analysis of Node's process management tool 'pm2” Apr 03, 2023 pm 06:02 PM

This article will share with you Node's process management tool "pm2", and talk about why pm2 is needed, how to install and use pm2, I hope it will be helpful to everyone!

Pi Node Teaching: What is a Pi Node? How to install and set up Pi Node? Pi Node Teaching: What is a Pi Node? How to install and set up Pi Node? Mar 05, 2025 pm 05:57 PM

Detailed explanation and installation guide for PiNetwork nodes This article will introduce the PiNetwork ecosystem in detail - Pi nodes, a key role in the PiNetwork ecosystem, and provide complete steps for installation and configuration. After the launch of the PiNetwork blockchain test network, Pi nodes have become an important part of many pioneers actively participating in the testing, preparing for the upcoming main network release. If you don’t know PiNetwork yet, please refer to what is Picoin? What is the price for listing? Pi usage, mining and security analysis. What is PiNetwork? The PiNetwork project started in 2019 and owns its exclusive cryptocurrency Pi Coin. The project aims to create a one that everyone can participate

Let's talk about the event loop in Node Let's talk about the event loop in Node Apr 11, 2023 pm 07:08 PM

The event loop is a fundamental part of Node.js and enables asynchronous programming by ensuring that the main thread is not blocked. Understanding the event loop is crucial to building efficient applications. The following article will give you an in-depth understanding of the event loop in Node. I hope it will be helpful to you!

What should I do if node cannot use npm command? What should I do if node cannot use npm command? Feb 08, 2023 am 10:09 AM

The reason why node cannot use the npm command is because the environment variables are not configured correctly. The solution is: 1. Open "System Properties"; 2. Find "Environment Variables" -> "System Variables", and then edit the environment variables; 3. Find the location of nodejs folder; 4. Click "OK".

See all articles