前面已经将基本的Spring Cloud Alibaba 基本项目框架已经创建好,并且已安装好Nacos,下面开始加入 Nacos 服务配置管理。
使用Spring Cloud Config和Nacos Config做统一配置管理时,启动springboot项目初始化都是使用bootstrap.properties配置文件去初始化上下文。
加载顺序,依次为:
bootstrap.properties -> bootstrap.yml ->application.properties -> application.yml,
其中 bootstrap.properties 配置为最高优先级。
这是由spring boot的加载属性文件的优先级决定的,想要在加载属性之前去config server上取配置文件。
一、在 src/main/resources 目录下创建 bootstrap.properties 文件,内容如下:
spring.application.name=nacos-user
spring.cloud.nacos.discovery.server-addr=192.168.100.213:8848
spring.cloud.nacos.config.server-addr=192.168.100.213:8848
spring.cloud.nacos.config.file-extension=yaml
spring.cloud.nacos.config.prefix=nacos-user
spring.profiles.active=dev
二、启动类添加 @EnableDiscoveryClient 注解:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
@SpringBootApplication
@EnableDiscoveryClient
public class UserApplication {
public static void main(String[] args) {
SpringApplication.run(UserApplication.class, args);
}
}
三、在Controller类中添加 @RefreshScope 注解,实现配置热加载:
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.PathVariable;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RefreshScope
public class UserController {
@GetMapping("/user/{id}")
public Object product(@PathVariable Integer id) {
return "我是【用户】对象【" + id + "】";
}
@Value("${username:test}")
private String username;
@GetMapping("/username")
public String get() {
return username;
}
}
三、进入Nacos添加配置:
1、http://192.168.100.213:8848/nacos 用户名密码均为 nacos,登录管理界面;
2、进入左侧《配置列表》,点击右侧“+”号,添加配置;
3、新建配置:
Data ID:nacos-user-dev.yaml
配置格式:YAML
配置内容填写:
server.port: 8019 username: onyie
最后点击 发布 -> 确定 -> 返回 即可
注1:配置内容“:”号后,一定要加上空格!!!
注2:Data ID 格式规则为:${prefix}-${spring.profile.active}.${file-extension}
prefix 默认为 spring.application.name 的值,也可以通过配置项 spring.cloud.nacos.config.prefix 来配置。
spring.profile.active 即为当前环境对应的 profile,详情可以参考 Spring Boot文档。
注意:当 spring.profile.active 为空时,对应的连接符 - 也将不存在,dataId 的拼接格式变成 ${prefix}.${file-extension}
file-exetension 为配置内容的数据格式,可以通过配置项 spring.cloud.nacos.config.file-extension 来配置。
目前只支持 properties 和 yaml 类型。
四、然后启动 UserApplication ,检查配置是否生效:
1、检查启动端口,是否为Nacos中配置的 8019;
2、浏览器输入:http://localhost:8019/username 检查返回内容是否为配置内容;
3、修改 nacos-user-dev.yaml 配置中的 username,刷新http://localhost:8019/username,检查是否及时返回新内容;
五、检查Nacos服务发现,是否已经将当前 nacos-user 服务添加进去:
在服务管理 -> 服务列表 下查看:
服务名为前面的 spring.application.name 配置。