1. 什么是服务治理
SpringCloud封装了Netflix公司开发的Eureka模块来实现服务治理
在传统的rpc远程调用框架中,管理每个服务与服务之间依赖关系比较复杂,管理比较复杂,所以需要使用服务治理,管理服务于服务之间依赖关系,可以实现服务调用、负载均衡、容错等,实现服务发现与注册。
2. 什么是服务注册与发现(通俗版)
简单讲就是微服务框架的服务注册中心,通过服务注册中心进行双向绑定每个(客户端、子类)服务,并维持心跳连接;
系统的维护人员就可以通过Eureka Server来监控系统中各个微服务是否正常运行。
3. Eureka包含两个组件:Eureka Server和Eureka Client
消费者端口80,提供者端口8001,Eureka端口7001
1.Server模块
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>cloud2020artifactId>
<groupId>springcloudgroupId>
<version>1.0-SNAPSHOTversion>
parent>
<modelVersion>4.0.0modelVersion>
<artifactId>cloud-eureka-server7001artifactId>
<dependencies>
<dependency>
<groupId>org.springframework.cloudgroupId>
<artifactId>spring-cloud-starter-netflix-eureka-serverartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-webartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-actuatorartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-devtoolsartifactId>
<scope>runtimescope>
<optional>trueoptional>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-testartifactId>
<scope>testscope>
dependency>
<dependency>
<groupId>springcloudgroupId>
<artifactId>cloud-api-commonsartifactId>
<version>${project.version}version>
dependency>
dependencies>
project>
jar包版本说明:
<dependency>
<groupId>org.springframework.cloudgroupId>
<artifactId>spring-cloud-starter-netflix-eureka-serverartifactId>
dependency>
<dependency>
<groupId>org.springframework.cloudgroupId>
<artifactId>spring-cloud-starter-eurekaartifactId>
dependency>
application.yml
server:
port: 7001
eureka:
instance:
hostname: localhost # eureka 服务端的实例名称
client:
# false 代表不向服务注册中心注册自己,因为它本身就是服务中心
register-with-eureka: false
# false 代表自己就是服务注册中心,自己的作用就是维护服务实例,并不需要去检索服务
fetch-registry: false
service-url:
# 设置与 Eureka Server 交互的地址,查询服务 和 注册服务都依赖这个地址
defaultZone: http://localhost:7001/eureka/
测试: http://localhost:7001
2.8001注册进Eureka成为提供者
pom.xml
<dependency>
<groupId>org.springframework.cloudgroupId>
<artifactId>spring-cloud-starter-netflix-eureka-clientartifactId>
dependency>
application.yml
eureka:
client:
# 注册进 Eureka 的服务中心
register-with-eureka: true
# 检索服务中心的其它服务
# 单节点无所谓,集群必须设置为true才能配合ribbon使用负载均衡
fetch-registry: true
service-url:
# 设置与 Eureka Server 交互的地址
defaultZone: http://localhost:7001/eureka/
主启动类
@SpringBootApplication
@EnableEurekaClient
public class PaymentMain8001 {
public static void main(String[] args) {
SpringApplication.run(PaymentMain8001.class,args);
}
}
测试: http://localhost:7001 能在Status列下看到8001节点
3、80注册进Eureka成为消费者
pom.xml
<dependency>
<groupId>org.springframework.cloudgroupId>
<artifactId>spring-cloud-starter-netflix-eureka-clientartifactId>
dependency>
application.yml
eureka:
client:
register-with-eureka: true
fetch-registry: true
service-url:
defaultZone: http://localhost:7001/eureka/
主启动类
@SpringBootApplication
@EnableEurekaClient
public class OrderMain80 {
public static void main(String[] args) {
SpringApplication.run(OrderMain80.class,args);
}
}
测试: http://localhost:7001 能在Status列下看到80节点
1、集群原理说明
问题:微服务RPC远程服务调用最核心的是什么?
高可用,试想你的注册中心只有一个only one, 它出故障了那就呵呵( ̄▽ ̄)"了,会导致整个为服务环境不可用,所以解决办法:搭建Eureka注册中心集群 ,实现负载均衡+故障容错
2、集群环境构建
参考cloud-eureka-server7001,新建cloud-eureka-server7002
127.0.0.1 eureka7001.com
127.0.0.1 eureka7002.com
Connect to eureka7001.com:7001 timed out
application.yml
与单机版不同的是,defaultZone指向了其他注册中心的地址
7001:
server:
port: 7001
eureka:
instance:
hostname: eureka7001.com # eureka 服务端的实例名称
client:
# false 代表不向服务注册中心注册自己,因为它本身就是服务中心
register-with-eureka: false
# false 代表自己就是服务注册中心,自己的作用就是维护服务实例,并不需要去检索服务
fetch-registry: false
service-url:
# 设置与 Eureka Server 交互的地址,查询服务 和 注册服务都依赖这个地址
#集群指向其他eureka
defaultZone: http://eureka7002.com:7002/eureka/
7002:
server:
port: 7002
eureka:
instance:
hostname: eureka7002.com # eureka 服务端的实例名称
client:
# false 代表不向服务注册中心注册自己,因为它本身就是服务中心
register-with-eureka: false
# false 代表自己就是服务注册中心,自己的作用就是维护服务实例,并不需要去检索服务
fetch-registry: false
service-url:
# 设置与 Eureka Server 交互的地址,查询服务 和 注册服务都依赖这个地址
# 集群指向其他eureka
defaultZone: http://eureka7001.com:7001/eureka/
测试: http://localhost:7001 能在DS Replicas看到7002;http://localhost:7002 能在DS Replicas看到7001
3、8001发布到2台Eureka集群
defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/
server:
port: 8001
spring:
application:
name: cloud-payment-service # 项目名,也是注册的名字
datasource:
type: com.alibaba.druid.pool.DruidDataSource #当前数据源操作类型
driver-class-name: org.gjt.mm.mysql.Driver #mysql驱动包
url: jdbc:mysql://localhost:3306/db2019?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=UTC
username: root
password: 12345
eureka:
client:
# 注册进 Eureka 的服务中心
register-with-eureka: true
# 检索 服务中心 的其它服务
fetch-registry: true
service-url:
# 设置与 Eureka Server 交互的地址
# 提供者注册到多个eureka中
defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/
mybatis:
mapper-locations: classpath:mapper/*.xml
type-aliases-package: com.atguigu.springcloud.entities # 所有Entity 别名类所在包
4、80发布到2台Eureka集群
defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/
server:
port: 80
spring:
application:
name: cloud-order-service
eureka:
client:
register-with-eureka: true
fetch-registry: true
service-url:
# 提供者注册到多个eureka中
defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/
测试: 先要启动EurekaServer,7001/7002服务,再要启动服务提供者provide8001,最后再启动消费者80
6、支付服务提供者8001集群环境构建
参考cloud-provider-payment8001新建cloud-provider-payment8002
server:
port: 8002
public class PaymentController {
@Resource
private PaymentService paymentService;
@Value("${server.port}") //读取yml中的值
private String serverPort;
@PostMapping(value = "/payment/create")
public CommonResult create(@RequestBody Payment payment){
int result = paymentService.create(payment);
log.info("***********插入结果:"+result);
if (result > 0){
return new CommonResult(200,"插入数据库成功,serverPort:"+serverPort,result);
}else {
return new CommonResult(444,"插入数据库失败",null);
}
}
@GetMapping(value = "/payment/get/{id}")
public CommonResult<Payment> getPaymentById(@PathVariable("id") Long id){
Payment payment = paymentService.getPaymentById(id);
log.info("***********查询结果:"+payment+"\t"+"oo哈哈");
if (payment!=null){
return new CommonResult(200,"查询成功,serverPort:"+serverPort,payment);
}else {
return new CommonResult(444,"查询失败",null);
}
}
}
7、消费者80
此时消费者一旦消费完之后,他以后访问的还是那台提供者。明显不对,原因在于消费者并没有去Eureka里找服务,而是自己找的
就是消费者如何访问 由这两个提供者组成的集群?
修改OrderController,将远程调用的地址,改成提供者在Eureka 上的名称,无需写端口号
@Slf4j
@RestController
public class OrderController {
//远程调用的地址,改成提供者在Eureka 上的名称,无需写端口号
public static final String PAYMENT_URL="http://cloud-payment-service";
@Resource
private RestTemplate restTemplate;
@PostMapping("/consumer/payment/create")
public CommonResult<Payment> create(@RequestBody Payment payment){
return restTemplate.postForObject(PAYMENT_URL+"/payment/create",//请求地址
payment,//请求参数
CommonResult.class);//返回类型
}
@GetMapping("/consumer/payment/get/{id}")
public CommonResult<Payment> getPaymentById(@PathVariable("id")Long id){
return restTemplate.getForObject(PAYMENT_URL+"/payment/get/"+id,//请求地址
CommonResult.class);//返回类型
}
}
开启负载均衡,CLOUD-PAYMENT-SERVICE有多个,如果不开启,不知道是哪一个,调用者不知道要调用集群下哪个服务,会报这个错误
ERROR:java.net.UnknownHostException:
@Configuration
public class ApplicationContextConfig {
@Bean
@LoadBalanced
public RestTemplate getRestTemplate(){
return new RestTemplate();
}
}
这时候,消费者消费的提供者多次访问就会变化了(这就是Ribbon的负载平衡功能)【即提供者会在8001和8002来回变动】
Ribbon和Eureka整合后Consumer可以直接调用服务而不用再关心地址和端口号,且该服务还有负载功能了。O(∩_∩)O
1、当前问题
8001同理
instance:
instance-id: payment8002 # 每个提供者的id不同,显示的不再是默认的项目名
server:
port: 8002
spring:
application:
name: cloud-payment-service # 项目名,也是注册的名字
datasource:
type: com.alibaba.druid.pool.DruidDataSource #当前数据源操作类型
driver-class-name: org.gjt.mm.mysql.Driver #mysql驱动包
url: jdbc:mysql://localhost:3306/db2019?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=UTC
username: root
password: 12345
eureka:
client:
# 注册进 Eureka 的服务中心
register-with-eureka: true
# 检索 服务中心 的其它服务
fetch-registry: true
service-url:
# 设置与 Eureka Server 交互的地址
defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/
instance:
instance-id: payment8002 # 每个提供者的id不同,显示的不再是默认的项目名
mybatis:
mapper-locations: classpath:mapper/*.xml
type-aliases-package: com.atguigu.springcloud.entities # 所有Entity 别名类所在包
修改8001和8002 YAML文件
prefer-ip-address: true # 可以显示ip地址
server:
port: 8002
spring:
application:
name: cloud-payment-service # 项目名,也是注册的名字
datasource:
type: com.alibaba.druid.pool.DruidDataSource #当前数据源操作类型
driver-class-name: org.gjt.mm.mysql.Driver #mysql驱动包
url: jdbc:mysql://localhost:3306/db2019?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=UTC
username: root
password: 12345
eureka:
client:
# 注册进 Eureka 的服务中心
register-with-eureka: true
# 检索 服务中心 的其它服务
fetch-registry: true
service-url:
# 设置与 Eureka Server 交互的地址
#defaultZone: http://eureka7001.com:7001/eureka/
defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/
instance:
instance-id: payment8002 # 每个提供者的id不同,显示的不再是默认的项目名
prefer-ip-address: true # 可以显示ip地址
mybatis:
mapper-locations: classpath:mapper/*.xml
type-aliases-package: com.atguigu.springcloud.entities # 所有Entity 别名类所在包
对于注册进eureka里面的微服务,可以通过服务发现来获得该服务的信息。
1、修改8001和8002的Controller
public class PaymentController {
@Resource
private DiscoveryClient discoveryClient;
@GetMapping(value = "/payment/discovery")
public Object discovery(){
//获得服务清单列表
List<String> services = discoveryClient.getServices();
for (String service : services) {
log.info("*****element:"+service);
}
// 根据具体服务进一步获得该微服务的信息
List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
for (ServiceInstance instance : instances) {
log.info(instance.getServiceId()+"\t"+instance.getHost()+"\t"+instance.getPort()+"\t"+instance.getUri());
}
return this.discoveryClient;
}
}
2、主启动类
@SpringBootApplication
@EnableEurekaClient
@EnableDiscoveryClient //服务发现
public class PaymentMain8002 {
public static void main(String[] args) {
SpringApplication.run(PaymentMain8002.class,args);
}
}
1、故障现象
保护模式主要用于一组客户端和Eureka Server之间存在网络分区场景下的保护。一旦进入保护模式,Eureka
Server将会尝试保护其服务注册表中的信息,不再删除服务注册表中的数据,也就是不会注销任何微服务。
如果在Eureka Server的首页看到以下这段提示,则说明Eureka进入了保护模式:
EMERGENCY! EUREKA MAY BE INCORRECTLY CLAIMING INSTANCES ARE UP WHEN THEY'RE NOT.
RENEWALS ARE LESSER THAN THRESHOLD AND HENCE THE INSTANCES ARE NOT BEING EXPIRED JUST TO BE SAFE
2、故障原因
为了防止EurekaClient可以正常运行,但是与EurekaServer网络不通情况下,EurekaServer**不会立刻**将EurekaClient服务剔除
默认情况下,如果EurekaServer在一定时间内没有接收到某个微服务实例的心跳,EurekaServer将会注销该实例(默认90秒)。
但是当网络分区故障发生(延时、卡顿、拥挤)时,微服务与EurekaServer之间无法正常通信,以上行为可能变得非常危险了,
因为微服务本身其实是健康的,**此时本不应该注销这个微服务**。
Eureka通过“自我保护模式”来解决这个问题——当EurekaServer节点在短时间内丢失过多客户端时(可能发生了网络分区故障),
那么这个节点就会进入自我保护模式。
在自我保护模式中,Eureka Server会保护服务注册表中的信息,不再注销任何服务实例。
综上,自我保护模式是一种应对网络异常的安全保护措施。它的架构哲学是宁可同时保留所有微服务
(健康的微服务和不健康的微服务都会保留)也不盲目注销任何健康的微服务。
使用自我保护模式,可以让Eureka集群更加的健壮、稳定。
一句话:某时刻某一个微服务不可用了,Eureka不会立刻清理,依旧会对该微服务的信息进行保存
属于CAP里面的AP分支
3、怎么禁止自我保护
现在可以不用集群版了,只用开一个。
注册中心eureakeServer端7001
出厂默认,自我保护机制是开启的 eureka.server.enable-self-preservation=true,使用eureka.server.enable-self-preservation = false 可以禁用自我保护模式
server:
# 关闭自我保护机制,保证不可用该服务被及时剔除
enable-self-preservation: false
eviction-interval-timer-in-ms: 2000
server:
port: 7001
eureka:
instance:
hostname: eureka7001.com # eureka 服务端的实例名称
client:
# false 代表不向服务注册中心注册自己,因为它本身就是服务中心
register-with-eureka: false
# false 代表自己就是服务注册中心,自己的作用就是维护服务实例,并不需要去检索服务
fetch-registry: false
service-url:
# 设置与 Eureka Server 交互的地址,查询服务 和 注册服务都依赖这个地址
defaultZone: http://eureka7001.com:7001/eureka/
server:
# 关闭自我保护机制,保证不可用该服务被及时剔除
enable-self-preservation: false
eviction-interval-timer-in-ms: 2000
生产者客户端eureakeClient端8001
# Eureka客户端像服务端发送心跳的时间间隔,单位s,默认30s
least-renewal-interval-in-seconds: 1
# Rureka服务端在收到最后一次心跳后等待时间上线,单位为s,默认90s,超时将剔除服务
least-expiration-duration-in-seconds: 2
server:
port: 8001
spring:
application:
name: cloud-payment-service # 项目名,也是注册的名字
datasource:
type: com.alibaba.druid.pool.DruidDataSource #当前数据源操作类型
driver-class-name: org.gjt.mm.mysql.Driver #mysql驱动包
url: jdbc:mysql://localhost:3306/db2019?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=UTC
username: root
password: 12345
eureka:
client:
# 注册进 Eureka 的服务中心
register-with-eureka: true
# 检索 服务中心 的其它服务
fetch-registry: true
service-url:
# 设置与 Eureka Server 交互的地址
# 提供者注册到多个eureka中
defaultZone: http://eureka7001.com:7001/eureka/
# defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/
instance:
instance-id: payment8001 # 每个提供者的id不同,显示的不再是默认的项目名
prefer-ip-address: true # 可以显示ip地址
# Eureka客户端像服务端发送心跳的时间间隔,单位s,默认30s
least-renewal-interval-in-seconds: 1
# Rureka服务端在收到最后一次心跳后等待时间上线,单位为s,默认90s,超时将剔除服务
least-expiration-duration-in-seconds: 2
mybatis:
mapper-locations: classpath:mapper/*.xml
type-aliases-package: com.atguigu.springcloud.entities # 所有Entity 别名类所在包
测试
先启动7001再启动8001,关闭8001,马上被删除了
Eureka停更说明:2.0后停更了。