/**
*@authorSam
*@date2015/04/01
*@descA message queue
*/
VarEventemitter =Require' Events ').Eventemitter;
VarUtil =Require' Util ');
/**
*@cons
*@param{Client} a Redis client
*@param{Priority:2} A number for Set priority level, default 2 mean there has a
* */
VarRedismessagequeue =functionClientNamePriority) {
IfName = = =NULL) {
throw newError (' Message queue name is null ');
}
This.Name =Name
Priority =Priority | |3;//The system defaults to a three-priority
This.Priority =Priority <1?1:Priority//Process less than or equal to0The situation
This.__client =Client
This.__queuenames = [];
This.__init ();
};
Redismessagequeue.EVENTS = {
ERROR:' Error '
};
Util.InheritsRedismessagequeue,Eventemitter);
Redismessagequeue.Prototype.__init =function () {
VarSelf =This
//Generate Priority queue name, *_0,*_1High priority for small numbers
ForVari =0;I <This.Priorityi++) {
VarMessagequeuename =' Message_queue_ ' +This.Name +' _ ' +I
Self.__queuenames[I] =Messagequeuename;
//Asynchronous Delete
This.__client.del (Messagequeuename);
}
This.__client.On' Error ',functionERR) {
Self.EmitRedismessagequeue.EVENTS.ERROR,ERR);
});
};
Redismessagequeue.Prototype.produce =functionMessageLevelCallback) {
VarSelf =This
IfMessage = =NULL) {
Callback &&CallbackNULL);
Return
}
Varstr =Null
VarPriority =Self.__queuenames.Length
//Default write to lowest priority queue go inside
Level =Level | |Priority-1;
Level =Level <Priority?Level:Priority-1;
Iftypeofmessage = = =' String ') {
str =Message
}else{
try{
str =Json.Stringify (message);
}catch (Ex) {
Callback &&Callbackex);
Return
}
}
Self.__client.lpush (This.__queuenames[Level],Strcallback);
};
Redismessagequeue.Prototype.consume = function (CB) {
var = this ; var queuenames = self.__queuenames; var time = 0;//indicates that the client is always waiting for queuenames.push (time); var client = self.__client; clien T.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 implements Message Queuing