服务注册与发现【Zookeeper】
Zookeeper 服务器取代 Eureka 服务器,作为服务注册中心(因我本地没有安装Zookeeper,则下面内容无本人实战案例,引用的其他案例来说明)
服务提供者:
新建一个服务提供者 cloud-provider-payment8004(与前面Eureka服务提供者区分),端口8004
引入POM,其他的依赖和其他服务提供者一样,只是少了EurekaClient依赖,多了Zookeeper依赖:
<!-- 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>
</dependency>
YML
server:
port: 8004
spring:
application:
name: cloud-provider-payment
cloud:
zookeeper:
connect-string: 192.168.136.140:2181
主启动类:添加注解:@EnableDiscoveryClient
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
@SpringBootApplication
@EnableDiscoveryClient
public class ProviderPaymentApplication8004 {
public static void main(String[] args) {
SpringApplication.run(PaymentMain8004.class,args);
}
}
启动问题:
如果引入的Zookeeper jar包版本和安装的Zookeeper版本不一致,就会启动报错,类似如下问题:
此时,我们就可以排除Zookeeper的POM中自带的 zookeeper*. jar,然后引入和我们安装版本对应的jar包版本:
<!-- 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>
服务消费者:
新建 cloud-consumerzk-order8081
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>
</dependency>
YML:
server:
port: 80
spring:
application:
name: cloud-consumer-order
cloud:
zookeeper:
connect-string: 192.168.136.140:2181
主启动:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
@SpringBootApplication
@EnableDiscoveryClient
public class OrderZKMain8081 {
public static void main(String[] args) {
SpringApplication.run(OrderZKMain8081.class,args);
}
}
其他的业务实现,和Eureka一样。
总结:
将服务注册中心,从Eureka 换成Zookeeper 后,涉及到需要修改的地方就只有:
1. 服务提供者和消费者,从引入EurekaClient 依赖,切换成引入 Zookeeper 依赖。
2. yml 文件修改:原来配置的Eureka注册中心地址,换成Zookeeper注册中心地址。
3. 主启动类:去掉 @EnableEurekaClient 的 Eureka注解,改为 @EnableDiscoveryClient 的Zookeeper注解。
4. 如果遇到jar包版本冲突而导致的启动失败问题,那就剔除掉默认引入的jar包而重新引入和安装的Zookeeper版本一致的jar包。