发布时间:2023-07-11 10:00
1、项目背景介绍
spring cloud 中提供了三种注册中心,分别是Eureka, zookeeper,Consul,前面我们采用Eureka实现了服务的注册与发现,今天我们采用zookeeper做为注册中心,和各位一样注册中心我们应该怎么选,他们各自的优势在哪,下面用图表进行三种形式的注册中心简单对比。
在分布式系统中有一个重要的概念叫CAP理论。在总结两者Eureka和zookeeper的区别之前,我们先来看一个 CAP 理论。什么叫 CAP 理论呢?CAP 理论是由 Eric Brewer 教授提出,是分布式系统中的一个重要的概念。具体如下:
C(Consistency):数据一致性。大家都知道,分布式系统中,数据会有副本。由于网络或者机器故障等因素,可能有些副本数据写入正确,有些却写入错误或者失败,这样就导致了数据的不一致了。而满足数据一致性规则,就是保证所有数据都要同步。
A(Availability):可用性。我们需要获取什么数据时,都能够正常的获取到想要的数据(当然,允许可接受范围内的网络延迟),也就是说,要保证任何时候请求数据都能够正常响应。
P(Partition Tolerance):分区容错性。当网络通信发生故障时,集群仍然可用,不会因为某个节点挂了或者存在问题,而影响整个系统的正常运作。
对于分布式系统来说,出现网络分区是不可避免的,因此分区容错性是必须要具备的,也就是说,CAP三者,P是必须的,是个客观存在的事实,不可避免,也无法绕过,大家可以根据自己对知识的掌握和场景选择不同的注册中心进行管理自己的项目。
2、项目功能介绍
依旧是spring cloud 组件,今天用zookeeper作为服务注册中心进行服务的注册与发现。
3、项目的环境搭建
今天我们用单机版的Zookeeper进行项目的搭建,单机版的zookeer很简单,目前采用的版本是3.4.12
4、项目总体核心代码
4.1、项目依赖
org.springframework.boot
spring-boot-starter-web
org.springframework.cloud
spring-cloud-starter-zookeeper-all
org.apache.zookeeper
zookeeper
3.4.12
4.1、项目代码
----------------------application文件------------------------------
package com.gpdi;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
@EnableDiscoveryClient
@SpringBootApplication
public class SpringCloudDiscoverApplication {
public static void main(String[] args) {
SpringApplication.run(SpringCloudDiscoverApplication.class, args);
}
}
-------------------------Controller文件-------------------------------------
package com.gpdi.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.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import java.util.*;
@RestController
public class ServiceController {
/**
* @desc:返回所有的服务名称
*/
@GetMapping("/services")
public List getAllServices() {
return discoveryClient.getServices();
}
/**
* @desc:获取实例中的相关信息(包含机器的名称(Host)、服务名称、端口等信息)
*/
@GetMapping("/service/instances/{serviceName}")
public List getAllServiceInstances(@PathVariable String serviceName) {
List list = discoveryClient.getInstances(serviceName);
List instanceList = new Vector<>();
list.forEach((a) -> {
instanceList.add("http://" + a.getHost() + "/" +
a.getServiceId() + "/" + a.getPort());
});
return instanceList;
}
@Autowired
private DiscoveryClient discoveryClient;
}
---------------------------配置文件------------------------------------------
spring.application.name = spring-cloud-discover
# 随机服务端口
server.port = 8083
#management.server.port = 7071
# 开放 所有Web 管理 Endpoints
management.endpoints.web.exposure.include = *
#spring.cloud.zookeeper.discovery.instance-host=${spring.cloud.client.ipAddress}