一. 简单概述
使用 ZooKeeper 的临时节点与持久节点,将服务注册到 ZooKeeper 上,当服务启动时,会以当前服务的服务名称为持久节点,当前服务的具体ip地址为临时节点保存到 ZooKeeper,当服务发生宕机时,临时节点消失,或服务发生改变时,基于事件通知告诉其它服务获取新的服务数据
二. 配置服务注册到 ZooKeeper
- 安装配置ZooKeeper,启动
- 服务消费方,服务提供方同时引入 ZooKeeper 依赖,注意点实际安装的 ZooKeeper 是否与 SpringCloud 自动整合的 ZooKeeper 依赖版本一致,若版本不一致可能会报错,一般排除 SpringBoot 引入的 ZooKeeper 依赖,单独引入与安装的版本相同的依赖
<!--SpringBoot整合Zookeeper客户端-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-zookeeper-discovery</artifactId>
<exclusions>
<!--先排除自带的zookeeper3.5.3-->
<exclusion>
<groupId>org.apache.zookeeper</groupId>
<artifactId>zookeeper</artifactId>
</exclusion>
</exclusions>
</dependency>
<!--添加zookeeper3.4.14版本-->
<dependency>
<groupId>org.apache.zookeeper</groupId>
<artifactId>zookeeper</artifactId>
<version>3.4.14</version>
</dependency>
- 服务提供方与服务消费方的启动类都要添加 @EnableDiscoveryClient 注解修饰
- 服务消费方创建配置类创建 RestTemplate 注入到容器中,使用 @LoadBalanced 修饰开启Ribbon负载
- 服务消费方通过 RestTemplate 根据服务名称在 Consul 注册中心获取指定服务的调用地址,负载调用
1. 服务提供方 yml 文件配置注册到 ZooKeeper
server:
port: 8004 #当前服务端口号
spring:
application:
name: cloud-provider-payment8004 #当前服务名称
#=============当前服务注册到ZooKeeper配置===========================
cloud:
zookeeper:
connect-string: 127.0.0.1:2181 #当前服务注册到ZooKeeper的地址,多个","隔开
#=============当前服务注册到ZooKeeper配置end===========================
2. 服务消费方 yml 文件配置注册到 ZooKeeper
server:
port: 80 #当前服务端口号
spring:
application:
name: cloud-consumerzk-order80 #当前服务名称
#=============当前服务注册到ZooKeeper配置===========================
cloud:
zookeeper:
connect-string: 127.0.0.1:2181
#=============当前服务注册到ZooKeeper配置===========================
3. 服务消费方配置 RestTemplate 注入到容器中
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
@Configuration
public class ApplicationContextConfig {
@Bean
@LoadBalanced
public RestTemplate getRestTemplate(){
return new RestTemplate();
}
}
4. 服务消费方使用 RestTemplate 根据服务名称调用指定服务
import com.common.result.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;
@Controller
public class OrderController {
@Autowired
private RestTemplate restTemplate;
//服务提供方注册到ZooKeeper的服务名称
private String serverName = "cloud-provider-payment8004";
@RequestMapping(value = "getVal", method = RequestMethod.GET)
@ResponseBody
public JsonResult getVal() {
return restTemplate.getForObject("http://"+serverName+"/getVal",JsonResult.class);
}
}