Cause: org.springframework.jdbc.CannotGetJdbcConnectionException: Failed to obtain JDBC Connection;

报错内容如下:
Error querying database. Cause: org.springframework.jdbc.CannotGetJdbcConnectionException: Failed to obtain JDBC Connection; nested exception is com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure

SpringBoot 项目的 application.yml 如下:

spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8
    username: root
    password: xxx

原因分析:

  • 由于我使用的 Mysql 的版本是 5.7,而在配置 数据库的 url 的时候,没有设置 useSSL=false,所以报了 Communications link failure (通信链路错误),获取不到 JDBC 连接的错误。
  • 根据MySQL 5.5.45+、5.6.26+和5.7.6+的要求,如果不设置显式选项,则必须建立默认的SSL连接。所以需要通过设置 useSSL=false 来显式禁用SSL,或者设置 useSSL=true 并为服务器证书验证提供信任存储。

解决:修改一下 url 即可

spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false
    username: root
    password: xxx

连接Mysql数据库时在 url 后面加上 useSSL=false 的作用
SSL协议提供服务主要:

  1. 认证用户服务器,确保数据发送到正确的服务器;    .
  2. 加密数据,防止数据传输途中被窃取使用;
  3. 维护数据完整性,验证数据在传输过程中是否丢失;

当前支持SSL协议两层:

SSL记录协议(SSL Record Protocol):

  • 建立靠传输协议(TCP)高层协议提供数据封装、压缩、加密等基本功能支持

SSL握手协议(SSL Handshake Protocol):

  • 建立SSL记录协议用于实际数据传输始前通讯双进行身份认证、协商加密
    算法、 交换加密密钥等。

不建议在没有服务器身份验证的情况下建立SSL连接。根据MySQL 5.5.45+、5.6.26+和5.7.6+的要求,如果不设置显式选项,则必须建立默认的SSL连接。需要通过设置useSSL=false来显式禁用SSL,或者设置useSSL=true并为服务器证书验证提供信任存储。

1.true 需要连接
2.false 不需要连接

所以建议设置useSSL为false,有时遇到的问题可以这样来考虑

jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false

连接Mysql数据库时在 url 后面加上 useSSL=false 的作用,来自:https://www.cnblogs.com/mihutao/p/15963259.html

你可能感兴趣的:(报错记录,mysql,数据库)