spring-boot web app loses ability to connect to MySQL / RDS after a while

后端 未结 2 1959
时光说笑
时光说笑 2021-01-06 14:21

I have a normal spring boot 1.2.x web app with an embedded Tomcat 7.x container and connected to an RDS instance (running MySQL 5.6). If the application is idle for a period

相关标签:
2条回答
  • 2021-01-06 14:52

    If you are using auto-configuration to define RDS connection from the property file like this:

    cloud.aws.rds.testdb.password=testdbpwd
    cloud.aws.rds.testdb.username=testdbuser
    cloud.aws.rds.testdb.databaseName=testdb
    

    spring boot datasource auto-configuration will not work even you put these(or tomcat datasource conf) to your configuration file:

    spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
    spring.datasource.test-on-borrow: true
    spring.datasource.validation-query: SELECT 1 FROM DUAL
    spring.datasource.log-validation-errors: true
    

    I think this is the reason why you cannot validate your connections in the pool, before using them.

    You need to override postProcessAfterInitialization method to set pool properties of the TomcatJdbcDataSourceFactory bean like this:

    @Component
    public class PoolConfiguration implements BeanPostProcessor {
    
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        if (bean instanceof TomcatJdbcDataSourceFactory) {
            TomcatJdbcDataSourceFactory tomcatJdbcDataSourceFactory = (TomcatJdbcDataSourceFactory) bean;
            tomcatJdbcDataSourceFactory.setTestOnBorrow(true);
            tomcatJdbcDataSourceFactory.setTestWhileIdle(true);
            tomcatJdbcDataSourceFactory.setValidationQuery("SELECT 1");
        }
        return bean;
    }
    }
    

    I could not find any other solution for this.By the way this might be a bug of spring-cloud-aws-autoconfigure packet.

    Good Luck!

    0 讨论(0)
  • 2021-01-06 14:59

    Try using this as well

    spring.datasource.test-while-idle=true
    spring.datasource.validation-interval=5000
    
    0 讨论(0)
提交回复
热议问题