简体   繁体   中英

JAVA + Postgres Limit connections , how to close it ! FATAL: sorry, too many clients already

I need to release connection to postgres

My java application interact with postgres and my problem is when i need to call this function more than 200 time postgres crashes , normal thing ... because postgres have limited connections and this script leave a connection opened everytime it execute.

@Override
    public Object[] getExtrasInfosSource(int idSource) {
    StringBuffer sql = new StringBuffer();
        final SessionFactoryImplementor sfi = (SessionFactoryImplementor) getSessionFactory();
        final Settings settings = sfi.getSettings();
        // Appel du procedure stocké "getExtrasInfosForSource(idSource integer)" au niveau de bd
        sql.append("SELECT * from "+settings.getDefaultSchemaName()+".getExtras_Infos_For_Source(:idSource)");
        SQLQuery query = this.getSession().createSQLQuery(sql.toString());
        query.setInteger("idSource", idSource);
        return (Object[]) query.setMaxResults(1).uniqueResult();...

Can you please tell me how to close the connection opened in postgres from this script to avoid the app crash everytime postgres connections is over loaded.

According to Hibernate's javadocs you can call .close() on a session.

close()

End the session by releasing the JDBC connection and cleaning up.

Before returning your query results: this.getSession().close();

I have solved this issue by adding those variables to my server config , it refresh the IDLE connections (or so) opened left in postgresql

<?xml version="1.0" encoding="utf-8"?>
<Context>
    <Resource name="jdbc/database"
              auth="Container"
              type="javax.sql.DataSource"
              driverClassName="org.postgresql.Driver"
              url="jdbc:postgresql://localhost:5432/DBA"
              username="DBA"
              password="DBA"
              initialSize="34"
              maxActive="80"
              maxIdle="5"

              timeBetweenEvictionRunsMillis="1000"
              minEvictableIdleTimeMillis="2000"
              validationQuery="SELECT 1"
              validationInterval="3000"
              testOnBorrow="true"
              removeAbandoned="true"
              removeAbandonedTimeout="3"/>  

</Context>

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