配置中心有一个优先级顺序:项目默认会加载配置中心的poem-config-dev.yml中的配置。当配置中心宕机了,才会走本地的配置bootstrap.yml>application.yml他是这么一个顺序。且配置中心模块的配置文件必须要用bootstrap.yml。
配置中心的命名格式:{application-name}-{profiles-active}.yml
使用配置中心后,后续扩展会有配置分组的概念。
这里我推荐就直接用默认的DEFAULT_GROUP分组即可,dev、test、proife期的项目来区分即可。 这么做的限制就是项目体系不会特别大。
例:nacos-config-test.yml 测试环境
nacos-config-dev.yml 待上线环境
nacos配置中心代码
1.pom文件配置
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>SpringCloud</artifactId>
<groupId>com.gbicc</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>poem-config</artifactId>
<dependencies>
<!-- SpringCloud Ailibaba Nacos -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<!-- SpringCloud Ailibaba Nacos Config -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
</dependency>
<!-- SpringCloud Ailibaba Sentinel -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>
<!-- SpringBoot Web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
</project>
2.创建bootstrap.yml配置文件,配置中心也要注册到注册中心
server:
port: 8766
spring:
application:
name: poem-config
profiles:
active: dev
cloud:
nacos:
discovery:
server-addr: 127.0.0.1:8848
config:
server-addr: 127.0.0.1:8848
file-extension: yml
3.创建spring boot项目启动类ConfigApplication
package com.gbicc;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
@EnableDiscoveryClient
@RestController
@RefreshScope
public class ConfigApplication {
public static void main(String[] args) {
SpringApplication.run(ConfigApplication.class,args);
System.out.println("配置中心模块启动成功");
}
@Value("${nacos.config}")
private String config;
@RequestMapping("/config/getValue")
public String getValue() {
return config;
}
}
4.nacos注册服务
文件的格式不要用错了
5.启动项目,查看注册中心服务列表,这时应该是可以看到配置中心模块已经注册到注册中心
6.直接访问http://localhost:8766/config/getValue,可以看到已经将配置中心的配置加载到
使用注册中心后,系统模块就的配置文件可以修改为bootstrap.yml