springcloud学习-Eureka服务注册与发现
文章目录
1. 什么是Eureka(类似zookeeper)
Eureka是Netflix开发的服务发现框架,本身是一个基于REST的服务,主要用于定位运行在AWS域中的中间层服务,以达到负载均衡和中间层服务故障转移的目的。
SpringCloud将它集成在其子项目spring-cloud-netflix中,以实现SpringCloud的服务发现功能。
2. Eureka包含两个组件:EureKa Server和EureKa client
3. Eureka服务端使用
3.1 导入依赖
<!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-netflix-eureka-server -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
<version>3.0.1</version>
</dependency>
3.2 编写配置文件
server:
port: 7001
#EureKa配置
eureka:
instance:
hostname: localhost #Eureka服务端实例名称
client:
register-with-eureka: false #表示是否向eureka注册中心注册自己
fetch-registry: false #false位自己位注册中心
service-url: #监控页面
defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/
3.3 注解开启服务
@SpringBootApplication
@EnableEurekaServer //开启EurekaServer
public class start {
public static void main(String[] args) {
SpringApplication.run(start.class,args);
}
}
3.4 访问监控页面http://localhost:7001/ - 监控页面不用添加/eureka/
填写自己配置文件中的的监控页面地址,没有填写则默认配置以及地址如下:
public EurekaClientConfigBean() {
this.serviceUrl.put("defaultZone", "http://localhost:8761/eureka/");
this.gZipContent = true;
this.useDnsForFetchingServiceUrls = false;
this.registerWithEureka = true;
this.preferSameZoneEureka = true;
this.availabilityZones = new HashMap();
this.filterOnlyUpInstances = true;
this.fetchRegistry = true;
this.dollarReplacement = "_-";
this.escapeCharReplacement = "__";
this.allowRedirects = false;
this.onDemandUpdateStatusChange = true;
this.clientDataAccept = EurekaAccept.full.name();
this.shouldUnregisterOnShutdown = true;
this.shouldEnforceRegistrationAtInit = false;
this.order = 0;
}
3.5监控页面展示
4. 服务提供者在Eureka服务端注册服务
4.1 导入依赖
<!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-eureka -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
<version>1.4.7.RELEASE</version>
</dependency>
4.2 编写配置文件
#Eureka配置-服务注册 -----service-url填入要注册的服务端URL
eureka:
client:
service-url:
defaultZone: http://localhost:7001/eureka/
4.3 注解开启服务
@EnableEurekaClient
4.4 启动服务提供者后监控页面
4.5 修改监控页面服务描述信息Status
在配置文件中添加 eureka.instance.instance-id,如下:
#Eureka配置-服务注册
eureka:
client:
service-url:
defaultZone: http://localhost:7001/eureka/
instance: #修改Status信息
instance-id: The first provider for dept
4.6 修改后的监控页面
4.7 导入acluator依赖进行信息配置
4.8 通过装配DiscoveryClient获取服务发现的信息
5. Eureka集群配置
5.1 相互绑定
在yaml文件中挂在其他Eureka
eureka:
client:
service-url:
defaultZone: http://localhost:7001/eureka/,其他注册中心url
6. CAP原则
CAP理论指的是一个分布式系统最多只能同时满足一致性(Consistency)、可用性(Availability)和分区容错性(Partition tolerance)这三项中的两项。分布式系统必须满足P(分区容错性):
zookeeper保证的是CP:master节点挂掉会从新选举,期间服务不可用,但保证了一致性。
Eureka保证的是AP:节点平等,挂掉不影响服务,保证了可用性。