1 概述
1)服务雪崩是啥?
2)Hystrix介绍
3)Hystrix能干啥?
1,服务降级(fallback)
比如当某个服务繁忙,不能让客户端的请求一直等待,应该立刻返回给客户端一个备选方案
2,服务熔断(break)
当某个服务出现问题,卡死了,不能让用户一直等待,需要关闭所有对此服务的访问,然后调用服务降级
详细讲解:
类似于保险丝达到最大服务访问后,直接拒绝访问,拉闸限电,然后调用服务降级的方法并返回优好提示,相当于->服务降级->进而熔断->恢复调用链路
比如并发达到1000,我们就拒绝其他用户访问,在有用户访问,就访问降级方法
3,服务限流(flowlimit)
限流,比如秒杀场景,不能访问用户瞬间都访问服务器,限制一次只可以有多少请求
2 服务降级使用
1,服务端降级
1)架包
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
- 启动类添加注解@EnableCircuitBreaker
@SpringBootApplication
@EnableCircuitBreaker
public class PaymentHystrixApplication {
public static void main(String[] args) {
SpringApplication.run(PaymentHystrixApplication.class, args);
System.out.println("启动成功");
}
}
3)接口添加@HystrixCommand
/**
* 超时访问,设置自身调用超时的峰值,峰值内正常运行,超过了峰值需要服务降级 自动调用fallbackMethod 指定的方法
* 超时异常或者运行异常 都会进行服务降级
* 设置请求是1.5秒,但是接口请求是3秒
*/
@HystrixCommand(fallbackMethod = "paymentInfoTimeOutHandler", commandProperties = {
@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "1500")
})
public String paymentInfoTimeOut(Integer id) {
// int age = 10/0;//程序异常时降级
int second = 3000;
try {
TimeUnit.MILLISECONDS.sleep(second);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "线程池: " + Thread.currentThread(