【发布时间】:2020-04-24 11:00:13
【问题描述】:
我正在编写一个依赖于 redis 存储的快速中间件函数,以启用速率限制。它有效,但问题是我将我的 redis 凭据存储在谷歌云的秘密管理器中。我需要向 secret-manager 发出 异步 请求,因此 redis 连接的状态会有一点延迟。
我与 redis 实例连接的函数返回一个承诺。当 promise 完成后,redis 连接就建立了。
'use strict'
// global variables for use in other functions as well
let globals = {}
// redis component where the connection with the redis instance is established
const Redis = require('./components/redis')
// connect is a promise
Redis.connect.then(conn => {
// connection established
globals.redis = conn
// globals.redis contains now the connection with the redis instance
// for use in other functions, this works
}).catch(err => console.log('could not connect with the redis instance')
// rate limiter function which depends on a redis instance
const RateLimiter = require('./components/rate-limiter')
const rateLimiter = RateLimiter({
store: globals.redis,
windowMs: 60 * 60 * 1000,
max: 5
})
app.use(rateLimiter)
此代码将不起作用,因为 app.use(ratelimiter) 是在 redis 连接建立之前执行的。将 RateLimiter 代码移入 redis promise 的 then()-function 不会导致错误,但 app.use()-function then 不起作用。
我理想的解决方案是:
// connect is a promise
Redis.connect.then(conn => {
// connection established
globals.redis = conn
// globals.redis contains now the connection with the redis instance
// for use in other functions, this works
// <-- MOVING THE RATE LIMITER CODE INSIDE THE THEN()-FUNCTION
// DOES NOT WORK / THE MIDDLEWARE IS NOT USED -->
// rate limiter function which depends on a redis instance
const RateLimiter = require('./components/rate-limiter')
const rateLimiter = RateLimiter({
store: globals.redis,
windowMs: 60 * 60 * 1000,
max: 5
})
app.use(rateLimiter)
}).catch(err => console.log('could not connect with the redis instance')
如何让 app.use() '等待'直到有 redis 连接?
【问题讨论】:
标签: node.js express redis node-redis