SpringBoot integrates with Nacos for unified configuration management

Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

In-depth source code from three aspects:

  • The service registry
  • Obtaining the service address
  • Perception of service address changes

In the Spring — Cloud – one of the Common package type org. Springframework. Cloud. Client. The serviceregistry. Serviceregistry, it is to provide the service registry SpringCloud standard, Components that integrate into the SpringCloud implementation service registry implement this interface.

public interface ServiceRegistry<R extends Registration>{
	void registry(R registration);
	void deregistry(R registration);
	void close(a);
	void setStatus(R registration,String status);
	<T> T getStatus(R registration);
}
Copy the code

And the interface implementation class is com. Alibaba. Cloud. Nacos. Registry. NacosServiceRegistry, when it will trigger the service registration actions?

Spring Cloud integrates the implementation process of Nacos

The spring-cloud-Commons package contains the following autowage information in meta-INF/Spring.Factories:

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
org.springframework.cloud.client.CommonsClientAutoConfiguration=\
org.springframework.cloud.client.ReactiveCommonsClientAutoConfiguration=\
Copy the code

SpringBoot integrates with Nacos for unified configuration management

  • Create a SpringBoot project and integrate the Nacos configuration center

  • Add the Nacos Config Maven dependency

<dependency>
            <groupId>com.alibaba.boot</groupId>
            <artifactId>nacos-config-spring-boot-starter</artifactId>
            <version>0.2.4</version>
        </dependency>
Copy the code

Add the address of Nacos Server in application.yml

 nacos:
  	config:
     server-addr: 127.0. 01.: 8848
Copy the code

Create the NacosConfigController class to dynamically read configuration from the Nacos Server

@NacosPropertySource(dataId = "server1",autoRefreshed = true)
@RestController
public class NacosConfigController {

    @NacosValue(value = "${info:local}",autoRefreshed = true)
    private String info;

    @GetMapping("config")
    public String getConfig(a){
        returninfo; }}Copy the code

Nacos Notes:

  • @nacospropertysource, which is used to load dataId as the configuration source for Server1. The autochecksum field identifies the checksum field for automatic update
  • Info indicates the key, and Local indicates the default value. If the key does not exist, the default value is used. In practical applications, you need to consider how to ensure service availability when the configuration center is unavailable.