2016-11-07 17 views
1

我有一个小型测试应用程序,它使用主服务器(10.200.0.50)和备用服务器(10.200.0.51)对Postgresql群集进行查询。当应用程序连接到主服务器不可用时,我希望应用程序重新署名到备用服务器。在Java应用程序中使用jdbc字符串错误的PostgreSQL连接故障转移

我跟着文档从这里最后一节:)

public static void main(String[] args) { 

    Scanner s = new Scanner(System.in); 
    Statement stmt = null; 
    Connection c = null; 
    try { 
     Class.forName("org.postgresql.Driver"); 
     c = DriverManager 
     .getConnection("jdbc:postgresql://10.200.0.50,10.200.0.51:5432/replicationtest", 
      "postgres", "password");    

     stmt = c.createStatement(); 

     ResultSet rs = stmt.executeQuery("SELECT * FROM testtable;"); 
     while(rs.next()) { 
      String name = rs.getString("name"); 
      System.out.println(name); 
     } 
     rs.close(); 

     int choice = s.nextInt(); 

     ResultSet rs2 = stmt.executeQuery("SELECT * FROM testtable"); 
     while(rs2.next()) { 
      String name = rs2.getString("name"); 
      System.out.println(name); 
     } 
     rs2.close(); 
     c.close(); 

    } catch (Exception e) { 
     e.printStackTrace(); 
     System.err.println(e.getClass().getName()+": "+e.getMessage()); 
     System.exit(0); 
    } 
    s.close(); 
} 

方案主服务器10.200.0.50是向下和备用服务器 10.200.0.51: https://jdbc.postgresql.org/documentation/head/connect.html

到目前为止,我有这个已经结束。

这个伟大的工程,有起初有点延迟,但应用程序将使用在JDBC字符串

方案B)中规定的第二个服务器主要和备用服务器,当我运行应用程序。但是在第一个查询之后,应用程序在nextInt()上等待的位置之后,我将连接阻塞到10.200.0.50;在连接成功后模拟主要失败。

当我运行方案B,然后调用第二个查询我得到的错误:

org.postgresql.util.PSQLException: An I/O error occurred while sending to the backend. 
at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:317) 
at org.postgresql.jdbc.PgStatement.executeInternal(PgStatement.java:432) 
at org.postgresql.jdbc.PgStatement.execute(PgStatement.java:358) 
at org.postgresql.jdbc.PgStatement.executeWithFlags(PgStatement.java:305) 
at org.postgresql.jdbc.PgStatement.executeCachedSql(PgStatement.java:291) 
at org.postgresql.jdbc.PgStatement.executeWithFlags(PgStatement.java:269) 
at org.postgresql.jdbc.PgStatement.executeQuery(PgStatement.java:236) 
at com.rakuten.pgRecovery.Main.main(Main.java:59) 
Caused by: java.net.SocketTimeoutException: Read timed out 
at java.net.SocketInputStream.socketRead0(Native Method) 

回答

0

想通了,我需要的时候读取失败来包装我的查询在尝试捕捉和捕获的错误。之后,我需要打开一个新的连接,它将在传递的节点上进行轮循,从而获得良好的连接,如方案A