基于Spring Cloud Zookeeper实现服务注册与发现

时间:2021-05-19

服务注册

1.添加Spring Cloud Zookeeper依赖:

<dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-zookeeper-discovery</artifactId> <exclusions> <exclusion> <groupId>org.apache.zookeeper</groupId> <artifactId>zookeeper</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.apache.zookeeper</groupId> <artifactId>zookeeper</artifactId> <version>3.6.2</version> <exclusions> <exclusion> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency></dependencies>

2.在服务配置文件中添加zookeeper配置:

spring: cloud: zookeeper: connect-string: localhost:2181 #zookeeper地址

3.启动zookeeper服务器和服务(我这边是启动了两个服务,分别是provider和consumer),然后在zookeeper客户端中可以查看已经注册到zookeeper中的服务:

服务发现

1.创建controller

消费者controller:

package com.buhe.zk.controller;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.cloud.client.ServiceInstance;import org.springframework.cloud.client.discovery.DiscoveryClient;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.RestController;import org.springframework.web.client.RestTemplate;import java.util.List;@RestControllerpublic class ZkConsumerController { private static final String SERVICE_NAME = "provider"; private static final String SERVICE_PATH = "/zk/provider"; @Autowired private RestTemplate restTemplate; @Autowired private DiscoveryClient discoveryClient; /** * 调用提供者服务 * @return */ @GetMapping("/zk/consumer") public String zkConsumer(){ return "我吃了" + restTemplate.getForObject("http://" + SERVICE_NAME + SERVICE_PATH, String.class); } /** * 获取提供者服务URL * @return */ @GetMapping("/zk/url") public String serviceUrl() { List<ServiceInstance> list = discoveryClient.getInstances(SERVICE_NAME); if (list != null && list.size() > 0 ) { return list.get(0).getUri().toString() + SERVICE_PATH; } return null; }}

要使用RestTemplate别忘了加配置:

@Bean@LoadBalancedpublic RestTemplate restTemplate(){ return new RestTemplate();}

提供者controller:

package com.buhe.zk.controller;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.RestController;@RestControllerpublic class ZkProviderController { @GetMapping("/zk/provider") public String zkProvider(){ return "10个苹果"; }}

2.服务调用

以上就是基于Spring Cloud Zookeeper实现服务注册与发现的详细内容,更多关于Spring Cloud Zookeeper服务注册与发现的资料请关注其它相关文章!

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章