简体   繁体   中英

connection timeout when connecting to a remote postgresql database

I am facing this problem: I have a program that loops the following:

  • connect to a postgresql database
  • print a count number
  • close the connection

code is as follow:

int i = 0;
    while(true){

        IConnection conn = ((ConnectionHelper)HelperFactory.getInstance().getHelper("ConnectionHelper")).getConnection("psql");

        if(conn != null && conn.connect()){
            conn.close();
            System.out.println(i++);
        }
    }

I connect to psql db by jdbc, something like this:

DriverManager.getConnection("jdbc:postgresql://" + host + ":5432/" + database, 
                                            user, password);

the conn.connect() returns true if it can successfully connect to the database (tested, I can retrieve data from it)

But i get the following result:

0 1 2 . . . 3919 3920 3921 3922

org.postgresql.util.PSQLException: Connection refused. Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections.
    at org.postgresql.core.v3.ConnectionFactoryImpl.openConnectionImpl(ConnectionFactoryImpl.java:136)
    at org.postgresql.core.ConnectionFactory.openConnection(ConnectionFactory.java:66)
    at org.postgresql.jdbc2.AbstractJdbc2Connection.<init>(AbstractJdbc2Connection.java:125)
    at org.postgresql.jdbc3.AbstractJdbc3Connection.<init>(AbstractJdbc3Connection.java:30)
    at org.postgresql.jdbc3g.AbstractJdbc3gConnection.<init>(AbstractJdbc3gConnection.java:22)
    at org.postgresql.jdbc4.AbstractJdbc4Connection.<init>(AbstractJdbc4Connection.java:30)
    at org.postgresql.jdbc4.Jdbc4Connection.<init>(Jdbc4Connection.java:24)
    at org.postgresql.Driver.makeConnection(Driver.java:393)
    at org.postgresql.Driver.connect(Driver.java:267)

at the last loop the program stuck at trying to connect to psql til timeout. Any help?

Related to the exception message host or/and port where postgres is running not equals to the host or/and port what you put to the connect address, check it and you will find problem.


And yes, your server cannot be reachable, some firewals and so on, check it too.

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