nodejs使用redis作为缓存介质实现的封装缓存类示例
本文实例讲述了nodejs使用redis作为缓存介质实现的封装缓存类。分享给大家供大家参考,具体如下:
之前在node下使用redis作为缓存介质,对redis进行了一层封装
First:安装npm包redis
constredis=require('redis');
Second:进行封装
//cache.js
constredis=require('redis');
constconfig=require('config');
constlogger=require('winston');
constredisObj={
client:null,
connect:function(){
this.client=redis.createClient(config.redis);
this.client.on('error',function(err){
logger.error('redisCacheError'+err);
});
this.client.on('ready',function(){
logger.info('redisCacheconnectionsucceed');
});
},
init:function(){
this.connect();//创建连接
constinstance=this.client;
//主要重写了一下三个方法。可以根据需要定义。
constget=instance.get;
constset=instance.set;
constsetex=instance.setex;
instance.set=function(key,value,callback){
if(value!==undefined){
set.call(instance,key,JSON.stringify(value),callback);
}
};
instance.get=function(key,callback){
get.call(instance,key,(err,val)=>{
if(err){
logger.warn('redis.get:',key,err);
}
callback(null,JSON.parse(val));
});
};
//可以不用传递expires参数。在config文件里进行配置。
instance.setex=function(key,value,callback){
if(value!==undefined){
setex.call(instance,key,config.cache.maxAge,JSON.stringify(value),callback);
}
};
returninstance;
},
};
//返回的是一个redis.client的实例
module.exports=redisObj.init();
Howtouse
constcache=require('./cache');
cache.get(key,(err,val)=>{
if(val){
//dosomething
}else{
//dootherthing
}
});
cache.set(key,val,(err,res)=>{
//dosomething
});
cache.setex(key,val,(err,res)=>{
//dosomething
})
希望本文所述对大家nodejs程序设计有所帮助。