express mongodb 连接池

因为网络上虽然有mongodb nodejs 连接池的教程,但是用的是已经过时的api,所以想出这个方法,分享一下

需要基础的express的知识http://www.expressjs.com.cn/

使用的是官方的mongodb驱动和generic-pool

npm install --save mongodb generic-pool

当然我写的也是按照官方问档来写的,如果头比较铁的也可以直接去看(滑稽),这里给出链接,看完文章后也可以看一下官方文档

https://www.npmjs.com/package/generic-pool

https://docs.mongodb.com/ecosystem/drivers/node/

毕竟我写的博客也是中文的嘛。。。

创建连接池代码:

const MongodbClient = require('mongodb').MongoClient;
const GenericPool = require('generic-pool');


const factory = {

    create: function() {//创建链接
    return MongodbClient.connect("mongodb://" + "localhost" + ":" + "27017", { useUnifiedTopology: true });
    //返回一个mongodb的client链接对象 }, destroy:
function(client) {//销毁链接 client.close();//关闭链接,这里需要注意,形参client就是上面我们创建的对象 } } // const opts = { max: 10,//最大链接数 min: 2//最小。。 } const myPool = GenericPool.createPool(factory, opts);//就是在这里创建链接池 module.exports = myPool;//export给其他模块使用

 创建factory对象和opt对象,分别表示创建和销毁的方法 与 选项

使用方法,在这里我是使用了express的route,创建了一个路由user,当然这是express的知识,不讨论:

const express = require('express');
const Router = express.Router();
const myPool = require('./db_pool');//这里的db_pool就是上面的代码文件

Router.get('/user', (req, res, next) => {
    var name = req.query.name || '';//获得查询的参数

    var queryObject = {}
    if (name != '') {
        queryObject.name = name;
    }

    var resoursePro = myPool.acquire();//在这里请求一个连接池的连接,它返回的是一个promise对象,如果不明白的给个链接:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Promise
    resoursePro.then((client) => {     //这里的client就是上面我们在factory对象中create的返回值
        let cursor = client.db('dbname').collection('user').find(queryObject);//下面使用的就是常规操作啦,因为主要讲的连接池,就懒得写了...
        let somethign = cursor.toArray();
        somethign.then((result) => {
            // console.log(result);
            res.json(result);//响应查询的结果
            myPool.release(client).then(() => {//使用完了这个链接就要归还了啊
                console.log('release')
            });
        }).catch((err) => {
            myPool.release(client).catch((err) => {
                console.log(err)
            })
        })
    })
})

猜你喜欢

转载自www.cnblogs.com/incredible-x/p/11924768.html