我正在开发一个Koa + Mongodb后端。我的问题是:我什么时候应该关闭数据库,或Mongodb管理它,因为我现在没有关闭它们,看起来很好。
// app.js
const Koa = require('koa')
const database = require('./database')
const app = new Koa()
database
.connet()
.then(() => {app.listen(':8080')})
.catch((err) => {console.error(err)})
// ./database.js
const MongoClient = require('mongodb').MongoClient
const Model = require('./model')
class Database {
async connect() {
if (!db) {
db = await MongoClient.connect("localhost:27017")
this.item = new Model(db, 'item_collection')
}
}
}
module.exports = new Database()
// ./model.js
class Model {
constructor(db, collectionName) {
this.name = collectionName
this.database = database
}
async findAll() {
const result = await this.db.collection(this.name).find().toArray()
if (!result) {
throw new Error('error')
}
return result
}
}
module.exports = Model

我还使用vegeta进行压力测试,以100请求/秒向服务器发出API请求,响应时间很长。那么,我担心这里的过早优化吗?如果没有,我应该何时关闭数据库?
答案 0 :(得分:1)
当Koa继续运行时(在你的情况下监听端口8080)你应该 不 关闭数据库连接。
如果您正在运行预期结束的脚本(在cron上运行的任务等),则应在完成所有数据库任务后手动关闭连接。
您可以查看this example表达express.js(Koa姊妹框架)