本文共 2442 字,大约阅读时间需要 8 分钟。
下载Nacos并启动Nacos Server。安装完成后,按照以下步骤配置并运行应用。
在项目依赖中添加Nacos配置管理的Spring Boot Starter依赖。注意:0.2.10版本对应Spring Boot 2.2.4 RELEASE版本。
com.alibaba.boot nacos-config-spring-boot-starter 0.2.10
在application.yml
中添加Nacos Server地址配置。
nacos: config: server-addr: 127.0.0.1:8848
在主类中使用@NacosPropertySource
注解加载指定dataId的配置源,并启用自动刷新。
@SpringBootApplication@NacosPropertySource(dataId = "nacostest", autoRefreshed = true)public class TengxunsmsApplication { public static void main(String[] args) { SpringApplication.run(TengxunsmsApplication.class, args); }}
在控制器中使用@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; }}
运行TengxunsmsApplication
类。
curl http://localhost:8080/config/get
返回false。
发布dataId为nacostest的配置:
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。
在项目依赖中添加Nacos服务发现的Spring Boot Starter依赖。
com.alibaba.boot nacos-discovery-spring-boot-starter 0.2.10
在application.yml
中添加Nacos Server地址配置。
nacos: discovery: server-addr: 127.0.0.1:8848
在控制器中使用@NacosInjected
注解注入Nacos的NamingService
实例。
@Controller@RequestMapping("discovery")public class DiscoveryController { @NacosInjected private NamingService namingService; @RequestMapping(value = "/get", method = GET) @ResponseBody public Listget(@RequestParam String serviceName) throws NacosException { return namingService.getAllInstances(serviceName); }}
运行TengxunsmsApplication
类。
curl http://localhost:8080/discovery/get?serviceName=nacos-test
返回空列表。
注册名称为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
返回服务实例信息。
转载地址:http://pkixz.baihongyu.com/