Spring boot reset datasource on the fly

前端 未结 3 1997
悲哀的现实
悲哀的现实 2021-02-15 13:36

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

3条回答
  •  忘掉有多难
    2021-02-15 14:02

    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,

    
      org.springframework.boot
      spring-boot-starter-actuator
      1.5.6.RELEASE
    
    

提交回复
热议问题