where to destroy knex connection

前端 未结 3 1851
北海茫月
北海茫月 2021-02-14 20:54

I\'m using knex with pg.

I have a project similar as following.

dbClient.js

const dbClient = require(\'knex\')({
  client: \'pg\',
  connection:          


        
3条回答
  •  长情又很酷
    2021-02-14 21:44

    Knex destroy() seems to be a one time operation. After destroying a connection, one might require a brand new connection pool for the next operation.

    The db client module you export is cached into node module cache and a new connection pool is not created every time you require it.

    This is intended usage, the pool is supposed to be destroyed when app exits or all the tests are done. If you have reasons to create/destroy connections for every operation ( like in serverless environment) you should not reuse the destroyed client, rather create a new instance every time.

    Otherwise, it defeats the purpose of connection pooling.


    Update about lambda/server-less environments:

    Technically a function and its resources are to be released after the lambda function has run, this includes any connections it might have opened. This is necessary for truly stateless functions. Therefore it is advisable to close connection when function is done. However, a lot of functions opening/closing a lot of connections may eventually make the DB server run out of connections (see this discussion for example). One solution might be to use an intermediate pool like PgBouncer or PgPool that negotiates connections between DB server and Lambda functions.

    The other way is for the platform provider (AWS) to add special pooling capabilities to lambda environment and let them share long-lived resources.

提交回复
热议问题