让app.use()等待,直到建立到redis实例的连接



我正在编写一个依赖于redis存储的express中间件函数,以启用速率限制。这是可行的,但问题是我将redis凭据存储在谷歌云的秘密管理器中。我需要向机密管理器发出异步请求,因此redis连接的状态会有一个小延迟。

我的与redis实例连接的函数返回一个promise。当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连接建立之前执行的。在redis promise的then((-函数内部移动RateLimit代码不会导致错误,但app.use((-功能则不起作用。

我的理想解决方案是:

// 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连接?

您可以在异步函数中设置redis,并像这样使用async/await:

'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')
async function setupRedis()
try {
// connect is a promise
const conn = await Redis.connect;
// connection established
globals.redis = conn
// globals.redis contains now the connection with the redis instance
// for use in other functions, this works
// 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 (error) {
console.error("could not connect with the redis instance");
// rethrow error or whatever, just exit this function
}

setupRedis();

相关内容

  • 没有找到相关文章

最新更新