nacos--配置中心使用

什么是nacos

Nacos 支持基于 DNS 和基于 RPC 的服务发现(可以作为springcloud的注册中心)、动态配置服务(可以做配置中心)、动态 DNS 服务。

以下内容都是基于spring-boot 2.0.6.RELEASE + nacos

依赖管理

项目: nacos-spring-boot-project

1
2
3
4
5
<dependency>
<groupId>com.alibaba.boot</groupId>
<artifactId>nacos-config-spring-boot-starter</artifactId>
<version>0.2.1</version>
</dependency>

基于yml配置

1
2
3
nacos:
config:
server-addr: 192.168.190.128:8848

namespace是命名空间 ID,不能配置命名空间名称。如果不配置namespace,默认使用public

Nacos控制台新建配置

Data ID: nacos.cfg.dataId
Group: test

test=dc

启动类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
@SpringBootApplication
@NacosPropertySource(dataId = DATA_ID,groupId = GROUP_ID, autoRefreshed = true)
@Slf4j
@RestController
public class NacosApp {

static final String DATA_ID = "nacos.cfg.dataId";

static final String GROUP_ID = "test";

public static void main(String[] args) {
SpringApplication.run(NacosApp.class, args);
}

@GetMapping("/getValue")
public String getValue(){
return value;
}

@GetMapping("/getNacosValue")
public String getNacosValue(){
return nacosValue;
}


@Value(value = "${test:value}")
private String value;

@NacosValue(value = "${test:nacosValue}", autoRefreshed = true)
private String nacosValue;


@NacosConfigListener(
dataId = NacosApp.DATA_ID,
timeout = 500
)
public void onChange(String newContent) throws Exception {
log.info("onChange: {}", newContent);
}
}

Spring @Value注解和 Nacos @NacosValue 注解

注解 是否支持动态更新 补充
@Value
@NacosValue 需配置autoRefreshed=true

测试

1
2
3
4
5
6
7
8
9
10
curl -X GET "http://192.168.123.59:8080/getValue"
dc
curl -X GET "http://192.168.123.59:8080/getNacosValue"
dc
#发布/更改配置
curl -X POST "http://127.0.0.1:8848/nacos/v1/cs/configs?dataId=nacos.cfg.dataId&group=test&content=test=dcUpdate"
curl -X GET "http://192.168.123.59:8080/getValue"
dc
curl -X GET "http://192.168.123.59:8080/getNacosValue"
dcUpdate

感谢您的阅读。 🙏 关于转载请看这里