当数据库不可用时禁止路由(优雅地 "关闭")。

问题描述 投票:0回答:1

我正在用nodejs构建一个依赖于redis、postgresql和mongodb的web服务器。我把所有的证书都存储在google cloud secret manager中,所以我必须使用异步函数来获取它们。到目前为止,我的代码。

// Redis.js

const { accessSecretVersion } = require('./google_cloud/secret-manager')

const Redis = require('redis')

// initialize connection (promise because accessSecretVersion is an async function)
const initialize = new Promise(async (resolve, reject) => {
    const redis = Redis.createClient({
        host: await accessSecretVersion('redis_host'),
        port: 6379
    })

    redis.on('error', err => reject(err))

    redis.on('connect', () => resolve(redis))    
}) 

module.exports = {
    initialize
}

// App.js

'use strict'

const express = require('express')

const app = express()

const bodyParser = require('body-parser')

app.use(bodyParser.json())

const Redis = require('./redis')

let redis

// try to initialize a connection
// then => it works!
// catch => it does not work!
Redis.initialize.then(redis => {
    redis = redis
    console.log('redis available')
}).catch(err => console.log(err))

// further on, other stuff rely on 'redis'
// if 'redis' is undefined, they crash, but I want a graceful "shutdown" of the functions

// here, the emitter relies on 'redis'
// the problem is, this code is ran BEFORE the redis connection 
// has established, so it returns an empty
// (when this code runs, 'redis' is still undefined)
const Io = require('./components/socket_io/emitter')(redis)

如你所见,在app.js中,我尝试创建一个redis连接。如果成功(在redis.js中resolve),"let redis "被设置为redis连接。如果不成功(拒绝),我就在控制台中记录错误。

问题是,这段代码下来的其他一些函数都依赖于redis连接,比如socket.io-redissocket.io-emitter。

我想实现什么?

如果redis服务器宕机,我想发送一个全局状态码503(服务不可用),无论请求什么路由。服务器不应该崩溃,但应该无法到达,因为我的服务器中的很多功能都依赖于redis数据库中的数据,如果没有这些数据,我不希望人们做的东西。

这可能不是我所做的最好的方法+发送一个 "全局 "错误503是一个好主意,还是检查每个不同的路由更好?

node.js redis node-redis
1个回答
1
投票

理想的情况下,它应该由你的Infra来处理。

在应用程序级别,实现一个健康检查路线,并在那里做你的逻辑。例如:如果mysql或redis是下来,返回500错误。Infra将看到这个错误,并停止路由流量到该实例服务器容器。

© www.soinside.com 2019 - 2024. All rights reserved.