tags: java spring spring boot nacos Dynamic configuration
The reason for using dynamic configuration: Properties and YAML are written in the project. Many times some configurations need to be modified. Each modification must be restarted, which not only increases the instability of the system, but also greatly improves maintenance costs. It is very troublesome And spend time.
Using dynamic configuration, you can avoid these troubles, you can dynamically modify the configuration, no need to restart the project.
NACOS configuration center can make the configuration standardization and formatting. When the configuration information changes, the real -time effect is revised. Without restarting the server, you can automatically perceive the corresponding changes and send new changes to the corresponding program. Quickly respond to change.
Version of this environment: nacos1.4.2; Spring-Boot 2.3.9.release; Nacos-config-Spring-Boot-Starter 0.2.1

The name of the configuration file is gateway.yml

Notice: When the project starts, the Nacos-Config will automatically load the following files, so the following file names can be used as a file format for the default dynamic configuration.
Add the configuration of testingnacosConfigDemmo: NAME1

illustrate: The configuration project, the group name isICP_PLATFORM (Note: The group name is recommended to use the lower line _, it is not recommended to use the middle horizontal line-, there will be a chance to have problems that cannot be read in the middle horizontal line. Please pay attention to the use of connectors. Need tonacos naming space Naming Naming Space)


Add dependencies in the POM.XML file.
<dependency>
<groupId>com.alibaba.boot</groupId>
<artifactId>nacos-config-spring-boot-starter</artifactId>
<version>0.2.1</version>
</dependency>
Modify the project configuration file and read the configuration content in nacos
# Specify the startup port
server:
port: 7200
spring:
application:
# Specifying service name
name: gateway
#The project operating environment, you can match the name of the NACOS dynamic configuration file. Different environments use different dynamic configurations in different environments
profiles:
active: dev
cloud:
nacos:
config:
server-addr: 127.0.0.1:8848 #NACOS's registration address
file-extension: yml #Dynamic configuration file format. Is the dynamic configuration in NACOS, here is YML
group: ICP_PLATFORM #NACOS dynamic configuration packets should be consistent with NACOS configuration files
# namespace: #Namespace is the naming space of Nacos, I am the default space here, so I will not be configured
Controller code:
import com.insupro.search2.service.IIndexService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api/demo")
public class nacosConfigDemmo {
@Autowired
private DemoService demoService;
@GetMapping("/name")
public Object showDemoName(){
return demoService.showDemoName();
}
}
Service interface code:
public interface IIndexService {
Object showDemoName();
}
Service implementation code:
import com.insupro.search2.service.demoService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;
@Service
// Note that you need to refresh the configuration automatically, you need @Refreshscope
@RefreshScope
public class demoServiceImpl implements demoService{
/**
* Test configuration used in NACOS is used above.
*/
@Value("${nacosConfigDemmo}")
private String demoName;
@Override
public Object showDemoName(){
return demoName;
}
}
Run, request interface address, get the response value:
Postman request, the first response, the value is name2

Modify the nacos configuration file, change the NacosconfigDemmo: name1 to NACOSCONFIGDEMMO: name2 and publish it

Waiting for the console printing: Refresh Keys Changed: [nacosconfigdemmo], then the dynamic configuration has taken effect

Request again, find that the return value has changed:

As a result, name1 has become name2, the project does not need to restart, and the dynamic configuration has taken effect.
Get the configuration file and generate bean
import lombok.Getter;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cloud.context.config.annotation.RefreshScope;
// Automatically refresh the mechanism, you need the GET method to support
@Setter
@Getter
// Get the configuration file
@ConfigurationProperties(prefix = "security.ignore")
// Open automatic refresh
@RefreshScope
public class SecurityProperties {
private PermitProperties ignore = new PermitProperties();
}
Configuration file entity class
import lombok.Getter;
import lombok.Setter;
@Setter
@Getter
public class PermitProperties {
/**
* Set the URL without authentication
*/
private String[] httpUrls = {};
public String[] getUrls() {
if (httpUrls == null || httpUrls.length == 0) {
return new ArrayList<>();
}
List<String> list = new ArrayList<>();
for (String url : httpUrls) {
list.add(url);
}
return list.toArray(new String[list.size()]);
}
}
At this point, the automatic configuration is completed, and the gateway configuration and use can be performed according to your business code.
but! Intersection Notice! Intersection If you call the configuration in the configuration file, you need to use the @RefreshScope annotation in the configuration file to refresh the configuration. Because the configuration file has been completed when the project starts.
For example:
@Configuration
public class ResourceServerConfiguration {
@Autowired
private SecurityProperties securityProperties;
// Use @Configuration to define the configuration file, and use @Bean to assemble bean in the configuration class. At this time, if the @RefreshScope annotation is not used automatically, the automatic configuration will not take effect.
@Bean
@Autowired(required = false)
@RefreshScope
SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
if (securityProperties.getIgnore().getUrls().length > 0) {
authorizeExchange.pathMatchers(securityProperties.getIgnore().getUrls()).permitAll();
}
// Todo's remaining business code ................
return http.build();
}
}
1. NACOS download and start NACOS official website document SpringCloudAlibaba official website document Reference 1. NACOS download I won’t explain what NACOS is. Follow the Quick Star steps on...
See:https://nacos.io/zh-cn/docs/quick-start-spring-boot.html 1. Add dependencies note: Version0.2.x.RELEASECorresponding to Spring Boot 2.x version, version0.1.x.RELEASECorresponding to Spring Boot 1....
First send the configuration to the NACOS server; Then write a configuration entity class according to the configuration item in the profile; The role of @Refreshscope annotations is to perform dynami...
NACOS configuration center principle analysis Configuration Type: Spring Cloud Alibaba Nacos Config currently provides three configuration capabilities that are related to NACOS. A: The configuration ...
In the multi-environment development of micro-service, use NACOS configuration, from development, testing, to deployment, can bring great convenience. In general, a company has multiple projects, a pr...
NACOS dynamic refresh configuration Version configuration NACOS configuration...
Yesterday, OpenFeign achieved remote calls, continue today Dynamic configuration with NACOS as a configuration center It has been introduced above, directly putting the official Demo However, pay atte...
What is nacos The full English name of Dynamic Naming and Configuration Service, NA is Naming/NameServer, as the registration center, CO is configuration, as the registration center. Service means tha...
Recently, Nacos, Apollo as the configuration center, record it. The premise is that the NACOS environment has been set up. We first set up tests by ourselves, and then let's build maintenance, so just...
1 First, add the @RefreshScrope annotation to the controller layer code; 2. Add a bootstrap.yml configuration file to the configuration file Configure the IP of nacos inside (the IP must be in this co...