首页 > 解决方案 > NodeJs Redis(缓存)错误处理 - 如何忽略错误?

问题描述

目前我有一个 cache.js 文件来启动 Redis,以便重用连接。

缓存.js

 const redis = require('redis');
const { promisify } = require("util");


const client = redis.createClient({ host: process.env.REDIS_HOST, port: process.env.REDIS_PORT, password: process.env.REDIS_PASSWORD })

client.on('error', function(err) {
    console.log('error encountered', err.toString())
    return null
});


const getAsync = promisify(client.get).bind(client);
const setAsync = promisify(client.set).bind(client);
const setexAsync = promisify(client.setex).bind(client);
module.exports = { getAsync, setAsync, setexAsync }

我如何使用它。

try {
    const redis = require('lib/cache')
    const results = await redis.getAsync(key)
    if (results) {
        return res.json(JSON.parse(results));
    }

} catch(err) {
    console.log('redis error => ', err) //this is not important, I want to proceed to get data from db.
}
....... continue codes to get data from database since there's no cache.

这一切都运行良好,直到出现错误(例如 Redis 服务器关闭、与 Redis 的连接不可用、密码错误等),并且节点应用程序卡住了。

它不会继续,在它 console.log 由 .on('error') 发出的事件返回错误之后。

我想要的是。 因为我把它用作缓存,所以我希望它继续服务并从数据库返回数据,而忽略缓存。redis 缓存的可用性在我的应用程序中并不重要。

我怎样才能达到我想要的?

我尝试在发出事件中返回 null 但不工作,我还尝试从 .on('error') 事件中抛出错误,但没有抛出错误。

标签: node.jsredis

解决方案


推荐阅读