1. 程式人生 > >如何解決Java通過JDBC訪問MySQL時SSL連線告警問題

如何解決Java通過JDBC訪問MySQL時SSL連線告警問題

背景

MySQL 5.5.45+, 5.6.26+, 5.7.6+開始支援SSL連線,如果沒有明確設定相關的選項時,預設要求SSL連線。為相容性考慮,舊應用程式需要設定verifyServerCertificate和useSSL屬性。MySQL連線時給出的告警資訊也清楚的給出了原因和處理方案。
Establishing SSL connection without server's identity verification is not recommended. 
According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be 
established by default if explicit option isn't set. For compliance with existing applications 
not using SSL the verifyServerCertificate property is set to 'false'. You need either to 
explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide 
truststore for server certificate verification.

方案1: 在URL中設定相關屬性

	static {
		try {
			Class.forName("com.mysql.jdbc.Driver");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public Connection getConnection() throws SQLException {
		String url = "jdbc:mysql://localhost:3306/db_hibernate?verifyServerCertificate=false&useSSL=false";
		String user = "root";
		String password = "infinera";
		
		return DriverManager.getConnection(url, user, password);
	}

方案2: 通過Properties屬性設定

	static {
		try {
			Class.forName("com.mysql.jdbc.Driver");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public Connection getConnection() throws SQLException {
		String url = "jdbc:mysql://localhost:3306/db_hibernate";
		String user = "root";
		String password = "infinera";
		
		Properties properties = new Properties();
		
		properties.setProperty("user", "root");
		properties.setProperty("password", "infinera");
		properties.setProperty("useSSL", "false");
		properties.setProperty("verifyServerCertificate", "false");
		
		return DriverManager.getConnection(url, user, password);
	}