自己做的一个SpringBoot demo,打算使用--多数据源--
配好了之后部署我的测试服务器, 看着日志打印=======启动成功=========
完美。
但是当抄起我的http请求时:
com.mysql.cj.jdbc.exceptions.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 com.mysql.cj.jdbc.exceptions.SQLError.createCommunicationsException(SQLError.java:174)
at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:64)
at com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:836)
at com.mysql.cj.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:456)
at com.mysql.cj.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:246)
很容易看到是jdbc 连接出现问题,ok,
第一步:检查我的数据库是否启动, 启动的没错
第二部:检查我配置文件
spring:
profiles: test
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://-----:3306/----?useUnicode=true&characterEncoding=utf8&serverTimezone=UTC&useSSL=false
username: root
password: root
what ?数据库竟然这样配置着。。。。。。
但是又一想,这种配置竟然能启动? 经过查询得出以下结论:
SpringBoot 启动时默认不对数据库连接进行校验(懒加载)
因为我的代码没有进行 预热 等操作,所以在启动时是无法察觉的
解决方案:
就是在启动时,对热点数据进行预热,或者做一些数据库连接操作
比如:
@Component
public class ApplicationContextHelper implements ApplicationContextAware {
private static ApplicationContext context;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
try {
context = applicationContext;
// 项目初始化完成后,手动检验数据库
DataSource dataSource = (DataSource) context.getBean("dataSource");
dataSource.getConnection().close();
} catch (Exception e) {
e.printStackTrace();
// 当检测数据库连接失败时, 停止项目启动
System.exit(-1);
}
}
public ApplicationContext getApplicationContext() {
return context;
}
}