在spring cloud组件中 spring cloud Hystrix是防雪崩的利器,它也是基于Netflix提供的Hystrix进行封装的。
一.服务容错降级
1.介绍
优先核心服务,非核心服务不可用或弱可用
通过HystrixCommand注解指定
fallbackMethod(回退函数)中具体实现降级逻辑
2.代码实现
首先是一个基本的restful请求(可以在customer启动类上将@SpringBootApplication替换成@SpringCloudApplication)
// 断路器配置,当无法调用如下方法时,就会调用自定的hiError方法。
@HystrixCommand(fallbackMethod = "hiError")
public String hiService(String name)
{
RestTemplate restTemplate = new RestTemplate();
String data = restTemplate.getForObject("http://service-provider/hi?name=" + name, String.class);
return data;
}
public String hiError(String name)
{
return "hey " +
name + ", there is some problem with hi page";
}
当hiService方法出错时,服务降级会执行hiError方法。
但是,如果超时之后,也会进行服务降级,那么就需要根据需求配置超时时间。
#配置hystrix的超时时间
hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds=5000
#配置方法体的超时时间
hystrix.command.方法名.execution.isolation.thread.timeoutInMilliseconds=5000
也可以注解对指定方法配置超时时间
// 断路器配置,当无法调用如下方法时,就会调用自定的hiError方法。
@HystrixCommand(fallbackMethod = "hiError",
commandProperties = {@HystrixProperty(name="execution.isolation.thread.timeoutInMilliseconds",value = "5000")})
public String hiService(String name)
{
String data = restTemplate.getForObject("http://service-provider/hi?name=" + name, String.class);
return data;
}
无论使用哪种配置,要实现服务降级,都需要在方法体上加入注解@HystrixCommand
另外,如果使用的是feign,则使用的是ribbon的超时设置
#ribbon的超时时间
ribbon.ReadTimeout=3000
ribbon.ConnectTimeout=3000
二.熔断机制
熔断机制:当一段时间内请求量超过限制的时候,会进行断路器模式。
断路器模式:将受保护的服务封装在一个可以监控故障的断路器对象中去,当故障达到一定的值,断路器将会跳闸,断路器对象返回错误信息。
1.断路器配置
@HystrixCommand(commandProperties = {
@HystrixProperty(name = "circuitBreaker.enabled",value = "true"),
@HystrixProperty(name = "circuitBreaker.requestVolumeThreshold",value = "10"),//最小请求数
@HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds",value = "10000"),//10秒时间窗口(进行请求统计)。休眠之后再次设置断路器half open(允许正常请求)
@HystrixProperty(name="circuitBreaker.errorThresholdPercentage",value = "60")})//百分比条件,时间窗口内达到最小请求数,错误率高达60%,则打开断路器
#断路器
feign.hystrix.enabled=true