简体   繁体   中英

Share a database connection pool between sequelize and pg

I have a server which I've written using Express and node-postgres (pg). It creates its own DB pool:

const dbPool = new pg.Pool(dbConfig);

and runs SQL queries directly using this connection.

Now I'm adding a new table and corresponding REST API. I'd like to use sequelize and epilogue to reduce the boilerplate. Unfortunately, sequelize wants to create its own database connection pool:

const sequelize = new Sequelize(database, user, password, config);

Is it possible to re-use the existing connection pool or otherwise share it between my existing pg code and my new sequelize code?

Sequelize does not offer the option to pass a custom pool, but you can pass options that will get used to create the sequelize pool, such as min and max connections.

What I would do in your case is to check your total DB connection count, and make a repartition based on the expected usage of your two pools.

For example if you have 20 connections max on your database:

const dbPool = new pg.Pool({
  max: 10
});

const sequelize = new Sequelize(/* ... */, {
  // ...
  pool: {
    max: 10,
    min: 0,
    acquire: 30000,
    idle: 10000
  }
});

I would also suggest using environment variables to set the max connection on your sequelize pool and nod-pg pool, so that you could adapt easily your repartition if needed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM