当前位置:首页 > JavaScript

js 实现消息队列

2026-04-07 11:34:10JavaScript

实现消息队列的基本思路

使用 JavaScript 实现消息队列的核心是利用数组或链表结构存储消息,并通过先进先出(FIFO)的原则处理消息。消息队列通常包含入队(enqueue)和出队(dequeue)操作,以及队列状态监控等功能。

js 实现消息队列

基于数组的简单消息队列

class MessageQueue {
  constructor() {
    this.queue = [];
  }

  enqueue(message) {
    this.queue.push(message);
  }

  dequeue() {
    return this.queue.shift();
  }

  isEmpty() {
    return this.queue.length === 0;
  }

  size() {
    return this.queue.length;
  }
}

基于链表的消息队列

链表实现可以避免数组 shift() 操作的高时间复杂度(O(n)),提升性能。

js 实现消息队列

class Node {
  constructor(value) {
    this.value = value;
    this.next = null;
  }
}

class LinkedListMessageQueue {
  constructor() {
    this.head = null;
    this.tail = null;
    this.length = 0;
  }

  enqueue(value) {
    const newNode = new Node(value);
    if (!this.head) {
      this.head = newNode;
      this.tail = newNode;
    } else {
      this.tail.next = newNode;
      this.tail = newNode;
    }
    this.length++;
  }

  dequeue() {
    if (!this.head) return null;
    const value = this.head.value;
    this.head = this.head.next;
    this.length--;
    if (this.length === 0) this.tail = null;
    return value;
  }

  isEmpty() {
    return this.length === 0;
  }

  size() {
    return this.length;
  }
}

支持异步处理的扩展消息队列

结合 Promise 或 async/await 实现异步消息处理,适用于需要等待任务完成的场景。

class AsyncMessageQueue {
  constructor() {
    this.queue = [];
    this.resolveMap = new Map();
  }

  enqueue(message) {
    return new Promise((resolve) => {
      if (this.resolveMap.size === 0) {
        this.queue.push(message);
        resolve();
      } else {
        const oldestResolve = this.resolveMap.keys().next().value;
        oldestResolve(message);
        this.resolveMap.delete(oldestResolve);
      }
    });
  }

  dequeue() {
    return new Promise((resolve) => {
      if (this.queue.length > 0) {
        resolve(this.queue.shift());
      } else {
        this.resolveMap.set(resolve, true);
      }
    });
  }
}

使用场景示例

消息队列适用于任务调度、事件处理、缓冲请求等场景。例如,在 Web 应用中处理高并发请求时,可以用消息队列缓冲任务。

const queue = new MessageQueue();

// 生产者
queue.enqueue("Task 1");
queue.enqueue("Task 2");

// 消费者
while (!queue.isEmpty()) {
  const task = queue.dequeue();
  console.log("Processing:", task);
}

性能优化与注意事项

  • 避免频繁内存操作:链表实现更适合高频入队/出队场景。
  • 错误处理:增加队列溢出或空队列处理的逻辑。
  • 并发控制:多线程环境下需使用锁机制(如 Web Worker 的原子操作)。

标签: 队列消息
分享给朋友:

相关文章

vue消息提示怎么实现

vue消息提示怎么实现

Vue 消息提示的实现方法 使用 Element UI 的 Message 组件 Element UI 提供了 ElMessage 组件,用于显示全局消息提示。安装 Element UI 后可以直接使…

php实现一个双向队列

php实现一个双向队列

PHP 实现双向队列 双向队列(Deque)是一种允许在队列两端进行插入和删除操作的线性数据结构。PHP 可以通过数组或 SplDoublyLinkedList 类实现双向队列。 使用数组实…

php redis如何实现队列

php redis如何实现队列

PHP Redis 实现队列的方法 Redis 是一个高性能的键值存储系统,常用于实现队列功能。以下是在 PHP 中使用 Redis 实现队列的几种常见方法: 使用 LPUSH 和 RPOP 实现队…

php实现消息

php实现消息

PHP实现消息功能的方法 数据库设计 创建消息表存储消息数据,基本字段包括: id:消息唯一标识 sender_id:发送者ID receiver_id:接收者ID content:消息内容 cre…

js 实现一个任务队列

js 实现一个任务队列

实现基础任务队列结构 使用数组存储任务,通过push方法添加任务,shift方法取出任务执行: class TaskQueue { constructor() { this.tasks…

js 实现消息队列

js 实现消息队列

实现消息队列的基本概念 消息队列是一种异步通信机制,允许不同的应用程序或组件通过发送和接收消息来交互。在JavaScript中,可以使用数组、对象或第三方库来实现消息队列的功能。 使用数组实现简单消…