Detailed Explanation of Dynamic Refresh Configuration for Spring boot Application
- 2021-11-10 09:43:12
- OfStack
I wrote an article "Spring Cloud Bus to realize configuration real-time update", which uses configuration center to manage configuration and spring cloud bus to realize real-time notification. For simple SpringBoot applications, dynamic refresh configuration can be realized without using configuration center.
Reference://www.ofstack.com/article/222381. htm
The article uses springboot version: 2.0. 4. RELEASE springcloud version Finchley. SR1
1. Dependence
The following three dependencies need to be introduced:
compile('org.springframework.cloud:spring-cloud-starter-config')
compile('org.springframework.boot:spring-boot-starter-actuator')
compile('org.springframework.boot:spring-boot-starter-web')
(1) spring-cloud-starter-config for refresh configuration
(2) spring-boot-starter-actuator is an interface to expose the modification/refresh configuration
(3) spring-boot-starter-web is an interface for accessing exposed modification/refresh configurations
2. Configure the exposed interface
application.properties
# Use port 9999
server.port=9999
# Expose interface
management.endpoints.web.exposure.include=env,refresh
(1) env interface, which can obtain configuration (GET) or modify configuration (POST)
(2) refresh interface, which can refresh the configuration (POST), so that value annotated by @ RefreshScope can be re-injected.
3. @RefreshScope
Add @ RefreshScope annotations where you need to refresh the configuration in real time
Step 4 Start the service
Step 5 Modify the configuration
Visit localhost: 9999/actuator/env (GET) to get the configuration at this time
Visit localhost: 9999/actuator/env (POST)
{
"name":"somekey",
"value":"newvalue"
}
As above, the value corresponding to somekey in the configuration can be changed to newvalue
6. Get configuration values
Get the injected configuration value directly without calling the refresh interface, and find that it is still the old value
7. Refresh configuration to retrieve
Access localhost: 9999/actuator/refresh (POST) to refresh configuration
Retrieve the injected configuration value and find that it is a new value
Summarize
This article is here, I hope to give you help, but also hope that you can pay more attention to this site more content!