简介
Nacos 提供了方便的服务配置功能,相较与spring-cloud-starter-config-server 还需要建立服务配置服务端,Nacos 本身就拥有服务配置功能,对微服务开发者更是友好。
Nacos 官网dataId 说明:配置文件=
s
p
r
i
n
g
.
a
p
p
l
i
c
a
t
i
o
n
.
n
a
m
e
−
{spring.application.name}-
spring.application.name−{spring.profiles.active}-{.properties | .yml | .yaml}
参考连接: https://nacos.io/zh-cn/docs/quick-start-spring-cloud.html
实现
1.Nacos Web控制台新建service-consumer模块配置文件service-consumer-dev.yml
2.配置service-consumer 模块bootstrap.yml
server:
port: 8020
spring:
application:
name: service-consumer
cloud:
nacos:
discovery:
server-addr: 127.0.0.1:8848
config:
server-addr: 127.0.0.1:8848
file-extension: yml
3.配置service-consumer模块application.yml
spring:
profiles:
active: dev
management:
endpoints:
web:
exposure:
include: "*"
4.修改service-consumer模块TestController.java
package com.vincent.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.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import javax.annotation.Resource;
import java.util.Map;
@RestController
@RequestMapping("/consumer")
@RefreshScope
public class TestController {
@Resource
private RestTemplate restTemplate;
@Value("${application.version}")
private String version;
@GetMapping("test")
public Object test(){
Map<String,Object> rst = this.restTemplate.getForObject("http://nacos-provider/test",Map.class);
rst.put("version",this.version);
return rst;
}
}
5.启动service-consumer模块并访问 http://localhost:8020/consumer/test
6.修改service-consumer-dev.yml 配置文件application.version=2.0,再访问http://localhost:8020/consumer/test
Nacos 持久化与集群
nacos安装目录下配置文件信息:
- 集群配置
配置成功后Web 控制台信息如下
参考文档:https://nacos.io/zh-cn/docs/cluster-mode-quick-start.html
总结
通过Nacos 服务配置发现,修改配置发布后不需要调用监控端点刷新配置就能得到最新的配置信息,相比spring-cloud-starter-config配置更方便快捷