rajesh reddy SR
rajesh reddy SR

Reputation: 426

Dynamic Database property changes in Springboot

I have mysql database and i have configured database properties in application.properties file . Now if i do change db connection properties , i want reflect that changes into my application on the fly , means with out restarting the server

Is this possible using with spring cloud config server and actuator?

Upvotes: 3

Views: 2627

Answers (1)

pvpkiran
pvpkiran

Reputation: 27018

I have tested this quite a bit and here are my findings.

  1. Spring config server works pretty well for simple key value pairs.
  2. It also works for Database properties provided that you are creating datasource objects yourself and you are using @RefreshScope.
    For example, if you have a config server with these properties.

    mongodb.feed.database=kiran
    mongodb.feed.host=localhost
    mongodb.feed.port=27017
    

And you are configuring MongoTemplate in your application like this.

@Configuration
@ConfigurationProperties(prefix = "mongodb.feed")
@EnableMongoRepositories(basePackages = "in.phani.springboot.repository", mongoTemplateRef = "feedMongoTemplate")
@Setter
class FeedMongoConfig {

  private String host;
  private int port;
  private String database;

  @Primary
  @Bean(name = "feedMongoTemplate")
  @RefreshScope // this is the key
  public MongoTemplate feedMongoTemplate() throws Exception {
    final Mongo mongoClient = createMongoClient(new ServerAddress(host, port));
    return new MongoTemplate(mongoClient, database);
  }

  Mongo createMongoClient(ServerAddress serverAddress) {
    return new MongoClient(serverAddress);
  }
}

And if you change the database name in your config properties and then refresh the scope with /refresh endpoint. It works pretty well.

  1. With springboot you need not do manual configuration like this. Spring boot has Autoconfiguration for most of the stuff. Continuing with the same example above, if you were to put in config properties something like this

    spring.data.mongodb.uri=mongodb://localhost:27017/phani
    

spring-boot will configure MongoTemplate for you(you don't need to create yourself as in 2nd point). Here comes the hiccup.
Now if you change the database name, and refresh the scope, it doesn't work. Because in this case, MongoTemplate was configured by spring-boot Autoconfiguration(MongoAutoConfiguration)

So in conclusion, it needs extensive testing to be done, before using it on production(especially for complex beans like datasources, MongoTemplates), since there is not enough documentation on this.. But I would say, it is worth trying.

Upvotes: 1

Related Questions