node.js 下使用 redis 作为缓存介质
之前有一篇介绍 node.js 下,轻量级缓存应用模块 node-cache 点击访问.
今天介绍使用 redis 作为缓存介质.
首先,我们需要一个 node.js 下可以访问 redis 的中间件,就是 node_redis
github地址:https://github.com/NodeRedis/node_redis
安装:
npm install --save redis
然后我们封装一个缓存类:
var redis = require('redis');
var config = require('../config');
////////////////////////////////////
// Cache
////////////////////////////////////
function Cache() {
this._redis = this._redis ? this._redis : redis.createClient(config.redis.port, config.redis.host);
}
Cache.prototype.keys = function (k,fn) {
this._redis.keys(k, fn);
}
Cache.prototype.get = function (k, fn) {
this._redis.get(k, fn);
};
Cache.prototype.set = function (k, v, fn) {
this._redis.set(k, v, fn);
};
Cache.prototype.expire = function (k, interval) {
this._redis.expire(k, interval);
};
Cache.prototype.del = function (k, fn) {
this._redis.del(k, fn);
};
Cache.prototype.hset = function (k, f, v, fn) {
if (this._redis.hset === undefined) {
fn(Error(), null);
} else {
this._redis.hset(k, f, v, fn);
}
};
Cache.prototype.hget = function (k, f, fn) {
if (this._redis.hget === undefined) {
fn(Error(), null);
} else {
this._redis.hget(k, f, fn);
}
};
Cache.prototype.multiDel = function (k, fn) {
var multi = this._redis.multi();
_.each(k, function (row) {
multi.del(row);
});
multi.exec();
};
module.exports = Cache;
我们上面定义了一个存储类 Cache
构造函数
function Cache() {
this._redis = this._redis ? this._redis : redis.createClient(config.redis.port, config.redis.host);
}
有一个私有变量 _redis ,我们暂时称作构造器,他是用来初始化redis连接对象的.
接着下面定义了 Cache 类的几个属性方法,方法体里最后还是调用了 _redis连接对象暴露的底层方法.
Cache 类上定义是属性方法,最后都调用了 _reids 下的同名方法.
这时我们的缓存类就有了
设置缓存 (set)
获取缓存 (get)
缓存过期 (expire)
hset 及 hget 方法.
如何使用:
在需要设置缓存的方法层调用 上面的 Cache 类
var Cache = require('../common/Cache');
假设代码里有一个查询当日数据方法,而这种实时返回当前数据的接口访问量比较大,很有必要做一个缓存
看下这个方法:
var selectToday = function (appkey, url, callback) {
var cache = new Cache();
var key = 'today:' + appkey;
cache.get(key,function(err,value){
if(!err&&value){
callback(null, JSON.parse(value));
}else{
todayData(appkey, url, function (err, result) {
if (!err) {
cache.set(key, JSON.stringify(result));
cache.expire(key,config.redis.expire);
callback(null, result);
} else {
callback(err, null);
}
});
}
});
};
首先方法里实例化一个缓存对象
var cache=new Cache();
然后根据调用 get 方法,查看缓存中是否有此数据. cache.get(.....)
如果有: 直接拿来返回调用层 callback(null, JSON.parse(value)); 我在redis 里存储的是一个格式化后的Object ,所以这里取出来后格式化成对象返回.
如果没有缓存此数据:
调用方法 todayData(......)
拿到数据后:
如果出错,直接返回调用层错误信息.
如果正确,把此结果缓存到 reids 数据库中,同时设定一个过期时间 cache.expire(key,过期时间) //我的过期时间配置在config 中.
end