let app.use()等待连接到redis示例

vvppvyoh  于 2021-06-09  发布在  Redis
关注(0)|答案(1)|浏览(397)

我正在编写一个依赖于redis商店的express中间件函数,以启用速率限制。它可以工作,但问题是我将redis凭证存储在googlecloud的secretmanager中。我需要对secretmanager做一个异步请求,所以redis连接的状态有一个小的延迟。
我连接redis示例的函数返回一个承诺。当承诺完成时,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 promises的then()-函数中移动ratelimiter代码不会导致错误,但是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连接?

mhd8tkvw

mhd8tkvw1#

您可以在异步函数中设置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();

相关问题