2016-11-07 18 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