SpringBoot 2.0 - DB credentials update without restarting the App!
Wait what? Did I read the title properly?
I haven’t tried this out yet, but it looks like you can now add @RefreshScope to a javax.sql.DataSource @Bean definition and it’ll automatically be re-configured? If so, that’s super cool!
Read the above line once again! For quite some time, we have enjoyed Spring Cloud Config. With the recent launch of SpringBoot 2.0, we could change the database credential(s) on the fly and hit the /actuator/refresh endpoint and refresh the DB connection pool with the new credentials without restarting the app. I have seen at several enterprises, where due to their internal requirements, the DBA team mandate to change the credentials on a periodic basis. This enables zero app down-time (withouth Blue/Green, etc.)
Enough of theory, now let’s test this with a simple app.
git clone https://github.com/aniruthmp/db-reload.git
- Run a local spring-cloud-config at the default port 8888
- Ensure to provide the
spring.cloud.config.server.git.urito locate the configuration data for the above
db-reloadapp. Make sure to have the following properties (update the DB credentials based on your set-up)
spring: datasource: url: jdbc:mysql://localhost:3306/db_1 username: springuser password: ThePassword jpa: hibernate: ddl-auto: create management: endpoints: enabled-by-default: true web: exposure: include: refresh
Note: If you are unfamiliar about the changes introduced in SpringBoot 2.0 Actuator endpoints, check out this introducing-actuator-endpoints-in-spring-boot-2-0
- Now start your
db-reloadapp and PUT some test data
$ curl -X PUT -d name=Ani -d email="email@example.com" http://localhost:8080/demo/add $ curl -X PUT -d name=Jack -d email="firstname.lastname@example.org" http://localhost:8080/demo/add
- Now verify the above records by doing a GET
$ curl http://localhost:8080/demo/all
- Now change your DB credentials in mysql after logging into your
$ ALTER USER 'springuser'@'localhost' IDENTIFIED BY 'NewThePassword';
- After changing the password successfully, go ahead and update your
spring.cloud.config.server.git.uriand commit/push the change.
- Now perform the /actuator/refresh endpoint
$ curl -X POST http://localhost:8080/actuator/refresh
Note in the output above that “spring.datasource.password” got refreshed. Also in the application logs you can notice the following
2018-04-18 21:27:29.660 INFO 15521 --- [nio-8080-exec-3] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown initiated... 2018-04-18 21:27:29.669 INFO 15521 --- [nio-8080-exec-3] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown completed.
- Now try to call the DELETE or GET and you can see the output.