一、下载
下载 Nacos 并启动 Nacos server,见 Nacos的安装使用。
二、启动配置管理
1.添加依赖
<dependency>
<groupId>com.alibaba.boot</groupId>
<artifactId>nacos-config-spring-boot-starter</artifactId>
<version>0.2.10</version>
</dependency>
注意:版本 0.2.x.RELEASE 对应的是 Spring Boot 2.x 版本,版本 0.1.x.RELEASE 对应的是 Spring Boot 1.x 版本。本示例使用的是0.2.10版本,SpringBoot 要使用较低版本,否则会报错,本示例使用的是2.2.4.RELEASE版本。详见NoClassDefFoundError: org/springframework/boot/context/properties/ConfigurationBeanFactoryMetadata
2.在 application.yml 中配置 Nacos server 的地址
nacos:
config:
server-addr: 127.0.0.1:8848
3.使用 @NacosPropertySource 加载 dataId 为 nacostest 的配置源,并开启自动更新
@SpringBootApplication
@NacosPropertySource(dataId = "nacostest", autoRefreshed = true)
public class TengxunsmsApplication {
public static void main(String[] args) {
SpringApplication.run(TengxunsmsApplication.class, args);
}
}
4.通过 Nacos 的 @NacosValue 注解设置属性值
@Controller
@RequestMapping("config")
public class ConfigController {
@NacosValue(value = "${userLocalCache:false}", autoRefreshed = true)
private boolean userLocalCache;
@RequestMapping(value = "/get", method = GET)
@ResponseBody
public boolean get() {
return userLocalCache;
}
}
5.启动应用 TengxunsmsApplication
6.测试
(1)cmd 下执行
curl http://localhost:8080/config/get
返回false
(2)cmd 下调用 Nacos Open API 向 Nacos server 发布配置:dataId 为nacostest,内容为userLocalCache=true
curl -X POST "http://127.0.0.1:8848/nacos/v1/cs/configs?dataId=nacostest&group=DEFAULT_GROUP&content=userLocalCache=true"
再次执行
curl http://localhost:8080/config/get
返回 true
三、启动服务发现
1.添加依赖
<dependency>
<groupId>com.alibaba.boot</groupId>
<artifactId>nacos-discovery-spring-boot-starter</artifactId>
<version>0.2.10</version>
</dependency>
注意:版本 0.2.x.RELEASE 对应的是 Spring Boot 2.x 版本,版本 0.1.x.RELEASE 对应的是 Spring Boot 1.x 版本。
2.在 application.yml 中配置 Nacos server 的地址
nacos:
discovery:
server-addr: 127.0.0.1:8848
3.使用 @NacosInjected 注入 Nacos 的 NamingService 实例
@Controller
@RequestMapping("discovery")
public class DiscoveryController {
@NacosInjected
private NamingService namingService;
public List<Instance> get(@RequestParam String serviceName) throws NacosException {
return namingService.getAllInstances(serviceName);
}
}
4.启动应用TengxunsmsApplication
5.测试
(1)cmd 下执行
curl http://localhost:8080/discovery/get?serviceName=nacos-test
返回为【】
(2)调用 Nacos Open API 向 Nacos server 注册一个名称为 nacos-test 服务
curl -X POST "http://127.0.0.1:8848/nacos/v1/ns/instance?port=8080&healthy=true&ip=127.0.0.1&weight=1.0&serviceName=nacos-test&encoding=GBK"
再次执行
curl http://localhost:8080/discovery/get?serviceName=nacos-test
返回为
[{"instanceId":"127.0.0.1#8080#DEFAULT#DEFAULT_GROUP@@nacos-test","ip":"127.0.0.1","port":8080,"weight":1.0,"healthy":true,"enabled":true,"ephemeral":true,"clusterName":"DEFAULT","serviceName":"DEFAULT_GROUP@@nacos-test","metadata":{},"instanceHeartBeatInterval":5000,"instanceHeartBeatTimeOut":15000,"ipDeleteTimeout":30000,"instanceIdGenerator":"simple"}]