node.js - 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') 事件中抛出错误,但没有抛出错误。
解决方案
推荐阅读
- h2 - 如何在 H2 中删除数据库?
- python - Python: make a derived class into a singleton
- android - Paging 3 - 为什么我的重试页脚没有调用我的 PagingSource 的加载方法?
- sapui5 - 如何在ui5/fiori表JSONModel中进行汇总
- java - 请求范围的 bean 在 Cucumber 的 Spring 测试中不起作用
- python-3.x - 如何使用 CDK Python 通过 lambda 访问跨区域 s3 存储桶
- python - 如果已经在名称空间中,请避免重新加载 Pandas 数据帧
- qt - 未生成 JOM 文件
- ios - 旋转文本 MeshResource 使其不会被镜像
- sql - 使用 sql 使用 max 和 over 时出错