首页 > 解决方案 > NodeJS - PostgreSQL - 池不在文件之间共享

问题描述

我有一个 PostgreSQL 池创建脚本并导出这个池以在不同的文件中使用。在一个文件中它可以正常工作,但是该池不会在其他文件中重用,并且在每个文件中我都看到创建了一个新池!有什么想法是我犯错的地方吗?我想在一个模块中创建一个池,将其导出并在许多文件中使用它,而无需克隆池实例。我只想创建一个池。任何想法都非常感谢。

parsDbsPostgres.js

// parsDbsPostgres.js
var pg = require('pg');
let mainPool = null;

function createPool(){
    const pool = new pg.Pool({
        host: 'localhost',
        port: 5432,
        user: 'user',
        password: 'password',
        database: 'database',
        max: 20,
        idleTimeoutMillis: 1000,
        connectionTimeoutMillis: 2000,
    });
    return pool;
}
function getPool(){
    if(!mainPool){
        console.log('Pool Don\'t Exists');
        mainPool = createPool();
    }else{
        console.log('Pool Exists');
        return mainPool;
    }
}
module.exports = { getPool };

而且apicontroller.js是:

// apicontroller.js
var parsDbsPostgres = require('./parsDbsPostgres.js');
try {
        var schedule = require('node-schedule');
        var s = schedule.scheduleJob('*/3 * * * * *', function () { // every 1 second
        var myPool = parsDbsPostgres.getPool();
        console.log(myPool);
        });
    }catch(err){
        console.log(err);
}

标签: node.jspostgresqlpool

解决方案


推荐阅读