super-queue
基于Redis的简单消息队列模块
安装
$ npm install super-queue --save
必须使用 Node.js v4.0 或更高版本
使用
生产者 Producer
'use strict'; const Producer = Producer; const p = // 队列名称 queue: 'my_queue' // 设置Redis数据库连接 redis: host: 'localhost' port: 6379 db: 0 // 默认的消息有效时间(s),为0表示永久 maxAge: 0 // 心跳时间周期(s),默认2秒 heartbeat: 2; // 消息入队const data = 'abcdefg'; // 消息内容,必须为字符串类型const maxAge = 10; // 消息有效时间,当省略此参数时使用默认的maxAge值p; // 初始化成功,触发start事件// 注意:一定要在触发此事件后再使用push(),否则可能无法收到消息处理结果p; // 退出p;
消费者 Consumer
'use strict'; const Consumer = Consumer; const c = // 队列名称 queue: 'my_queue' // 设置Redis数据库连接 redis: host: 'localhost' port: 6379 db: 0 // 处理能力,如果当前消费者正在处理的消息数量超过该值则不再接收新消息,为0表示不限制 capacity: 0 // 心跳时间周期(s),默认2秒 heartbeat: 2; // 监听队列c; // 退出c;
监视器 Monitor
监视器主要完成以下功能:
- 当消费者异常退出时,自动将该消费者中未处理完的任务重新加入队列
- 监控队列长度,当超过指定值时自动清理部分最早入队但未处理的消息,并通知相应的生产者
'use strict'; const Monitor = Monitor; const m = // 设置Redis数据库连接 redis: host: 'localhost' port: 6379 db: 0 // 自动检查时间间隔(s),默认为2秒 interval: 2; m;m; m;m; // 获取客户端状态m; // 获取队列状态m; // 退出m;
Promise 支持
本模块同时提供了返回Promise
对象的接口,但其不能与callback
混用。以下为使用Promise
接口的例子:
'use strict'; // 使用模块输出的promise属性下的Producerconst Producer = promiseProducer; // 用法一样const p = // 队列名称 queue: 'my_queue' // 设置Redis数据库连接 redis: host: 'localhost' port: 6379 db: 0 // 默认的消息有效时间(s),为0表示永久 maxAge: 0 // 心跳时间周期(s),默认2秒 heartbeat: 2; // 消息入队const data = 'abcdefg'; // 消息内容,必须为字符串类型const maxAge = 10; // 消息有效时间,当省略此参数时使用默认的maxAge值// 不需要传递callback参数,其他用法跟原来一样p; // 返回的Promise对象使用的是bluebird模块,如果一定要使用callback可使用其asCallback()方法p; // 初始化成功,触发start事件// 注意:一定要在触发此事件后再使用push(),否则可能无法收到消息处理结果p; // 退出p;
License
The MIT License (MIT)
Copyright (c) 2016 SuperID | 免费极速身份验证服务
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.