zookeeper安装
参考地址: zookeeper单机和集群版安装
配置
服务提供者配置
springboot主启动类上添加注解@EnableDiscoveryClient
maven导入
<!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-zookeeper-discovery -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-zookeeper-discovery</artifactId>
<!--排除zk3.5.3 解决版本冲突-->
<exclusions>
<exclusion>
<groupId>org.apache.zookeeper</groupId>
<artifactId>zookeeper</artifactId>
</exclusion>
</exclusions>
</dependency>
<!--添加zk 3.4,9版本-->
<!-- https://mvnrepository.com/artifact/org.apache.zookeeper/zookeeper -->
<dependency>
<groupId>org.apache.zookeeper</groupId>
<artifactId>zookeeper</artifactId>
<version>3.4.9</version>
</dependency>
yml配置
server:
port: 8004
spring:
application:
name: cloud-provider-payment
cloud:
zookeeper:
connect-string: 192.168.136.140:2181 #服务端所在的ip地址
服务消费者配置
- springboot启动类添加
@SpringBootApplication
@EnableDiscoveryClient //添加该注解
public class OrderZKMain80 {
public static void main(String[] args) {
SpringApplication.run(OrderZKMain80.class,args);
}
}
- maven
<!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-zookeeper-discovery -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-zookeeper-discovery</artifactId>
<!--排除默认的zk3.5.3-->
<exclusions>
<exclusion>
<groupId>org.apache.zookeeper</groupId>
<artifactId>zookeeper</artifactId>
</exclusion>
</exclusions>
</dependency>
<!--添加你使用的zk 3.4,9版本-->
<!-- https://mvnrepository.com/artifact/org.apache.zookeeper/zookeeper -->
<dependency>
<groupId>org.apache.zookeeper</groupId>
<artifactId>zookeeper</artifactId>
<version>3.4.9</version>
</dependency>
- yml配置
server:
port: 80
spring:
application:
name: cloud-consumer-order #项目名也是服务名
cloud:
zookeeper:
connect-string: 192.168.88.3:2181 # zookeeper服务所在的地址
- 配置 RestTemplate
@Configuration
public class ApplicationContextConfig {
@LoadBalanced #添加该注解负载均衡调用服务
@Bean
public RestTemplate getRestTemplate() {
return new RestTemplate();
}
}
服务提供者和消费者都已经注册完成
启动
- 出现错误
- 解决zookeeper版本jar包冲突问题
修改后的pom文件
<!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-zookeeper-discovery -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-zookeeper-discovery</artifactId>
<!--排除zk3.5.3-->
<exclusions>
<exclusion>
<groupId>org.apache.zookeeper</groupId>
<artifactId>zookeeper</artifactId>
</exclusion>
</exclusions>
</dependency>
<!--添加zk 3.4,9版本-->
<!-- https://mvnrepository.com/artifact/org.apache.zookeeper/zookeeper -->
<dependency>
<groupId>org.apache.zookeeper</groupId>
<artifactId>zookeeper</artifactId>
<version>3.4.9</version>
</dependency>
测试
客户端启动后 zookeeper服务端注册的名
在一台电脑有zookeeper的找到zookeeper\bin下运行该命令连接 服务端
zkCli -server 192.168.88.3:2181
查看注册的服务
服务节点是临时节点还是持久节点
是临时节点 一但zookeeper向客户端进行心跳连接不到(客户端以关闭或与服务zookeeper断开)
zookeeper注销该节点
如下图 客户端关闭一段时间后zookeeper已经注销该服务
客户端开启后重新进行注册服务