Node.js Redis 服务器关闭时,Redis 客户端获取方法错误

Node.js Redis client get method error when Redis server is down

我正在使用 node-redis 版本 3.0.2。但是,我正在检查如果 Redis 服务器出现故障,我的网站将如何响应。我有这个请求处理程序,它调用一个函数,首先检查提供的密钥是否在 Redis 中,否则进行数据库调用,然后将获取的数据保存在 Redis 中。

const GetByPriority = model => async (req, res) => {
    let { page=1, size=9 } = req.query;
    size = parseInt(size);
    page = parseInt(page);
    try {
        const doc = await SetOrGetCompanyCache(`companies-${page}-${size}`, async () => {
            const query = await model
                .find({})
                .limit(size*1)
                .skip((page-1)*size)
                .sort({ p: -1, _id:1 })
                .lean()
                .exec()
            return query;
        })
        if (!doc)
        {
            return res.status(404).end()
        }
        res.status(200).json({page:page, size:size, data: doc })
    } catch (e) {
        console.error(e)
        res.status(400).end()
    }
}

问题是当 Redis 服务器关闭时,return似乎没有错误 redisClient 的 get 方法。我的意思是我不明白为什么它没有记录错误。另外,它没有 return InternalServerError.

export function SetOrGetCompanyCache (key, callback) {
    return new Promise((resolve, reject)=>{
        redisClient.get(key, async (error,data)=>{
            if(error)
            {
                console.log(error) //It does not get here
                return reject(createError.InternalServerError('Caching Error'))
            }
            //Cache hit
            if(data != null)
            {
                return resolve(JSON.parse(data))
            }
            //Cache miss
            //callback() --> MongoDB query
            const queryData = await callback();
            if(!queryData)
            {
                return reject(createError[404])
            }
            redisClient.setex(key,COMPANY_QUERY_EXP,JSON.stringify(queryData))
            resolve(queryData)
        })
    })
}

它只记录了以下片段

Redis connection to 127.0.0.1:6379 failed - connect ECONNREFUSED 127.0.0.1:6379
Redis connection to 127.0.0.1:6379 failed - connect ECONNREFUSED 127.0.0.1:6379
Redis connection to 127.0.0.1:6379 failed - connect ECONNREFUSED 127.0.0.1:6379

我相信这是因为我在 redisClient 文件中添加了以下侦听器

redisClient.on('error', (err)=>{
    console.error(err.message)
})

现在的问题是 set 方法没有 return 任何指示 Redis 服务器已关闭的错误,因此我什至无法让服务器执行正常的数据库调用案例.

我在 discord 上询问了 redis 社区,他们提到我应该在 redis-client

中将 enable-offline-queue 设置为 false

应该是这样的

export const redisClient  = createClient({
    port: process.env.REDIS_PORT,
    host: process.env.REDIS_HOST,
    //In order to turn off queuing commands and get an error if we couldn't connect to the redis server
    enable_offline_queue: false
});

正如他们所说

In Node Redis, if you handle add the on('error') stuff it will queue up your commands and then in the background try to reconnect. When it does reconnect, it will then run the queued commands. [7:30 PM] It actually follows a retry_strategy to attempt to reconnect. You can read all about it on the old README at https://www.npmjs.com/package/redis/v/3.1.2 npm redis A modern, high performance Redis client. Latest version: 4.0.4, last published: 24 days ago. Start using redis in your project by running npm i redis. There are 8235 other projects in the npm registry using redis.

[7:31 PM] You need to set the enable_offline_queue option to false to turn off this queueing and get an error.