2017-10-11 24 views

回答

1

为了提高安全性,建议在连接到云数据库上的Db2时使用SSL。例如,要通过JDBC连接字符串应该是这样的:

"jdbc:db2://<Db2OnCloudServer>:50001/BLUDB:sslConnection=true;user=bluadmin;password=<Password>;enableSeamlessFailover=true;"

你可以在“服务凭据”这个字符串和凭据从云服务实例的DB2。如果您还没有在那里看到凭据,请点击“新凭据”,它们就会出现。 使用SSL的另一个好处还在于,如果出现故障转移并且您正在使用上述连接字符串,则它将无缝地重新连接,因为服务器和客户端交换备用服务器信息。

当您不使用SSL连接时,您将需要为应用程序指定其他参数以重新连接,因为从服务器发送的备用服务器信息仅用于SSL连接。要做到这一点,你可以使用一个连接字符串,如下所示:

"jdbc:db2://<DB2OnCloudServer>:50000/BLUDB:user=bluadmin;password=<Password>;enableClientAffinitiesList=1;maxRetriesForClientReroute=10;retryIntervalForClientReroute=5;clientRerouteAlternateServerName=<Db2OnCloudServer>,<Db2OnCloudServer>;clientRerouteAlternatePortNumber=50000,50000;enableSeamlessFailover=true;"

注意您将指定在同一台服务器字符串中的备用服务器。这是因为当故障转移发生时,服务器的IP将会移动,因此连接总是通过相同的IP完成。通过指定clientRerouteAlternateServerNameclientRerouteAlternatePortNumber它将覆盖从服务器返回的值,这意味着它将连接到ssl端口。

上述内容将关注到数据库的实际连接,但是您的应用程序还需要具有适当的重试逻辑。下面是一个显示使用情况的粗略代码示例: import java.sql。*;

public class JDBCSampleEx { 

    public static void main(String args[]) { 

     String connectionURL = "jdbc:db2://169.48.134.122:50000/BLUDB:user=bluadmin;password=MmM5OWQ3ZWUyZmNm;enableClientAffinitiesList=1;maxRetriesForClientReroute=10;retryIntervalForClientReroute=5;clientRerouteAlternateServerName=169.48.134.122,169.48.134.122;clientRerouteAlternatePortNumber=50000,50000;enableSeamlessFailover=true;"; 
     Connection con = null; 

     try { 

      // Load the JCC Driver class (db2jcc4.jar). 
      Class.forName("com.ibm.db2.jcc.DB2Driver"); 

      //Create the connection using the static getConnection method 
      con = DriverManager.getConnection(connectionURL); 

      Statement stmt = con.createStatement(); 
      ResultSet rs = null; 
      con.setAutoCommit(false); 
      try { 
       rs = stmt.executeQuery("select FIRSTNME, SALARY from EMPLOYEE"); 
       // Print results 
       while (rs.next()) { 
        System.out.println("Name= " + rs.getString("FIRSTNME") + " SALARY= " + rs.getString("SALARY")); 
       } 
       // do a random update 
       String sql = "update EMPLOYEE set FIRSTNME = '" + RandomAlphaNum.gen(10) + "'"; 
       stmt.executeUpdate(sql); 
       con.commit(); 
      } catch (java.sql.SQLException e) { 
       //Catch return code to do any retry 
       if (e.getErrorCode() == -30108 || e.getErrorCode() == -4498 || e.getErrorCode() == -4499) { 
        // Add any logic to reply the current in flight transaction 
        // if necessary 
        System.out.println("Replay any transactions if necessary"); 
       } else { 
        throw e; 
       } 
      } 
     } catch (SQLException e) { 
      e.printStackTrace(); 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } finally { 
      try { 
       if (con != null) { 
        con.close(); 
       } 
      } catch (Exception e) { 
       e.printStackTrace(); 
      } 
     } 
    } 
} 
相关问题