Node.js与mongodb可以只创建一条连接以提高性能,如果出现数据连接断开,可以通过侦听“serverHeartbeatFailed”,自动重连,示例代码如下:
import { Db, MongoClient } from 'mongodb'
let client: MongoClient
let database: Db
export const init = async(interval = 2000) => {
client = new MongoClient('mongodb://localhost/tst')
try {
await client.connect()
database = client.db()
client.once('serverHeartbeatFailed', (e) => {
console.log('Database connect error will reconnect again')
setTimeout(init, interval)
})
console.log('Database connected')
} catch(e) {
console.log('Database init err will reconnect again')
setTimeout(init, interval)
}
}
回复 (0)
微信扫码 立即评论