SpringBoot极简教程 · Spring Boot Spring-Boot

Spring Boot 配置 MySQL8.0 的异常处理

2019-05-06  本文已影响1人  Yinvoker

今天在使用Spring Boot连接8.0版本时会出现部分异常报错,以下为解决方法。

报错情况


Wed Jan 09 16:47:16 CST 2019 WARN: Establishing SSL connection without serve

HikariPool-1 - Exception during pool initialization.



java.sql.SQLTransientConnectionException: HikariPool-1 - Connection is not available, request timed out after 30000ms.

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.

com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: 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.

    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)

    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)

    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)

    at java.lang.reflect.Constructor.newInstance(Constructor.java:525)

    at com.mysql.jdbc.Util.handleNewInstance(Util.java:404)

    at com.mysql.jdbc.SQLError.createCommunicationsException(SQLError.java:981)

    at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:339)

    at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2253)

    ......

等等一系列错误.......

解决方案

application.properties文件


#数据库连接

spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test?serverTimezone=UTC&characterEncoding=utf8&useUnicode=true&useSSL=false

spring.datasource.username=root

spring.datasource.password=root

spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

spring.jpa.properties.hibernate.hbm2ddl.auto=update

spring.jpa.show-sql=false

#连接池配置

spring.datasource.druid.initial-size=1

spring.datasource.druid.min-idle=1

spring.datasource.druid.max-active=20

spring.datasource.druid.test-on-borrow=true

spring.datasource.druid.stat-view-servlet.allow=true

spring.jpa.database-platform=org.hibernate.dialect.MySQL5Dialect

pom.xml文件


<!--MySQL-->

<dependency>

<groupId>mysql</groupId>

<artifactId>mysql-connector-java</artifactId>

<version>8.0.12</version>

</dependency>

<!--JPA-->

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-data-jpa</artifactId>

</dependency>

原理简要说明

首先,新版mysql驱动的url必须设置时区,即 serverTimezone=UTC

因为mysql数据库和项目使用编码可能不同,所以要设置编码格式,否则会产生乱码,需要设置 characterEncoding=utf8 和 useUnicode=true

MySQL在高版本需要指明是否进行SSL连接,设置useSSL=false(这里true或false都可以了)

下面的连接池配置就是为了处理连接超时问题,来对连接池进行一些基础配置

设置完以后就可以正常运行了!!!

上一篇 下一篇

猜你喜欢

热点阅读