Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
427 views
in Technique[技术] by (71.8m points)

java - Reconnect to Db2 Database in running spring boot application

I am connecting to a db2 database using springBoot application. Over weekend the connection to database gets lost, with a connection reset exception. I need to have some auto retry mechanism in my application, where in when the request comes, and it gets a connection closed exception , the application should reconnect back to database. I am using SpringBoot 2.1.2 Release. db2jcc4 version is 4.26.14 At the server startup the database connection is established.

@ConfigurationProperties(prefix="data.app")
@Bean
public DataSource dataSourceApp(){

return new HikariDataSource(new HikariConfig())
}

@Bean
EntityManagerFactory appEntityManagerFactory(){
LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean ();
emf.setDataSource(dataSourceApp);
emf.setJPAVendorAdaptor(jpaVendorAdaptor);
emf.afterPropertiesSet();
return emf.getObject();

}


@Bean
publc EntityManager appEntityManager()
{
return appEntityManagerFactory.createEntityManager();
}

Then this entityManager is used for executing queries for each request.

Following are the connection pool properties

data.app.minimumIdle=0
data.app.idleTimeout=120000
data.app.driverClassName=com.ibm.db2.jcc.DB2Driver
data.app.jdbcURL=
data.app.username=
data.app.password=
data.app.maximumPoolSize=10
data.app.connectionTimeout=300000
data.app.poolName=
data.app.maxLifetime=130000
data.app.validationTimeout=300000

I want to reconnect to this database, when the first request comes and it encounters connection close exception. (Only want the Database bean to be reconnected , entire application should not be restarted ).

Thanks in advance .

question from:https://stackoverflow.com/questions/65919280/reconnect-to-db2-database-in-running-spring-boot-application

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Used the @RefreshScope of Spring actuator, and changed the following

@Bean
publc EntityManager appEntityManager()
{
return appEntityManagerFactory.createEntityManager();
}

to

@Bean
publc EntityManager appEntityManager()
{
return SharedEntityManagerCreator.createSharedEntityManager(appEntityManagerFactory);
}

On calling the refresh endpoints the database is relaoded. Using SharedEntityManagerCreator also returned the connection back to pool.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...