如我之前提到的问题,我正在尝试学习如何使用sails.js,在尝试将api的响应缓存到redis中。我已经搜索了如何做到这一点,但是我无法让它起作用。在没有缓存的情况下,我通过ajax调用api。
您有什么想法可以让我如何在控制器中调用api并使用redis缓存响应?
您可以使用https://github.com/mranney/node_redis
步骤:
"redis": "^0.12.1"
npm install
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
});
});