Nacos配置中心能够实现多项和多环境配置,便于统一管理各个项目和服务的环境。
1 Nacos配置 1.1 启动Nacos# Ubuntu中启动Nacos bash -f startup.sh -m standalone
Nacos地址: http://localhost:8848/nacos/
1.2 设置配置文件进入Nacos,添加config-01-dev.yml和config-01-prod.yml配置文件,“config-01”是应用名.
Nacos DataId配置组成是${prefix}-${spring.profiles.active}.${file-extension};
prefix对应应用名(不是工程名):config-01;
spring.profiles.active对应选择的开发环境:dev或者prod(根据需求自行修改名称);
file-extension对应文件后缀:yml
添加配置文件
编辑配置文件
2 创建应用创建工程名:config
包名:com.mason.config
2.1 基本配置设置pom.xml文件
2.2 创建yml文件4.0.0 org.springframework.boot spring-boot-starter-parent2.2.5.RELEASE com.mason config0.0.1-SNAPSHOT config Nocas config project for Spring Boot org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-devtoolsruntime true org.springframework.boot spring-boot-starter-actuator com.alibaba.cloud spring-cloud-starter-alibaba-nacos-discovery com.alibaba.cloud spring-cloud-starter-alibaba-nacos-configorg.springframework.boot spring-boot-starter-testtest 11 Hoxton.SR3 2.2.1.RELEASE org.springframework.cloud spring-cloud-dependencies${spring-cloud.version} pom import com.alibaba.cloud spring-cloud-alibaba-dependencies${spring.cloud.alibaba.version} pom import org.springframework.boot spring-boot-maven-plugin2.3.1.RELEASE
bootstrap.yml文件比application.yml文件的优先级高,可以把配置文件放在bootstrap.yml文件中。
创建bootstrap.yml文件
server:
port: 8080
spring:
application:
name: config-01
cloud:
nacos:
discovery:
server-addr: 127.0.0.1:8848
config:
server-addr: 127.0.0.1:8848
file-extension: yml
management:
endpoints:
web:
exposure:
include: '*'
创建application.yml文件
spring:
profiles:
# 调用config-01-dev.yml文件中的配置
active: dev
# 调用config-01-prod.yml文件中的配置
# active: prod
2.3 创建Controller
在com.mason.config包下创建controller目录,并创建ConfigController.java文件,如下:
package com.mason.config.controller;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RefreshScope //此注解实现配置自动更新
public class ConfigController {
// 获得Nacos配置文件中的参数
@Value("${custom.info}")
private String config;
@GetMapping("/getConfigInfo")
public String getConfigInfo(){
return this.config;
}
}
2.4 主程序
ConfigApplication.java文件如下:
package com.mason.config;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class ConfigApplication {
public static void main(String[] args) {
SpringApplication.run(ConfigApplication.class, args);
}
}
3 测试
注意需要先启动Nacos后,再启动ConfigApplication应用,否则无法获得配置文件会报错。
在浏览器中输入地址:http://localhost:8080/getConfigInfo
使用config-01-dev.yml文件返回值:Development Hello Nacos Config
使用config-01-prod.yml文件返回值: Product Hello Nacos Config



