最近想知道node相关的缓存,就找到了redis
然后自己实现了node api数据的缓存
我先写了个模块,当做redis的链接对象的工厂
新建了redis_factory.js
var redis = require('redis');
var poolModule = require('generic-pool');//使用generic-pool池化
var pool = poolModule.Pool({
name : 'redisPool',
create : function(callback) {
var client = redis.createClient();
callback(null, client);
},
destroy : function(client) {
client.quit();
},
max : 100,
min : 5,
idleTimeoutMillis : 30000,
log : false
});
exports.pool = pool;
然后在api方法里面这样用
#include <iostream>
#include"stack.h"
#include"stack.cpp"
using namespace std;
int main()
{
Stack<double> stack;
stack.push(5);
stack.push(54.01);
stack.push(55);
stack.push(577);
stack.printStack();
cout<<stack.contains(54)<<endl;
cout<<stack.contains(555)<<endl;
return 0;
}
var pool = require('../common/redis_factory').pool;
var ItemModel = require('../Dao/item')();
app.get('/getData',function(req, res) {
var type = req.query.type;
var city = req.query.city;
var id = type + city;//根据参数生成id
pool.acquire(function (err, client) {//pool.acquire获取数据库连接
client.GET(id, function (err,result) {//在redis里面看看id对应的值有没存在
if(result!=null){
pool.release(client);//释放数据库连接
res.end(result);//存在,返回数据
}else{
ItemModel.findByType(type,city,function(err,data){//不存在,去mongodb里面查询
if(!err) {
var ret =JSON.stringify(data);//如果不出错,把返回的json转化为字符串
pool.acquire(function (err, client) {
client.SET(id,ret,function (err,result) {//把字符串存到redis里面
pool.release(client);//释放数据库连接
});
});
res.end(ret);//返回查询到的数据
}
else{
res.end(err);
}
});
}
}
});
});