1Eureka介绍
• Eureka 是 Netflix 公司开源的一个服务注册与发现的组件 。
• Eureka 和其他 Netflix 公司的服务组件(例如负载均衡、熔断器、网关等) 一起,被 Spring Cloud 社区整合为
Spring-Cloud-Netflix 模块。
• Eureka 包含两个组件:Eureka Server (注册中心) 和 Eureka Client (服务提供者、服务消费者)。
Eureka学习步骤
- 搭建 Provider 和 Consumer 服务。
- 使用 RestTemplate 完成远程调用。
- 搭建 Eureka Server 服务。
- 改造 Provider 和 Consumer 称为 Eureka Client。
- Consumer 服务 通过从 Eureka Server 中抓取 Provider
地址 完成 远程调用
2-Eureka快速入门
2.1-环境搭建
判断:15分钟内有85%以下的服务不能正常汇报 默认是30秒
- 创建父工程
创建module -父工程 Spring-cloud-parent
- 创建后的目录结构(删除src)
Spring-cloud-parent pom.xml
<!--spring boot 环境 -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.0.RELEASE</version>
<relativePath/>
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
2.2-创建服务提供者
- 创建服务提供者eureka-provider
eureka-provider pom.xml
<dependencies>
<!--spring boot web-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
GoodsController
package com.test.provider.controller;
import com.test.provider.domain.Goods;
import com.test.provider.service.GoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* Goods Controller 服务提供方
*/
@RestController
@RequestMapping("/goods")
public class GoodsController {
@Autowired
private GoodsService goodsService;
@GetMapping("/findOne/{id}")
public Goods findOne(@PathVariable("id") int id){
Goods goods = goodsService.findOne(id);
return goods;
}
}
GoodsService
package com.test.provider.service;
import com.test.provider.dao.GoodsDao;
import com.test.provider.domain.Goods;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* Goods 业务层
*/
@Service
public class GoodsService {
@Autowired
private GoodsDao goodsDao;
/**
* 根据id查询
* @param id
* @return
*/
public Goods findOne(int id){
return goodsDao.findOne(id);
}
}
Goods
package com.test.provider.domain;
/**
* 商品实体类
*/
public class Goods {
private int id;
private String title;//商品标题
private double price;//商品价格
private int count;//商品库存
public Goods() {
}
public Goods(int id, String title, double price, int count) {
this.id = id;
this.title = title;
this.price = price;
this.count = count;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
}
GoodsDao
package com.test.provider.dao;
import com.test.provider.domain.Goods;
import org.springframework.stereotype.Repository;
import javax.validation.ReportAsSingleViolation;
/**
* 商品Dao
*/
@Repository
public class GoodsDao {
public Goods findOne(int id){
return new Goods(1,"华为手机",3999,10000);
}
}
ProviderApp
package com.test.provider;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* 启动类
*/
@SpringBootApplication
public class ProviderApp {
public static void main(String[] args) {
SpringApplication.run(ProviderApp.class,args);
}
}
application.yml
server:
port: 8000
2.3-创建服务消费者
-
创建服务消费者eureka-consumer
-
最终目录结构
OrderController
package com.test.consumer.controller;
import com.test.consumer.domain.Goods;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* 服务的调用方
*/
@RestController
@RequestMapping("/order")
public class OrderController {
@GetMapping("/goods/{id}")
public Goods findGoodsById(@PathVariable("id") int id){
System.out.println("findGoodsById..."+id);
//远程调用Goods服务中的findOne接口
return null;
}
}
Goods
package com.test.consumer.domain;
/**
* 商品实体类
*/
public class Goods {
private int id;
private String title;//商品标题
private double price;//商品价格
private int count;//商品库存
public Goods() {
}
public Goods(int id, String title, double price, int count) {
this.id = id;
this.title = title;
this.price = price;
this.count = count;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
}
ConsumerApp
package com.test.consumer;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class ConsumerApp {
public static void main(String[] args) {
SpringApplication.run(ConsumerApp.class,args);
}
}
application.yml
server:
port: 9000
2.4-RestTemplate远程调用
• Spring提供的一种简单便捷的模板类,用于在 java 代码里访问 restful 服务。
• 其功能与 HttpClient 类似,但是 RestTemplate 实现更优雅,使用更方便。
修改消费方代码
RestTemplateConfig
package com.test.consumer.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
@Configuration
public class RestTemplateConfig {
@Bean
public RestTemplate restTemplate(){
return new RestTemplate();
}
}
OrderController
package com.test.consumer.controller;
import com.test.consumer.domain.Goods;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
/**
* 服务的调用方
*/
@RestController
@RequestMapping("/order")
public class OrderController {
@Autowired
private RestTemplate restTemplate;
@GetMapping("/goods/{id}")
public Goods findGoodsById(@PathVariable("id") int id){
System.out.println("findGoodsById..."+id);
/*
//远程调用Goods服务中的findOne接口
使用RestTemplate
1. 定义Bean restTemplate
2. 注入Bean
3. 调用方法
*/
String url = "http://localhost:8000/goods/findOne/"+id;
// 3. 调用方法
Goods goods = restTemplate.getForObject(url, Goods.class);
return goods;
}
}
2.5- Eureka Server搭建
① 创建 eureka-server 模块
② 引入 SpringCloud 和 euraka-server 相关依赖
Spring-cloud-parent pom.xml
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
<!--spring cloud 版本-->
<spring-cloud.version>Greenwich.RELEASE</spring-cloud.version>
</properties>
<!--引入Spring Cloud 依赖-->
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
eureka-server pom.xml
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- eureka-server -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
</dependencies>
EurekaApp
package com.test.eureka;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;
@SpringBootApplication
// 启用EurekaServer
@EnableEurekaServer
public class EurekaApp {
public static void main(String[] args) {
SpringApplication.run(EurekaApp.class,args);
}
}
③ 完成 Eureka Server 相关配置
application.yml
server:
port: 8761
# eureka 配置
# eureka 一共有4部分 配置
# 1. dashboard:eureka的web控制台配置
# 2. server:eureka的服务端配置
# 3. client:eureka的客户端配置
# 4. instance:eureka的实例配置
eureka:
instance:
hostname: localhost # 主机名
client:
service-url:
defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka # eureka服务端地址,将来客户端使用该地址和eureka进行通信
register-with-eureka: false # 是否将自己的路径 注册到eureka上。eureka server 不需要的,eureka provider client 需要
fetch-registry: false # 是否需要从eureka中抓取路径。eureka server 不需要的,eureka consumer client 需要
④ 启动该模块
2.6-Eureka控制台介绍
System status:系统状态信息
DS Replicas:集群信息
tance currently registered with Eureka: 实例注册信息
General Info :通用信息
Instance Info :实例信息
2.7-Eureka Client
① 引 eureka-client 相关依赖
eureka-provider pom.xml
<dependencies>
<!--spring boot web-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- eureka-client -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
</dependencies>
ProviderApp
package com.test.provider;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
/**
* 启动类
*/
@EnableEurekaClient //该注解 在新版本中可以省略
@SpringBootApplication
public class ProviderApp {
public static void main(String[] args) {
SpringApplication.run(ProviderApp.class,args);
}
}
② 完成 eureka client 相关配置
application.yml
server:
port: 8001
eureka:
instance:
hostname: localhost # 主机名
client:
service-url:
defaultZone: http://localhost:8761/eureka # eureka服务端地址,将来客户端使用该地址和eureka进行通信
spring:
application:
name: eureka-provider # 设置当前应用的名称。将来会在eureka中Application显示。将来需要使用该名称来获取路径
③ 启动 测试
服务消费者eureka-consumer通过修改,也可以展示在控制台
eureka-consumer在这里仅仅是我们人为定义为消费者,作为一个服务,其实既可以作为服务提供方,同时也可以作为服务消费方
ConsumerApp添加@EnableEurekaClient
package com.test.consumer;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
@EnableEurekaClient
@SpringBootApplication
public class ConsumerApp {
public static void main(String[] args) {
SpringApplication.run(ConsumerApp.class,args);
}
}
application.yml
server:
port: 9000
eureka:
instance:
hostname: localhost # 主机名
client:
service-url:
defaultZone: http://localhost:8761/eureka # eureka服务端地址,将来客户端使用该地址和eureka进行通信
spring:
application:
name: eureka-consumer # 设置当前应用的名称。将来会在eureka中Application显示。将来需要使用该名称来获取路径
2.8- 动态获取路径
ConsumerApp添加@EnableDiscoveryClient
package com.test.consumer;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
@EnableDiscoveryClient // 激活DiscoveryClient
@EnableEurekaClient
@SpringBootApplication
public class ConsumerApp {
public static void main(String[] args) {
SpringApplication.run(ConsumerApp.class,args);
}
}
OrderController修改代码动态获取路径
package com.test.consumer.controller;
import com.test.consumer.domain.Goods;
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.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import java.util.List;
/**
* 服务的调用方
*/
@RestController
@RequestMapping("/order")
public class OrderController {
@Autowired
private RestTemplate restTemplate;
@Autowired
private DiscoveryClient discoveryClient;
@GetMapping("/goods/{id}")
public Goods findGoodsById(@PathVariable("id") int id){
System.out.println("findGoodsById..."+id);
/*
//远程调用Goods服务中的findOne接口
使用RestTemplate
1. 定义Bean restTemplate
2. 注入Bean
3. 调用方法
*/
/*
动态从Eureka Server 中获取 provider 的 ip 和端口
1. 注入 DiscoveryClient 对象.激活
2. 调用方法
*/
//演示discoveryClient 使用
List<ServiceInstance> instances = discoveryClient.getInstances("EUREKA-PROVIDER");
//判断集合是否有数据
if(instances == null || instances.size() == 0){
//集合没有数据
return null;
}
ServiceInstance instance = instances.get(0);
String host = instance.getHost();//获取ip
int port = instance.getPort();//获取端口
System.out.println(host);
System.out.println(port);
String url = "http://"+host+":"+port+"/goods/findOne/"+id;
// 3. 调用方法
Goods goods = restTemplate.getForObject(url, Goods.class);
return goods;
}
}
2.9-Eureka属性
2.9.1-instance相关属性
Eureka Instance的配置信息全部保存在org.springframework.cloud.netflix.eureka.EurekaInstanceConfigBean配置类里,实际上它是com.netflix.appinfo.EurekaInstanceConfig的实现类,替代了netflix的com.netflix.appinfo.CloudInstanceConfig的默认实现。
Eureka Instance的配置信息全部以eureka.instance.xxx的格式配置。
配置列表
- appname = unknown
应用名,首先获取spring.application.name的值,如果取值为空,则取默认unknown。
- appGroupName = null
应用组名
- instanceEnabledOnit = false
实例注册到Eureka上是,是否立刻开启通讯。有时候应用在准备好服务之前需要一些预处理。
- nonSecurePort = 80
非安全的端口
- securePort = 443
安全端口
- nonSecurePortEnabled = true
是否开启非安全端口通讯
- securePortEnabled = false
是否开启安全端口通讯
- leaseRenewalIntervalInSeconds = 30
实例续约间隔时间
- leaseExpirationDurationInSeconds = 90
实例超时时间,表示最大leaseExpirationDurationInSeconds秒后没有续约,Server就认为他不可用了,随之就会将其剔除。
- virtualHostName = unknown
虚拟主机名,首先获取spring.application.name的值,如果取值为空,则取默认unknown。
- instanceId
注册到eureka上的唯一实例ID,不能与相同appname的其他实例重复。
- secureVirtualHostName = unknown
安全虚拟主机名,首先获取spring.application.name的值,如果取值为空,则取默认unknown。
- metadataMap = new HashMap();
实例元数据,可以供其他实例使用。比如spring-boot-admin在监控时,获取实例的上下文和端口。
- dataCenterInfo = new MyDataCenterInfo(DataCenterInfo.Name.MyOwn);
实例部署的数据中心。如AWS、MyOwn。
- ipAddress=null
实例的IP地址
- statusPageUrlPath = “/actuator/info”
实例状态页相对url
- statusPageUrl = null
实例状态页绝对URL
- homePageUrlPath = “/”
实例主页相对URL
- homePageUrl = null
实例主页绝对URL
- healthCheckUrlUrlPath = “/actuator/health”
实例健康检查相对URL
- healthCheckUrl = null
实例健康检查绝对URL
- secureHealthCheckUrl = null
实例安全的健康检查绝对URL
- namespace = “eureka”
配置属性的命名空间(Spring Cloud中被忽略)
- hostname = null
主机名,不配置的时候讲根据操作系统的主机名来获取
- preferIpAddress = false
是否优先使用IP地址作为主机名的标识
2.9.2-server相关属性
Eureka Server注册中心端的配置是对注册中心的特性配置。
Eureka Server的配置全部在org.springframework.cloud.netflix.eureka.server.EurekaServerConfigBean里,实际上它是com.netflix.eureka.EurekaServerConfig的实现类,替代了netflix的默认实现。
Eureka Server的配置全部以eureka.server.xxx的格式进行配置。
配置列表
- enableSelfPreservation=true
是否开启自我保护
- renewalPercentThreshold = 0.85
自我保护续约百分比阀值因子。如果实际续约数小于续约数阀值,则开启自我保护
- renewalThresholdUpdateIntervalMs = 15 * 60 * 1000
续约数阀值更新频率。
- peerEurekaNodesUpdateIntervalMs = 10 * 60 * 1000
Eureka Server节点更新频率。
- enableReplicatedRequestCompression = false
是否启用复制请求压缩。
- waitTimeInMsWhenSyncEmpty=5 * 60 * 1000
当从其他节点同步实例信息为空时等待的时间。
- peerNodeConnectTimeoutMs=200
节点间连接的超时时间。
- peerNodeReadTimeoutMs=200
节点间读取信息的超时时间。
- peerNodeTotalConnections=1000
节点间连接总数。
- peerNodeTotalConnectionsPerHost = 500;
单个节点间连接总数。
- peerNodeConnectionIdleTimeoutSeconds = 30;
节点间连接空闲超时时间。
- retentionTimeInMSInDeltaQueue = 3 * MINUTES;
增量队列的缓存时间。
- deltaRetentionTimerIntervalInMs = 30 * 1000;
清理增量队列中过期的频率。
- evictionIntervalTimerInMs = 60 * 1000;
剔除任务频率。
- responseCacheAutoExpirationInSeconds = 180;
注册列表缓存超时时间(当注册列表没有变化时)
- responseCacheUpdateIntervalMs = 30 * 1000;
注册列表缓存更新频率。
- useReadOnlyResponseCache = true;
是否开启注册列表的二级缓存。
- disableDelta=false。
是否为client提供增量信息。
- maxThreadsForStatusReplication = 1;
状态同步的最大线程数。
- maxElementsInStatusReplicationPool = 10000;
状态同步队列的最大容量。
- syncWhenTimestampDiffers = true;
当时间差异时是否同步。
- registrySyncRetries = 0;
注册信息同步重试次数。
- registrySyncRetryWaitMs = 30 * 1000;
注册信息同步重试期间的时间间隔。
- maxElementsInPeerReplicationPool = 10000;
节点间同步事件的最大容量。
- minThreadsForPeerReplication = 5;
节点间同步的最小线程数。
- maxThreadsForPeerReplication = 20;
节点间同步的最大线程数。
- maxTimeForReplication = 30000;
节点间同步的最大时间,单位为毫秒。
- disableDeltaForRemoteRegions = false;
是否启用远程区域增量。
- remoteRegionConnectTimeoutMs = 1000;
远程区域连接超时时间。
- remoteRegionReadTimeoutMs = 1000;
远程区域读取超时时间。
- remoteRegionTotalConnections = 1000;
远程区域最大连接数
- remoteRegionTotalConnectionsPerHost = 500;
远程区域单机连接数
- remoteRegionConnectionIdleTimeoutSeconds = 30;
远程区域连接空闲超时时间。
- remoteRegionRegistryFetchInterval = 30;
远程区域注册信息拉取频率。
- remoteRegionFetchThreadPoolSize = 20;
远程区域注册信息线程数。
Eureka Server 在运行期间会去统计心跳失败比例在 15 分钟之内是否低于 85%,如果低于 85%,Eureka Server 会将这些实例保护起来,让这些实例不会过期,但是在保护期内如果服务刚好这个服务提供者非正常下线了,此时服务消费者就会拿到一个无效的服务实例,此时会调用失败,对于这个问题需要服务消费者端要有一些容错机制,如重试,断路器等。
我们在单机测试的时候很容易满足心跳失败比例在 15 分钟之内低于 85%,这个时候就会触发 Eureka 的保护机制,一旦开启了保护机制,则服务注册中心维护的服务实例就不是那么准确了,此时我们可以使用eureka.server.enable-self-preservation=false来关闭保护机制,这样可以确保注册中心中不可用的实例被及时的剔除(不推荐)。
自我保护模式被激活的条件是:在 1 分钟后,Renews (last min) < Renews threshold。
这两个参数的意思:
• Renews threshold:Eureka Server 期望每分钟收到客户端实例续约的总数。
• Renews (last min):Eureka Server 最后 1 分钟收到客户端实例续约的总数。
Lease expiration enabled 是否启用租约过期
当前实例心跳占比不满85%,Eureka自动保护机制启动启动后该值为false,当实例心跳占比满足了85%时,Eureka将会自动关闭自我保护机制,此时此值为true。
续约: 客户端向服务端发送一次心跳,来证明客户端在线。 理解:相当于服务端和客户端签订了一份合同,到期了就要续约,保证合同能够继续进行。
在Eureka源码中关于Renews thresshold阀值的计算函数如下
protected void updateRenewsPerMinThreshold() {
this.numberOfRenewsPerMinThreshold = (int)((double)this.expectedNumberOfClientsSendingRenews * (60.0D / (double)this.serverConfig.getExpectedClientRenewalIntervalSeconds()) * this.serverConfig.getRenewalPercentThreshold());
}
expectedNumberOfClientsSendingRenews: 注册的实例数
getExpectedClientRenewalIntervalSeconds:服务端期望的客户端续约间隔,既服务端每分钟期望接收的心跳间隔
getRenewalPercentThreshold(): 阀值系数 默认为0.85
当eureka-server注册自己时:
Renews thresshold = (注册的实例数*(60/服务端期望的客户端心跳间隔))* 阀值
当eureka-server不注册自己时:
Renews thresshold = (注册的实例数+1)*(60/服务端期望的客户端心跳间隔))* 阀值
注册的实例数:就是包括服务端集群和客户端在内的所有已经注册的实例。在控制台的Instances currently registered with Eureka中显示。
客户端一分钟心跳数:Eureka客户端eureka.instance.ease-renewal-interval-in-seconds配置的值,默认为30秒,既每30秒向服务端发送一次心跳。
阀值:我们在Eureka集群服务端配置的eureka.instance.renewal-percent-threshold. 不需要配置,默认值为0.85. 既15分钟内Eureka实例的心跳数低于85%时,启动自我保护机制。
如果Renews thresshold => Renews(last min)时,我们将进入自我保护机制中。
当我们将服务重新启动后,1-2分钟后,Renews thresshold < Renews(last min),我们也会自动退出自我保护机制。
3-Eureka高可用
- 准备两个Eureka Server
- 分别进行配置,相互注册
- Eureka Client 分别注册到这两个 Eureka Server中
3.1-搭建
创建eureka-server-1
pom.xml
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- eureka-server -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
</dependencies>
application.yml
server:
port: 8761
eureka:
instance:
hostname: eureka-server1 # 主机名
client:
service-url:
defaultZone: http://eureka-server2:8762/eureka
register-with-eureka: true # 是否将自己的路径 注册到eureka上。eureka server 不需要的,eureka provider client 需要
fetch-registry: true # 是否需要从eureka中抓取路径。eureka server 不需要的,eureka consumer client 需要
spring:
application:
name: eureka-server-ha
Eureka1App
package eureka;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;
@SpringBootApplication
// 启用EurekaServer
@EnableEurekaServer
public class Eureka1App {
public static void main(String[] args) {
SpringApplication.run(Eureka1App.class,args);
}
}
创建eureka-server-2
pom.xml
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- eureka-server -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
</dependencies>
application.yml
server:
port: 8762
eureka:
instance:
hostname: eureka-server2 # 主机名
client:
service-url:
defaultZone: http://eureka-server1:8761/eureka
register-with-eureka: true # 是否将自己的路径 注册到eureka上。eureka server 不需要的,eureka provider client 需要
fetch-registry: true # 是否需要从eureka中抓取路径。eureka server 不需要的,eureka consumer client 需要
spring:
application:
name: eureka-server-ha
Eureka2App
package eureka;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;
@SpringBootApplication
// 启用EurekaServer
@EnableEurekaServer
public class Eureka2App {
public static void main(String[] args) {
SpringApplication.run(Eureka2App.class,args);
}
}
修改本地host
3.2-客户端测试
修改服务提供者和服务消费者配置文件中的注册服务地址
eureka-provider
application.yml
server:
port: 8001
eureka:
instance:
hostname: localhost # 主机名
prefer-ip-address: true # 将当前实例的ip注册到eureka server 中。默认是false 注册主机名
ip-address: 127.0.0.1 # 设置当前实例的ip
instance-id: ${eureka.instance.ip-address}:${spring.application.name}:${server.port} # 设置web控制台显示的 实例id
lease-renewal-interval-in-seconds: 3 # 每隔3 秒发一次心跳包
lease-expiration-duration-in-seconds: 9 # 如果9秒没有发心跳包,服务器呀,你把我干掉吧~
client:
service-url:
defaultZone: http://eureka-server1:8761/eureka,http://eureka-server2:8762/eureka # eureka服务端地址,将来客户端使用该地址和eureka进行通信
spring:
application:
name: eureka-provider # 设置当前应用的名称。将来会在eureka中Application显示。将来需要使用该名称来获取路径
eureka-consumer
application.yml
server:
port: 9000
eureka:
instance:
hostname: localhost # 主机名
client:
service-url:
defaultZone: http://eureka-server1:8761/eureka,http://eureka-server2:8762/eureka # eureka服务端地址,将来客户端使用该地址和eureka进行通信
spring:
application:
name: eureka-consumer # 设置当前应用的名称。将来会在eureka中Application显示。将来需要使用该名称来获取路径
测试结果
4-Consul
4.1-Consul 概述
Consul 是由 HashiCorp 基于 Go 语言开发的,支持多数据中心,分布式高可用的服务发布和注册服务软件。
• 用于实现分布式系统的服务发现与配置。
• 使用起来也较 为简单。具有天然可移植性(支持Linux、windows和Mac OS X);安装包仅包含一个可执行文件,
方便部署 。
• 官网地址: https://www.consul.io
启动consul
dev模式:不会持久化数据
启动成功
控制台
4.2快速入门
- 搭建 Provider 和 Consumer 服务。
- 使用 RestTemplate 完成远程调用。
- 将Provider服务注册到Consul中。
- Consumer 服务 通过从 Consul 中抓取 Provider 地
址 完成 远程调用
Provider
pom.xml
<dependencies>
<!--consul 客户端-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-consul-discovery</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
</dependencies>
application.yml
server:
port: 8000
spring:
cloud:
consul:
host: localhost # consul 服务端的 ip
port: 8500 # consul 服务端的端口 默认8500
discovery:
service-name: ${spring.application.name} # 当前应用注册到consul的名称
prefer-ip-address: true # 注册ip
application:
name: consul-provider # 应用名称
consumer pom.xml
<dependencies>
<!--consul 客户端-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-consul-discovery</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
</dependencies>
application.yml
server:
port: 9000
spring:
cloud:
consul:
host: localhost # consul 服务端的 ip
port: 8500 # consul 服务端的端口 默认8500
discovery:
service-name: ${spring.application.name} # 当前应用注册到consul的名称
prefer-ip-address: true # 注册ip
application:
name: consul-consumer # 应用名称
OrderController
package com.test.consul.controller;
import com.test.consul.domain.Goods;
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.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import java.util.List;
/**
* 服务的调用方
*/
@RestController
@RequestMapping("/order")
public class OrderController {
@Autowired
private RestTemplate restTemplate;
@Autowired
private DiscoveryClient discoveryClient;
@GetMapping("/goods/{id}")
public Goods findGoodsById(@PathVariable("id") int id){
//演示discoveryClient 使用
List<ServiceInstance> instances = discoveryClient.getInstances("consul-PROVIDER");
//判断集合是否有数据
if(instances == null || instances.size() == 0){
//集合没有数据
return null;
}
ServiceInstance instance = instances.get(0);
String host = instance.getHost();//获取ip
int port = instance.getPort();//获取端口
System.out.println(host);
System.out.println(port);
String url = "http://"+host+":"+port+"/goods/findOne/"+id;
// 3. 调用方法
Goods goods = restTemplate.getForObject(url, Goods.class);
return goods;
}
}