【问题标题】:connection timeout when connecting to a remote postgresql database连接到远程 postgresql 数据库时连接超时
【发布时间】:2011-06-22 17:11:22
【问题描述】:

我面临这个问题:我有一个循环以下内容的程序:

  • 连接到 postgresql 数据库
  • 打印计数
  • 关闭连接

代码如下:

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++);
        }
    }

我通过 jdbc 连接到 psql db,如下所示:

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

conn.connect() 如果可以成功连接到数据库则返回true (经过测试,我可以从中检索数据)

但我得到以下结果:

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)

在最后一个循环中,程序卡在尝试连接到 psql 直到超时。有什么帮助吗?

【问题讨论】:

  • 您可以使用其他客户端如 PGAdmin 访问它吗?服务器是可访问的?
  • 每次迭代都打开和关闭连接的任何原因?
  • @Jigar Joshi 我可以在第一个 3xxx 连接上成功查询
  • @Vineet Reynolds 这只是一个模拟

标签: java postgresql jdbc


【解决方案1】:

与异常消息host or/and port where postgres is running not equals to the host or/and port what you put to the connect address有关,检查一下就会发现问题。


是的,你的服务器无法访问,一些防火墙等等,也检查一下。

【讨论】:

  • 我确定第一个 3xxx 连接可以访问服务器。我可以在数据库上查询并成功获得结果。问题是在打开和关闭数千个连接后它以某种方式无法连接
  • 你能看看服务器端的轮询连接,我的意思是有多少连接是从服务器打开而不是关闭的?
  • @Sergii Zagriichuk 这是我第一次使用 postgresql,我不熟悉它。我不知道如何检查 psql 的现有连接。有什么帮助吗?
  • 一秒钟,我会努力记住 :) 然后写。
  • 尝试下一个 sql 查询 SELECT * FROM pg_stat_activity;
猜你喜欢
  • 2015-11-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多