服务降级

微服务基本组成

Hystrix

概述

Hystrix断路器是一个用于处理分布式系统的延迟和容错的开源库,在分布式系统中,许多依赖不可避免的会调用失败,Hystrix能够保证在一个依赖出问题的情况下,不会导致整体服务失败,避免级联故障,以提高分布式系统的弹性

断路器本身是一种开关装置,当某个服务单元发生故障之后,通过断路器的故障监控,向调用方法返回一个符合预期的、可处理的备选响应(FallBack),而不是长时间的等待或者抛出调用方法方无法处理的异常,这样就保证了服务调用方的线程不会被长时间、不必要的占用,从而避免了故障在分布式系统中的蔓延,乃至雪崩

服务雪崩

作用:服务降级(fallback),服务熔断(break),服务限流(flowlimit),接近实时的监控

服务降级

服务器在出现故障时立即给客户端一个提示,不让客户端继续等待,fallback

出现服务降级的情况

  • 程序运行异常
  • 超时
  • 服务熔断触发服务降级
  • 线程池/信号量打满也会导致服务降级

服务熔断

当服务器达到最大访问后,直接拒绝访问,然后调用服务降级的方法并返回友好提示
熔断机制

熔断器起作用的情况

服务限流

秒杀等高并发操作时,进行有序的进行

案例

服务降级服务端

pom引入

1
2
3
4
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>

启动类

1
2
3
4
5
6
7
8
@SpringBootApplication
@EnableEurekaClient
@EnableCircuitBreaker // 开启
public class HystrixPaymentMain {
public static void main(String[] args) {
SpringApplication.run(HystrixPaymentMain. class,args);
}
}

service方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
@HystrixCommand(fallbackMethod = "paymentInfo_TimeOutHandler",commandProperties = {
@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value = "3000") //3秒钟以内就是正常的业务逻辑
})
public String paymentInfoTimeOut(Integer id){
int timeNumber = 5;
// 超时5秒
try { TimeUnit.SECONDS.sleep(timeNumber); }catch (Exception e) {e.printStackTrace();}
return "线程池:"+Thread.currentThread().getName()+", paymentInfo_TimeOut,Id:"+id+"\t"+"哈哈哈"+" 耗时(秒)"+timeNumber;
}

//兜底方法
public String paymentInfo_TimeOutHandler(Integer id){
return "线程池:"+Thread.currentThread().getName()+" paymentInfo_TimeOutHandler系统繁忙, 请稍候再试 ,id: "+id+"\t"+"哭了哇呜";
}

服务降级客户端

和Feign一起使用

pom引入

1
2
3
4
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>

yml开启

1
2
3
feign:
hystrix:
enabled: true #如果处理自身的容错就开启。开启方式与生产端不一样。

service方法

1
2
3
4
5
6
7
8
9
10
@Component
// fallback后面是处理异常的方法
@FeignClient(value = "CLOUD-PROVIDER-HYSTRIX-PAYMENT", fallback = PaymentFallbackService.class)
public interface PaymentHystrixService {
@GetMapping("/payment/hystrix/ok/{id}")
String paymentInfo_OK(@PathVariable("id") Integer id);

@GetMapping("/payment/hystrix/timeout/{id}")
String paymentInfo_TimeOut(@PathVariable("id") Integer id);
}
1
2
3
4
5
6
7
8
9
10
11
12
@Component
public class PaymentFallbackService implements PaymentHystrixService{
@Override
public String paymentInfo_OK(Integer id) {
return "-----PaymentFallbackService fall back-paymentInfo_OK , (┬_┬)";
}

@Override
public String paymentInfo_TimeOut(Integer id) {
return "-----PaymentFallbackService fall back-paymentInfo_TimeOut , (┬_┬)";
}
}

相关文章

SpringCloud

服务注册与发现

SpringCloud-OpenFeign问题

SpringCloud-GateWay工具类

DockerCompose常用软件配置

SpringQuartz动态定时任务

Redis集群搭建

redis分布式锁

服务链路追踪

K8S