redis實現訊息佇列

來源:互聯網
上載者:User

標籤:

/**
* @author sam
* @date 2015/04/01
* @desc a message queue
*/
var EventEmitter = require(‘events‘).EventEmitter;

var util = require(‘util‘);

/**
* @cons
* @param {client} a redis client
* @param {priority:2} a number for set priority level, default 2 mean there have two priority level
* */
var RedisMessageQueue = function(client, name, priority){

if(name === null){
throw new Error(‘message queue name is null‘);
}

this.name = name;

priority = priority || 3; //系統預設具有三個優先順序的

this.priority = priority < 1 ? 1 : priority; //處理小於等於0的情況

this.__client = client;

this.__queueNames = [];

this.__init();
};

RedisMessageQueue.EVENTS = {
ERROR : ‘error‘
};

util.inherits(RedisMessageQueue,EventEmitter);


RedisMessageQueue.prototype.__init = function(){
var self = this;
//產生優先順序隊列名稱,*_0,*_1 數字小的優先順序高
for(var i = 0 ; i < this.priority; i++){
var messageQueueName = ‘message_queue_‘ + this.name + ‘_‘ + i;

self.__queueNames[i] = messageQueueName;
//非同步刪除
//this.__client.del(messageQueueName);
}

this.__client.on(‘error‘,function(err){
self.emit(RedisMessageQueue.EVENTS.ERROR,err);
});

};


RedisMessageQueue.prototype.produce = function(message, level, callback){
var self = this;

if(message == null){
callback && callback(null);
return;
}

var str = null;

var priority = self.__queueNames.length;

//預設寫到最低優先順序隊列裡面去
level = level || priority - 1;

level = level < priority ? level : priority - 1;

if(typeof message === ‘string‘){
str = message;
}else{
try{
str = JSON.stringify(message);
}catch (ex){
callback && callback(ex);
return;
}
}

self.__client.lpush(this.__queueNames[level],str,callback);

};

RedisMessageQueue.prototype.consume = function(cb){

var self = this; var queueNames = self.__queueNames; var time = 0; //表示用戶端永遠等待 queueNames.push(time); var client = self.__client; client.brpop(queueNames,function(err,res){ if(err){ cb && cb(err); return; } if(result === null){ cb && cb(null,null); return; } var result = res[1]; try{ cb && cb(null, JSON.parse(result)); return; }catch (ex){ if(typeof result === ‘string‘){ cb && cb(null, result); return; } cb && cb(ex); } });};exports.RedisMessageQueue = RedisMessageQueue;

redis實現訊息佇列

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.