当前位置:首页 > JavaScript

js 实现消息队列

2026-02-02 17:52:17JavaScript

实现消息队列的基本概念

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

使用数组实现简单消息队列

利用数组的pushshift方法可以模拟队列的先进先出(FIFO)特性。

js 实现消息队列

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

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

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

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

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

// 使用示例
const queue = new SimpleQueue();
queue.enqueue('Task 1');
queue.enqueue('Task 2');
console.log(queue.dequeue()); // 输出: Task 1

使用Promise实现异步消息队列

结合Promise可以实现异步任务队列,确保任务按顺序执行。

class AsyncQueue {
  constructor() {
    this.queue = [];
    this.isProcessing = false;
  }

  enqueue(task) {
    return new Promise((resolve, reject) => {
      this.queue.push({ task, resolve, reject });
      if (!this.isProcessing) this.process();
    });
  }

  async process() {
    this.isProcessing = true;
    while (this.queue.length > 0) {
      const { task, resolve, reject } = this.queue.shift();
      try {
        const result = await task();
        resolve(result);
      } catch (error) {
        reject(error);
      }
    }
    this.isProcessing = false;
  }
}

// 使用示例
const asyncQueue = new AsyncQueue();
asyncQueue.enqueue(() => new Promise(res => setTimeout(() => res('Task 1 done'), 1000)));
asyncQueue.enqueue(() => new Promise(res => setTimeout(() => res('Task 2 done'), 500)));

使用第三方库

对于更复杂的场景,可以使用专门的库如BullRabbitMQAWS SQS

js 实现消息队列

Bull示例(基于Redis)

const Queue = require('bull');

const taskQueue = new Queue('tasks', 'redis://127.0.0.1:6379');

taskQueue.process(async (job) => {
  console.log(`Processing job ${job.id}:`, job.data);
  return { result: job.data.value * 2 };
});

taskQueue.add({ value: 10 });
taskQueue.add({ value: 20 });

处理并发和优先级

可以通过设置并发限制或优先级来优化队列性能。

// Bull并发控制
taskQueue.process(5, async (job) => { /* 最多同时处理5个任务 */ });

// 优先级队列
taskQueue.add({ value: 30 }, { priority: 1 }); // 更高优先级

错误处理和重试机制

为队列添加错误处理和自动重试逻辑。

taskQueue.process(async (job) => {
  try {
    // 业务逻辑
  } catch (error) {
    console.error(`Job ${job.id} failed:`, error);
    throw error; // Bull会自动重试(如果配置了重试次数)
  }
});

// 配置重试
taskQueue.add({ value: 40 }, { attempts: 3, backoff: 1000 });

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

相关文章

vue实现消息接收

vue实现消息接收

Vue 实现消息接收的方法 在 Vue 中实现消息接收通常涉及 WebSocket、EventBus 或第三方库(如 Socket.IO)。以下是几种常见的实现方式: 使用 WebSocket We…

vue实现消息提醒功能

vue实现消息提醒功能

Vue 实现消息提醒功能的方法 使用 Vue 的 v-if 或 v-show 控制显示 通过 Vue 的指令 v-if 或 v-show 可以动态控制消息提醒的显示与隐藏。v-if 是条件渲染,v-s…

vue实现滚动推送消息

vue实现滚动推送消息

vue实现滚动推送消息的方法 使用CSS动画实现滚动 通过CSS的animation和@keyframes实现无限滚动效果,适合简单的单行消息推送。 <template> <d…

vue消息提示怎么实现

vue消息提示怎么实现

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

php数组实现队列

php数组实现队列

使用数组实现队列的基本方法 在PHP中,数组可以模拟队列的先进先出(FIFO)特性。通过内置的数组函数,可以轻松实现队列的基本操作。 初始化队列 $queue = []; 入队操作(enqueue…

php使用redis实现队列

php使用redis实现队列

PHP 使用 Redis 实现队列 Redis 是一个高性能的键值存储系统,支持多种数据结构,如字符串、哈希、列表、集合等。利用 Redis 的列表(List)数据结构可以轻松实现队列功能。以下是实现…