How to automatically reconnect a DataSource connection in Spring? - java

Problem: when my spring application is running, and meanwhile the database server is stopped/restarted, then then db connection is lost and never restored.
I tested as follows:
execute query: OK
service mysql stop
execute query: exception:
Could not open JPA EntityManager for transaction; nested exception is javax.persistence.PersistenceException:
com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: No operations allowed after connection closed.
service mysql start
execute query: still exception!
Question: how can I tell spring DataSource to automatically reconnect after connection has been lost?
This is my configuration:
spring.datasource.url=jdbc:mysql://localhost/tablename?useSSL=false
spring.datasource.username=root
spring.datasource.password=rootpw
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.tomcat.validation-query=SELECT 1
spring.datasource.tomcat.validation-query-timeout=5000
spring.datasource.tomcat.test-on-borrow=true
spring.datasource.tomcat.test-on-connect=true

I'm using a connection pool like HikariCP to do a reconnect automatically.
see the example at Stackoverflow: How do I configure HikariCP in my Spring Boot app in my application.properties files?

My bad, I had a misconfiguration. The config above is all that's needed for auto reconnect.

Related

Connection closed exception when using Oracle Weblogic's JNDI datasource

I'm making use of Oracle Weblogic's (12.1.3) JNDI datasource for connection pooling. The max idle time for a connection is set to 30 seconds in the admin console. But, there is this method that takes more than a minute to complete, which results in the connection getting automatically closed.
My problem is that I have set autoCommit as false, and I'm unable to rollback the transaction in case of an Exception. I'm making use of pure JDBC. I tried using Spring's JdbcTemplate, surprisingly there is no Connection related issue when I'm making use of the #Transactional annotation.
Is there a technique using which I can keep the connections that I get from the Weblogic's JNDI datasource alive for more than 30 seconds, without modifying the configurations in the admin console?

Resetting DB connection in Spring boot at runtime after getting connection closed

I am getting error connection reset in my running spring boot app for db2 database. On restarting the application the connection starts working.
If I receive connection closed or connection reset error, I need to reconnect to the database at runtime.
What will be the best way to do this?
I am using Hikari connection pool , Is there some property which allows the database connection to be checked ..if broken ..then reconnect.
Or some spring boot configuration like #RefreshScope recreates the bean after configuration changes. Any spring boot bean which might help in this case?
Thanks for the help.
I have same issue, I try config param for hiraki but still getting connection is closed.
You can try the way by this link https://www.linkedin.com/pulse/spring-boot-retry-database-connection-startup-abdelghani-roussi?articleId=6723332249346981888

Execute custom query when a connection is fetched from dataSource

My web application runs on Tomcat 7.0 and uses Spring 3.2, Hibernate 4.3 and Oracle Database.
The entityManagerFactory is configured as org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean and the transactionManager is org.springframework.orm.jpa.JpaTransactionManager. The dataSource is defined as org.springframework.jndi.JndiObjectFactoryBean and internally refers to a connection pool of type org.apache.tomcat.jdbc.pool.DataSourceFactory.
Each time when a connection is fetched from the pool by the entityManager, I'd like to execute a custom sql statement in that connection. It will only change a property in the Oracle session context, like so:
dbms_session.set_context(context, propName, propValue);
So no dml is done.
Each time when a connection is released back to the pool, a similar statement should be executed to clear the property value.
The property value should be fetched dynamically from the spring-security context, so I can't hardcode this into a connection test statement.
I've also looked into Hibernate interceptors, but I've found no way to execute any sql in the same session from within an interceptor.
Any ideas?

How do I get Spring Boot to automatically reconnect to PostgreSQL?

I am running Spring Boot connecting to a PostgreSQL database. I have verified that data is written to the database if Spring Boot is started after the database.
spring.datasource.url = jdbc:postgresql://localhost/dbname
spring.datasource.username = user
spring.datasource.password = secret
spring.datasource.driver-class-name = org.postgresql.Driver
spring.datasource.testOnBorrow=true
spring.datasource.validationQuery=SELECT 1
When there are changes in the database in development, I run into exceptions:
PreparedStatementCallback; SQL []; This connection has been closed.; nested exception is org.postgresql.util.PSQLException: This connection has been closed.
Note that the database is accessible again when the exceptions occur; I think the problem is that connection is stale because the database endpoint it originally connected to is no longer available because of the restart. Restarting Spring Boot resolves the issue.
How do I configure Spring Boot to reconnect to PostgreSQL so that I do not need to restart it?
I have attempted to follow the answers in Spring Boot JPA - configuring auto reconnect and How to reconnect database if the connection closed in spring jpa?. I am not sure whether the PostgreSQL behavior is different from MySQL. My reading of the Spring Boot documentation has not helped; I do not know the components described well enough to understand what documentation I should be looking at.
Spring boot should be configured to reconnect automatically, problem is that it is not aware of the broken connection.
Since you are already using test on borrow and validation query, just try reducing validation interval so it is executed every time.
spring.datasource.tomcat.test-on-borrow=true
spring.datasource.tomcat.validation-query=SELECT 1
spring.datasource.tomcat.validation-interval=0
Tomcat jdbc connection pool on testOnBorrow:
(boolean) The indication of whether objects will be validated before being borrowed from the pool. If the object fails to validate, it will be dropped from the pool, and we will attempt to borrow another. NOTE - for a true value to have any effect, the validationQuery or validatorClassName parameter must be set to a non-null string. In order to have a more efficient validation, see validationInterval. Default value is false
But be aware of validationInterval:
(long) avoid excess validation, only run validation at most at this frequency - time in milliseconds. If a connection is due for validation, but has been validated previously within this interval, it will not be validated again. The default value is 30000 (30 seconds).

SQL JDBTempalate weblogic

I am executing SQLs via following code statement.
Application server is weblogic 12c
and Spring 3.1.1 API is used.
getJdbcTemplate().execute()...
I am wondering if getJdbcTemplate() returns DB connection itself or a reference to connection pool hosted at weblogic.
And if connection is closed after sql is executed?
If you define the datasource on Weblogic level and you reference that via a JNDI lookup in your spring configuration ==> will return a connection from the pool it was configured on Weblogic.
However with Spring you can configure your own pool without using Weblogic's one.
So depends on how you use it.
Cheers.

Categories