Nodejs Redis Publish subscription mechanism encapsulation
Recent projects have used Redis to understand and encapsulate the use of publish and subscribe.
var config = require ('.. /config/config ');
var log = require ("./loghelp");
var Redis = require ("Redis");
function initialclient (param) {
var option={host:config.redis.host, port:config.redis.port};
if (param)
{
option=object.assign (option,param);
}
Redis.print Let
-client = redis.createclient (option);
Client.on ("Error", function (err) {
log.error (err);
});
return client;
}
/*example: * Let channel= "Ryan";
Redis.pubSub.registerHandlers ("Ryan",msg=> Console.log (msg));
Redis.pubSub.subscribe (channel);
Redis.pubSub.publish (channel, "Hello from Chen"); */Class PubSub {constructor () {this.sub=initialclient ();
This.handlers=new Map (); this.subaction= (channle,message) =>{let actions= this.handlers.get (Channle) | |
New Set ();
For [let action] {action (message);
}} this.alredypublishs=[];
This.subconnected=false;
} publish (Channel,message) {let action= () =>{let Pub=initialclient ();
Pub.publish (Channel,message);
};
if (this.subconnected===false) {This.alredyPublishs.push (action);
else action (); } registerhandlers (channel,action) {var actions=this.handlers.get (channel) | |
New Set ();
Actions.Add (action);
This.handlers.set (channel,actions);
} subscribe (channel) {Let self=this; This.sub.subscribe (ChannEl,function (err,reply) {if (err) log.error (err);
Self.subconnected=true;
For (let publish of Self.alredypublishs) publish ();
Console.log (reply);
});
This.sub.on ("Message", function (channel, message) {self.subaction (channel,message);
});
} teardown () {this.sub.quit (); }
}
The Exports.pubsub=new pubsub () is then used to make the leak, which can be guaranteed to be a single case. When the program starts, call the
Registerhandlers registers the processing logic for a particular channel, and then calls
Subscribe subscription channel.
Call publish at the right time, this mechanism can implement all the client watch the same data change.
I have all hand-built Dotnetcore WEBAPI Framework, can achieve rapid development.
Address: Http://xiazai.jb51.net/201612/yuanma/WebApiCore-master (jb51.net). rar.
1 using DDD Mode development, congestion Model 2 add dapper extension, the default implementation and check the basic operation. Use AutoMapper to do physical conversion, reduce duplication of labor. 3 Dependency Injection Fusion AUTOFAC, storage layer and application layer automatic injection 4 implementation JWT Validation 5 join Swagger Document 6 Unit test add XUNIT,MYMVC to facilitate WEBAPI Test 7 database version control
Thank you for reading, I hope to help you, thank you for your support for this site!