本文主要面向 Spring 的使用者,通过两个示例来介绍如何使用 Nacos 来实现分布式环境下的配置管理和服务发现。
关于 Nacos Spring 的详细文档请参看:nacos-spring-project。
您需要先下载 Nacos 并启动 Nacos server。操作步骤参见 Nacos 快速入门。
启动了 Nacos server 后,您就可以参考以下示例代码,为您的 Spring 应用启动 Nacos 配置管理服务了。完整示例代码请参考:nacos-spring-config-example
<dependency><groupId>com.alibaba.nacos</groupId><artifactId>nacos-spring-context</artifactId><version>${latest.version}</version>
</dependency>
最新版本可以在 maven 仓库,如 "mvnrepository.com" 中获取。
@EnableNacosConfig
注解启用 Nacos Spring 的配置管理服务。以下示例中,我们使用 @NacosPropertySource
加载了 dataId
为 example
的配置源,并开启自动更新:@Configuration
@EnableNacosConfig(globalProperties = @NacosProperties(serverAddr = "127.0.0.1:8848"))
@NacosPropertySource(dataId = "example", autoRefreshed = true)
public class NacosConfiguration {}
@NacosValue
注解设置属性值。@Controller
@RequestMapping("config")
public class ConfigController {@NacosValue(value = "${useLocalCache:false}", autoRefreshed = true)private boolean useLocalCache;@RequestMapping(value = "/get", method = GET)@ResponseBodypublic boolean get() {return useLocalCache;}
}
启动 Tomcat,调用 curl http://localhost:8080/config/get
尝试获取配置信息。由于此时还未发布过配置,所以返回内容是 false
。
通过调用 Nacos Open API 向 Nacos Server 发布配置:dataId 为example
,内容为useLocalCache=true
curl -X POST "http://127.0.0.1:8848/nacos/v1/cs/configs?dataId=example&group=DEFAULT_GROUP&content=useLocalCache=true"
http://localhost:8080/config/get
,此时返回内容为true
,说明程序中的useLocalCache
值已经被动态更新了。本节演示如何在您的 Spring 项目中启动 Nacos 的服务发现功能。完整示例代码请参考:nacos-spring-discovery-example
<dependency><groupId>com.alibaba.nacos</groupId><artifactId>nacos-spring-context</artifactId><version>${latest.version}</version>
</dependency>
最新版本可以在 maven 仓库,如 "mvnrepository.com" 中获取。
@EnableNacosDiscovery
注解开启 Nacos Spring 的服务发现功能:@Configuration
@EnableNacosDiscovery(globalProperties = @NacosProperties(serverAddr = "127.0.0.1:8848"))
public class NacosConfiguration {}
@NacosInjected
注入 Nacos 的 NamingService
实例:@Controller
@RequestMapping("discovery")
public class DiscoveryController {@NacosInjectedprivate NamingService namingService;@RequestMapping(value = "/get", method = GET)@ResponseBodypublic List<Instance> get(@RequestParam String serviceName) throws NacosException {return namingService.getAllInstances(serviceName);}
}
启动 Tomcat,调用 curl http://localhost:8080/discovery/get?serviceName=example
,此时返回为空 JSON 数组[]
。
通过调用 Nacos Open API 向 Nacos server 注册一个名称为 example
服务。
curl -X PUT 'http://127.0.0.1:8848/nacos/v1/ns/instance?serviceName=example&ip=127.0.0.1&port=8080'
curl http://localhost:8080/discovery/get?serviceName=example
,此时返回内容为:[{"instanceId": "127.0.0.1#8080#DEFAULT#example","ip": "127.0.0.1","port": 8080,"weight": 1.0,"healthy": true,"cluster": {"serviceName": null,"name": "","healthChecker": {"type": "TCP"},"defaultPort": 80,"defaultCheckPort": 80,"useIPPort4Check": true,"metadata": {}},"service": null,"metadata": {}}
]
版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。
工作时间:8:00-18:00
客服电话
电子邮件
admin@qq.com
扫码二维码
获取最新动态