我一直致力于为我的 Nodejs 应用程序设置缓存服务器。 下面是我正在做的项目。简单的一个。
我有一个外部 API,它为我提供 GET 请求的 JSON 响应。 我想将这些键和 JSON(值)存储在 Redis 缓存服务器中。我有能力做到这一点。
现在,当调用 GET 请求时,它会到达我的 Node URL --> 外部 API <-- JSON 作为响应(存储在缓存中)。
对于下一个请求,如果相同的 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;
记录错误并且不创建异常。
关于javascript - 如何从nodejs检查Redis缓存连接状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58187213/