Spring is losing connection to the DB and does not recover or reconnect

后端 未结 4 1257
予麋鹿
予麋鹿 2020-12-13 10:15

I have a spring-boot application on the same host as the Maria DB and both are running fine for some time. But between 12 hours and 2 days it seems that the spring boot appl

相关标签:
4条回答
  • 2020-12-13 10:50

    Spring (3) boot settings for hibernate and oracle:

    spring.datasource.test-on-borrow=true

    spring.datasource.validation-query=select 1 from dual


    0 讨论(0)
  • 2020-12-13 10:54

    To elaborate on @user5101998's answer and update the other ones, autoReconnect is actually not recommended. From the connector documentation:

    The use of this feature is not recommended, because it has side effects related to session state and data consistency when applications don't handle SQLExceptions properly, and is only designed to be used when you are unable to configure your application to handle SQLExceptions resulting from dead and stale connections properly

    The test-on-borrow property makes your provider (Tomcat, Hikari, etc.) tests that the connection is valid before fetching it from the connection pool.

    The validate-query is what will be used to ensure that the connection is valid.

    Using these parameters should prevent Spring from using dead connections. For Tomcat for instance, you can find documentation here on these parameters.

    0 讨论(0)
  • 2020-12-13 10:59

    Per a senior member in the Spring forums, the Spring DataSource is not intended for production use:

    The above answers are only part of the solution. Indeed you need proper transaction managent AND you need a connection pool. The DriverManagerDataSource is NOT meant for production, it opens and closes a datebase connection each time it needs one.

    Instead you can use C3P0 as your DataSource which handles the reconnect and is much better in performance. Here's a quick example of a potential configuration in a Spring xml configuration:

    <bean id="c3p0DataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
        destroy-method="close">
        <property name="driverClass" value="com.mysql.jdbc.Driver" />
        <property name="jdbcUrl" value="#{systemProperties.dbhost}" />
        <property name="user" value="#{systemProperties.dbuser}" />
        <property name="password" value="#{systemProperties.dbpass}" />
        <property name="maxPoolSize" value="25" />
        <property name="minPoolSize" value="10" />
        <property name="maxStatements" value="100" />
        <property name="testConnectionOnCheckout" value="true" />
    </bean>
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <constructor-arg ref="c3p0DataSource" />
    </bean>
    
    0 讨论(0)
  • 2020-12-13 11:08

    Try changing your connection URL to:

    spring.datasource.url=jdbc:mysql://localhost/validation?autoReconnect=true
    
    0 讨论(0)
提交回复
热议问题