SpringBoot 启动未检查数据库连接

自己做的一个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;
    }

}

记得之前好像没有手动配置,也进行检查了, 后续需要深入了解一下

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值