MySQL连接错误分析
错误描述
应用程序在尝试连接MySQL数据库时遇到了通信链路故障。错误日志如下:
Caused by: com.mysql.cj.exceptions.CJCommunicationsException: Communications link failure
The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
… [其他堆栈信息] …
Caused by: java.net.UnknownHostException: 不知道这样的主机。 (mysql)
… [更多堆栈信息] …
根本原因
错误发生的原因是 application.yaml
配置文件中指定的MySQL服务器主机名不正确。配置如下:
server:
port: 8089
spring:
datasource:
url: jdbc:mysql://mysql:3306/heima?useSSL=false
username: root
password:
driver-class-name: com.mysql.cj.jdbc.Driver
解决方案
修改 application.yaml 文件中的数据库URL,将 mysql 改为 localhost:
spring:
datasource:
url: jdbc:mysql://localhost:3306/heima?useSSL=false
...
更改后重启应用程序,这应该解决通信链路故障的问题。