微服务服务发现、配置和管理之-Spring整合Nacos实现服务发现
完整示例代码请参考:nacos-spring-discovery-example一、下载 Nacos 并启动 Nacos server。参考:Nacos快速开始二、添加坐标可参考mvnrepository<dependency><groupId>com.alibaba.nacos</groupId><artifactId>nacos-spring-c
·
完整示例代码请参考:nacos-spring-discovery-example
一、下载 Nacos 并启动 Nacos server。参考:Nacos快速开始
二、添加坐标 可参考 mvnrepository
<dependency>
<groupId>com.alibaba.nacos</groupId>
<artifactId>nacos-spring-context</artifactId>
<version>${latest.version}</version>
</dependency>
三、通过添加 @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 {
@NacosInjected
private NamingService namingService;
@RequestMapping(value = "/get", method = GET)
@ResponseBody
public 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": {}
}
]
更多推荐
已为社区贡献14条内容
所有评论(0)