Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring boot reset datasource on the fly

I am trying to update datasource in Spring Boot when the DB property like DB name, password or hostname changes in the spring configuration file or custom DB property file. When the property changes the application has to update by its own by listening changes to property.

I was using Spring actuator to /restart beans once the DB configuration is changed. But user has to explicitly make a post request to restart. This step has to be avoided by listening to the changes and update datasource.

Can you tell me the best way to do this in Spring boot?

like image 646
vishnukumar Avatar asked Sep 04 '17 07:09

vishnukumar


2 Answers

Found a way to update datasource on-the-fly,

I have given external spring config file which contains DB properties to the application and then refreshed the properties using @RefreshScope for the datasource bean.

A thread monitors the file changes and makes a call to actuator refresh() method.

database.properties

dburl=jdbc://localhost:5432/dbname
dbusername=user1
dbpassword=userpwd

Creating datasource,

@RefreshScope
public class DBPropRefresh {
  @Value("${dburl}")
  private String dbUrl;

  @Value("${dbusername}")
  private String dbUserName;

  @Value("${dbpassword}")
  private String dbPassword;

  @Bean
  @RefreshScope
  public DataSource getDatasource() {
    return new DatasourceBuilder().create().url(dbUrl).username(dbUserName).password(dbPassword);
  }
}

Giving external config file to the application,

java -jar myapplication.jar --spring.config.location=database.properties

I have created a Java thread class to monitor database.properties file changes. Followed https://dzone.com/articles/how-watch-file-system-changes When there are changes then it makes call to refreshEndPoint.refresh().

In pom.xml,

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-actuator</artifactId>
  <version>1.5.6.RELEASE</version>
</dependency>
like image 91
vishnukumar Avatar answered Sep 18 '22 22:09

vishnukumar


You can use Spring's Dynamic Data Source routing and check if it helps? It's a very old technique and might come handy, if that serves your purpose.

But please note that - this is data source routing and not new data source configuration.

https://spring.io/blog/2007/01/23/dynamic-datasource-routing/

like image 34
Karthik R Avatar answered Sep 19 '22 22:09

Karthik R