我一直致力于为我的 Nodejs 应用程序设置缓存服务器。 下面是我正在做的项目。简单的一个。
我有一个外部 API,它为我提供 GET 请求的 JSON 响应。 我想将这些键和 JSON(值)存储在 Redis 缓存服务器中。我有能力做到这一点。
现在,当调用 GET 请求时,它会到达我的节点 URL --> 外部 API <-- JSON as response (which is stored in the cache).
对于下一个请求,如果相同的 GET 到来,它会去缓存获取键/值对。
但是在这里,如果我的缓存服务器无法访问或不可用,我必须再次访问 API 来获取值。
我尝试了如下代码,当缓存服务器关闭时它失败。如何进行 if 循环来获取 redis 缓存服务器的连接状态?
下面是我的controller.js
function getRedisCacheConnection(){
const REDIS_PORT = process.env.PORT || 6379;
const client = redis.createClient(REDIS_PORT);
client.on('connect', function() {
console.log('Redis client connected');
console.log(`${client.connected}`);
});
client.on('error', function (err) {
console.log('Something went wrong ' + err);
})
return client;
}
exports.getCityCode = (req,res)=>{
var originCity = req.query.origincity;
var originState = req.query.originstate;
function setReponse(originCity, response){
return response;
}
const options = {
method: 'GET',
uri: `http://webapi.external.com/api/v3/locations?name=${originCity}`,
headers: {
'Content-Type': 'application/json'
}
}
request(options).then(function (response){
res.status(200).send(setReponse(originCity, response));
const client1 = getRedisCacheConnection();
console.dir("setting key to Cache " + originCity);
client1.setex(originCity, 3600, response);
});
}
exports.Cache = (req,res,next) => {
const originCity = req.query.origincity;
function setReponse(originCity, response){
return response;
}
const client1 = getRedisCacheConnection();
client1.get(originCity, (err,data) =>{
if(err) throw err;
if(data !== null){
console.dir(originCity + " Getting Key from Cache");
res.status(200).send(setReponse(originCity,data));
}
else{
next();
}
});
}
这是我的router.js
app.get('/citycode/', city.Cache, city.getCityCode);
你抛出了一个错误:
if(err) throw err;
记录错误并且不要创建异常。
import { createClient } from 'redis';
const client = redis.createClient();
// within the event handlers for error and connect you could use fs module to
// write to a file the state values 'connected' & 'disconnected' then reread them
// and perform a control block statement
client.on('error', () => {
logtoFile('disconnected');
});
client.on('connect', () => {
logtoFile('connected');
});