解决MySql8报错:Public Key Retrieval is not allowed
该错误 com.mysql.cj.exceptions.UnableToConnectException: Public Key Retrieval is not allowed 是由于 MySQL 8.x 使用了新的默认身份验证插件 caching_sha2_password,而客户端没有允许从服务器获取公钥进行身份验证。
解决方案
方法一:修改数据库用户认证方式(推荐)
将 MySQL 用户的认证方式从 caching_sha2_password 改为 mysql_native_password。
执行以下 SQL:
ALTER USER 'your_username'@'your_host' IDENTIFIED WITH mysql_native_password BY 'your_password';
FLUSH PRIVILEGES;
替换 your_username、your_host 和 your_password 为你实际使用的值。
方法二:允许公钥检索(Public Key Retrieval)
在 JDBC 连接字符串中添加参数 allowPublicKeyRetrieval=true,示例如下:
jdbc:mysql://localhost:3306/shop-order?&allowPublicKeyRetrieval=trueuseUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=GMT%2B8
方法三:使用 SSL 安全连接(生产环境推荐)
启用 SSL 连接并配置好证书,以支持 caching_sha2_password 握手流程。