For the project address, please go to gitee to download and view https://gitee.com/xwb1056481167/spring-cloud
For the configuration of nacos, please go to https://blog.csdn.net/www1056481167/article/details/113612177
Nacos as the configuration center
Nacos replaces the config of springCloud. When the project is initialized, it is necessary to ensure that the configuration is pulled from the configuration center first. After the configuration is pulled, the normal startup of the project can be guaranteed. The configuration and robust loading priority order in springboot is that bootstrap has a higher priority than application.
In the past, you used config to go to github to pull and configure. Now nacos has encapsulated a set, and you can go directly to nacos to read the configuration information.
Configuration Center cloudalibaba-config-nacos-client3377
1 、 pom.xml
<!-- alibaba nacos config -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
</dependency>
<!-- alibaba nacos 服务端 -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
2. Configuration rules
Description of the official website of configuration rules: https://nacos.io/zh-cn/docs/quick-start-spring-cloud.html
表达式规则:
\${spring.application.name}-\${spring.profile.active}.\${spring.nacos.config.file-extension}
2.1 、 bootstrap.yml
server:
port: 3377
spring:
application:
name: nacos-config-client
cloud:
nacos:
discovery:
server-addr: localhost:8848 #nacos服务注册中心地址
config:
server-addr: localhost:8848 #nacos作为配置中心地址
file-extension: yaml #指定yaml格式的配置
2.2 、 application.yml
spring:
profiles:
active: dev
3. The main startup class
@SpringBootApplication
@EnableDiscoveryClient
public class NacosConfigClientMain3377 {
public static void main(String[] args) {
SpringApplication.run(NacosConfigClientMain3377.class, args);
}
}
4、controller
@RestController
@Slf4j
@RefreshScope //支持nacos的动态刷新功能
public class ConfigClientController {
@Value("\${config.info}")
private String configInfo;
@Value("\${server.port}")
private String serverPort;
@GetMapping("configInfo")
public String getConfigInfo() {
return "serverPort: " + serverPort + "\\t\\n\\n configInfo: " + configInfo;
}
}
@RefreshScope This annotation must be added, dynamically refresh the latest configuration information of the modified nacos configuration
Access
1. Create the nacos-config-client-dev.yaml file configured above in nacos
1. Visit http://localhost:3377/configInfo
2. Rendering
Modify the configuration file of nacos, it will automatically refresh to the latest configuration information after real-time refresh