Table of Contents
1. Message Queue
Home Web Front-end JS Tutorial An article briefly analyzing how to use message queue in node

An article briefly analyzing how to use message queue in node

Jan 17, 2023 pm 07:48 PM
node message queue

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 you!

An article briefly analyzing 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)


An article briefly analyzing 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. [Related tutorial recommendations: nodejs video tutorial, Programming teaching]

An article briefly analyzing 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

An article briefly analyzing how to use message queue in node

Exchange )Message queue

When sending a message

musthave 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

Then visit http://localhost:15672/ locally to see the background of the rabbitmq service. The initial account and password are An article briefly analyzing how to use message queue in nodeguest

An article briefly analyzing how to use message queue in node##node project installation amqplib

amqplib是node中使用消息队列的一套工具,可以让我们快速地使用消息队列

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

创建生产者

/** 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条消息的队列

An article briefly analyzing how to use message queue in node

创建消费者

/** 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

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

An article briefly analyzing how to use message queue in node

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

The above is the detailed content of An article briefly analyzing 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)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months 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)

Java Websocket development practice: how to implement message queue function Java Websocket development practice: how to implement message queue function Dec 02, 2023 pm 01:57 PM

Java Websocket development practice: How to implement the message queue function Introduction: With the rapid development of the Internet, real-time communication is becoming more and more important. In many web applications, real-time updates and notification capabilities are required through real-time messaging. JavaWebsocket is a technology that enables real-time communication in web applications. This article will introduce how to use JavaWebsocket to implement the message queue function and provide specific code examples. Basic concepts of message queue

How to use message queue for asynchronous task processing in FastAPI How to use message queue for asynchronous task processing in FastAPI Jul 30, 2023 pm 09:21 PM

How to use message queues for asynchronous task processing in FastAPI Introduction: In web applications, it is often necessary to process time-consuming tasks, such as sending emails, generating reports, etc. If these tasks are placed in a synchronous request-response process, users will have to wait for a long time, reducing user experience and server response speed. In order to solve this problem, we can use message queue for asynchronous task processing. This article will introduce how to use message queues to process asynchronous tasks in the FastAPI framework.

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

Token-based authentication with Angular and Node Token-based authentication with Angular and Node Sep 01, 2023 pm 02:01 PM

Authentication is one of the most important parts of any web application. This tutorial discusses token-based authentication systems and how they differ from traditional login systems. By the end of this tutorial, you will see a fully working demo written in Angular and Node.js. Traditional Authentication Systems Before moving on to token-based authentication systems, let’s take a look at traditional authentication systems. The user provides their username and password in the login form and clicks Login. After making the request, authenticate the user on the backend by querying the database. If the request is valid, a session is created using the user information obtained from the database, and the session information is returned in the response header so that the session ID is stored in the browser. Provides access to applications subject to

Golang development: Build a reliable message queue using NATS Golang development: Build a reliable message queue using NATS Sep 21, 2023 am 11:21 AM

Golang development: Using NATS to build a reliable message queue, specific code examples are required Introduction: In modern distributed systems, the message queue is an important component used to handle asynchronous communication, decouple system components and achieve reliable message delivery. This article will introduce how to use the Golang programming language and NATS (the full name is "High Performance Reliable Message System") to build an efficient and reliable message queue, and provide specific code examples. What is NATS? NATS is a lightweight, open source messaging system.

The wonderful use of Redis in message queue The wonderful use of Redis in message queue Nov 07, 2023 pm 04:26 PM

The wonderful use of Redis in message queues Message queues are a common decoupled architecture used to deliver asynchronous messages between applications. By sending a message to a queue, the sender can continue performing other tasks without waiting for a response from the receiver. And the receiver can get the message from the queue and process it at the appropriate time. Redis is a commonly used open source in-memory database with high performance and persistent storage capabilities. In message queues, Redis's multiple data structures and excellent performance make it an ideal choice

How to implement message queue using Linux script operations in Java How to implement message queue using Linux script operations in Java Oct 05, 2023 am 08:09 AM

How to use Linux script operations to implement message queues in Java requires specific code examples. Message queues are a common communication mechanism used to transfer data between different processes. In Java, we can implement message queues using Linux script operations so that we can easily send messages to or receive messages from the queue. In this article, we will detail how to implement message queues using Java and Linux scripts, and provide specific code examples. To get started with Java and Lin

How to deal with distributed transactions and message queues in C# development How to deal with distributed transactions and message queues in C# development Oct 09, 2023 am 11:36 AM

How to handle distributed transactions and message queues in C# development Introduction: In today's distributed systems, transactions and message queues are very important components. Distributed transactions and message queues play a crucial role in handling data consistency and system decoupling. This article will introduce how to handle distributed transactions and message queues in C# development, and give specific code examples. 1. Distributed transactions Distributed transactions refer to transactions that span multiple databases or services. In distributed systems, how to ensure data consistency has become a major challenge. Here are two types of

See all articles