java.sql.SQLNonTransientConnectionException:无法连接到地址=(host=<host>)(port=<port>)(type=master):连接被拒绝
java.sql.SQLNonTransientConnectionException: Could not connect to address=(host=<host>)(port=<port>)(type=master): Connection refused
ID: java/sql-non-transient-connection-exception
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| MySQL Connector/J 8.0.33 | active | — | — | — |
| PostgreSQL JDBC 42.7.1 | active | — | — | — |
| HikariCP 5.1.0 | active | — | — | — |
根因分析
JDBC驱动程序无法建立到指定数据库主机和端口的TCP连接,通常是因为数据库服务器未运行、端口被防火墙阻止或主机名不可达。
English
The JDBC driver cannot establish a TCP connection to the specified database host and port, typically because the database server is not running, the port is blocked by a firewall, or the hostname is unreachable.
官方文档
https://dev.mysql.com/doc/connector-j/8.0/en/connector-j-usagenotes-connect-driver-manager.html解决方案
-
Verify the database server is running and listening on the expected port. On Linux: `sudo netstat -tulpn | grep <port>`. On Windows: `netstat -ano | findstr :<port>`. If not listening, restart the database service.
-
Check firewall rules on both host and network level. Temporarily disable the firewall for testing: `sudo ufw disable` (Linux) or `netsh advfirewall set allprofiles state off` (Windows). Re-enable after testing and add an allow rule for the database port.
-
Test connectivity using telnet or nc from the application server: `telnet <host> <port>` or `nc -zv <host> <port>`. If the connection fails, check DNS resolution with `nslookup <host>` and ensure the hostname resolves to the correct IP.
无效尝试
常见但无效的做法:
-
Increase connection timeout in JDBC URL (e.g., connectTimeout=60000)
95% 失败
Timeout only affects how long the driver waits for a response; if the server is down or port is closed, timeout does not help. The connection will still fail after the extended timeout.
-
Change the JDBC driver version to an older one
90% 失败
The error is a network-level issue, not a driver compatibility problem. Changing the driver version does not affect TCP connectivity to the database server.
-
Add useSSL=false to the JDBC URL
85% 失败
SSL configuration is irrelevant when the initial TCP connection cannot be established. The connection refusal happens before any SSL handshake.