Sails JS 与 Redis 缓存
Sails JS with Redis for caching
正如我在之前的问题中所说,我正在尝试学习如何使用sails.js,我现在正在尝试做的是将api的响应缓存到redis。我已经搜索了如何执行此操作,但无法正常工作。没有缓存,我通过 ajax 调用 api。
关于我将如何使用我的控制器做到这一点有什么想法吗?如何使用 sails.js 中的控制器调用 api 并使用 redis 缓存响应?
您可以使用https://github.com/mranney/node_redis
步骤:
添加到package.json
"redis": "^0.12.1"
运行
npm install
创建服务模块/api/services/CachedLookup.js
var redis = require("redis"),
client = redis.createClient();
module.exports = {
rcGet: function (key, cb) {
client.get(key, function (err, value) {
return cb(value);
});
},
fetchApi1: function (cb) {
var key = 'KEY'
CachedLookup.rcGet(key, function (cachedValue) {
if (cachedValue)
return cb(cachedValue)
else {//fetch the api and cache the result
var request = require('request');
request.post({
url: URL,
form: {}
}, function (error, response, body) {
if(error) {
//handle error
}
else {
client.set(key, response);
return cb(response)
}
});
}
});
}
}
控制器内部
CachedLookup.fetchApi1(function (apiResponse) {
res.view({
apiResponse: apiResponse
});
});
正如我在之前的问题中所说,我正在尝试学习如何使用sails.js,我现在正在尝试做的是将api的响应缓存到redis。我已经搜索了如何执行此操作,但无法正常工作。没有缓存,我通过 ajax 调用 api。
关于我将如何使用我的控制器做到这一点有什么想法吗?如何使用 sails.js 中的控制器调用 api 并使用 redis 缓存响应?
您可以使用https://github.com/mranney/node_redis
步骤:
添加到package.json
"redis": "^0.12.1"
运行
npm install
创建服务模块/api/services/CachedLookup.js
var redis = require("redis"),
client = redis.createClient();
module.exports = {
rcGet: function (key, cb) {
client.get(key, function (err, value) {
return cb(value);
});
},
fetchApi1: function (cb) {
var key = 'KEY'
CachedLookup.rcGet(key, function (cachedValue) {
if (cachedValue)
return cb(cachedValue)
else {//fetch the api and cache the result
var request = require('request');
request.post({
url: URL,
form: {}
}, function (error, response, body) {
if(error) {
//handle error
}
else {
client.set(key, response);
return cb(response)
}
});
}
});
}
}
控制器内部
CachedLookup.fetchApi1(function (apiResponse) {
res.view({
apiResponse: apiResponse
});
});