node.js - 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);
}
解决方案
推荐阅读
- javascript - 为什么这个级联下拉列表中的第三个和第四个框没有 javascript 没有填充?
- websphere - Websphere 8.5 重新启动会破坏 classLoader 代码
- validation - 在 symfony 3 中没有调用验证器时要检查什么?
- python - 如何存储和使用数学运算符作为 python 变量
- java - 如何在 Spring 框架中修复 UnsatisfiedDependencyException
- c# - C# 泛型 - 有人可以解释这个签名吗
- graph - 查找长度 = 4 的路径,从有向图的邻接矩阵开始,只考虑不同的边?
- android - 首先从firebase实时数据库中检索新项目
- javascript - 如何将预览图像的位图发送到控制器?
- html - 如何从 Angular 5.2 的 IFrame 中引用 CSS(从 SCSS 编译)?