preface

For microservices, configuration localization is a big chicken rib. It is impossible to restart the service every time you need to change a configuration. Therefore, the final solution is to externalize the configuration and host it on a platform to achieve the purpose of multiple modifications without restarting the service.

However, for Spring Boot projects of single applications, dynamic refreshing is obviously a bit redundant. Anyway, there is only one service, so why not restart it?

However, dynamic refresh is necessary in some special scenarios, as follows:

  1. Adding a Data sourceWhen connecting to a third-party platform, you can’t restart the service every time you add a data source
  2. Solidified butt: A large number of fixed docking methods, but a fixed code segment is different, such as different fields in the view provided, different fields in the interface service, etc.

Of course, each company has a different solution to the two scenarios listed above, so I won’t go into the details here.

What are the mainstream solutions under microservices?

There are three mainstream ways of dynamic configuration center under micro-service, as shown in the following figure:

The three configuration center schemes in the figure above can be said to be the most widely used in enterprises, which are as follows:

  1. Nacos: Alibaba’s latest open source project, this guy is awesome, a combination of Eureka and Config+Bus, can be used as both a configuration center and a registry, and has its own independent management platform, can be said to be the most mainstream one.

  2. Config+Bus: The microservice configuration center used in the early days can rely on GitHub to manage microservice configuration files. This is also used by many enterprises now, but they need to independently deploy a microservice, which is not as good as Nacos.

  3. Apollo: Ctrip open source project Apollo, this is also used by many enterprises, Chen mou does not know much, interested in in-depth research.

How many options are available for Spring Boot?

In fact, the above three can be adapted in the Spring Boot project, but as a single application is a bit heavy, the author briefly introduces two available solutions.

Spring Boot+Nacos (not recommended)

Nacos can not only serve as the configuration and registration center of Spring Cloud, but also be adapted to Dubbo and K8s. The official documentation gives a detailed introduction on how to adapt, but the author won’t go into details here, as shown below:

Of course, Nacos is also suitable for Spring and Spring Boot projects.

How do you use it? Here the author only provides some ideas, not too much in-depth research, this article will be introduced in detail in the author’s next column Spring Cloud:

  1. Download the corresponding version of Nacos, start the project, and visit http://localhost:8848 to enter the management interface of Nacos.

  2. The configuration of Nacos introduced by the Spring Boot project relies on nacos-config-spring-boot-starter to configure the address of the Nacos manager.

  3. The annotation @nacospropertysource and @nacosValue are combined.

  • @NacosPropertySource: specifies the configuration centerdataIdAnd whether to refresh automatically
  • @NacosValuealternative@ValueAnnotations complete the automatic assembly of attributes
  1. IO /zh-cn/docs/…

Although this solution can realize the dynamic refresh of configuration, it needs to integrate Nacos and start a Nacos service, which is completely overqualified and not recommended in practical projects.

Spring Boot+Config+ Actuator (recommended)

This solution actually uses the Config configuration center, but is not as heavy as Nacos, and is perfectly suitable for SpringBoot projects of individual applications, requiring only minor changes to achieve the effect.

Option 1 (not recommended)

  1. Add Config dependency as follows:
<! -- springCloud dependencies -->
<dependencyManagement>
    <dependencies>
        <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Hoxton.SR3</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
    </dependencies>
</dependencyManagement>

<! -- config dependency -->
<dependency>
      <groupId>org.springframework.cloud</groupId>
      <artifactId>spring-cloud-starter-config</artifactId>
    </dependency>

  <! -- Actuator dependence -->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>
Copy the code
  1. The endpoint that exposes Spring Boot in the configuration file is as follows:
management.endpoints.web.exposure.include=*
Copy the code
  1. Three new properties are added to the configuration file:
config.version=22
config.app.name=dynamic-project
config.platform=mysql
Copy the code
  1. In combination with@RefreshScopeAnnotate dynamic refresh and write a Controller as follows:
@RestController
// @refreshScope This annotation must be annotated otherwise dynamic updates cannot be completed
@RefreshScope
public class DynamicConfigController {
    @Value("${config.version}")
    private String version;

    @Value("${config.app.name}")
    private String appName;

    @Value("${config.platform}")
    private String platform;


    @GetMapping("/show/version")
    public String test(a){
        return "version="+version+"-appName="+appName+"-platform="+platform;
    }
Copy the code
  1. Start project test, browser accesshttp://localhost:8080/show/version, the following information is displayed:

  1. Modify thetargetThe configuration file in the directory is as follows:
config.version=33
config.app.name=dynamic-project
config.platform=ORACLE
Copy the code
  1. Under the POST request http://localhost:8080/actuator/refresh interface, manual refresh configuration (must, otherwise does not automatically refresh)

  2. The browser to enter http://localhost:8080/show/version again, results are as follows:

You can see that the configuration is automatically modified. No further action is required.

Option 2 (Recommended)

What do you think of plan one? Isn’t that a little chicken

First question: Why call a manual refresh?

Second question: Can I only change it manually in the configuration file? What if you want to change the system in the background?

Want to solve the above two questions still need to look at the source of the Config, code key part in org. Springframework. Cloud. Context. Refresh. ContextRefresher# refresh () method, the diagram below:

So just call the ContextRefresher#refresh() method (asynchronously, to avoid blocking all the time) after modifying the properties.

To facilitate testing, we wrote our own manual refresh interface as follows:

@GetMapping("/show/refresh")
    public String refresh(a){
        // Modify the properties in the configuration file
        HashMap<String, Object> map = new HashMap<>();
        map.put("config.version".99);
        map.put("config.app.name"."appName");
        map.put("config.platform"."ORACLE");
        MapPropertySource propertySource=new MapPropertySource("dynamic",map);
        // Set the modified configuration to the environment
        environment.getPropertySources().addFirst(propertySource);
        Call the refresh method asynchronously to avoid blocking and waiting for no response
        new Thread(() -> contextRefresher.refresh()).start();
        return "success";
    }
Copy the code

In the above code, the author only sets the values in the configuration file manually. In the real project, the configuration refresh can be read from the database in a persistent way.

We test to see below and start the project, visit http://localhost:8080/show/version, found that is configured in the application before the values in the properties, the diagram below:

Call the refresh interface: http://localhost:8080/show/refresh reset the attribute value;

Called again at http://localhost:8080/show/version under the configuration is changed, the following figure:

As you can see from the above figure, the configuration has been modified to achieve the effect of dynamic refresh.

conclusion

This paper introduces several feasible schemes from the configuration center of microservices to the simple configuration center of Spring Boot, and the author strongly recommends the last scheme, the simplified version of Config, which is completely suitable for single applications.

Project source has been uploaded, there is a need to pay attention to the public number ape technical column reply keyword 008 access.