保护1:服务容错
在整个微服务架构中,每个服务之间都可能会进行相互调用,某些服务如果在被调用的过程中出现故障(就算为某些重要服务部署集群,同样不可能保证100%高可用),可能就会出现连锁效应,导致整个调用链路不可用,进而让这个微服务架构的系统变得不可用。这种情况称为服务雪崩效应。比如:某个业务需要服务A、服务B、服务C配合完成,整个调用链路是服务A-->服务B-->服务C,如果此时服务B或者服务C任何一个变得不可用,就会导致整个链路变得不可用,进而导致整个微服务架构的系统变得不可用。为了使系统变得更加健壮,就需要对服务进行容错处理。
引入依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
开启Hystrix功能
在启动类中加上以下注解(或者使用@EnableCircuitBreaker,@EnableHystrix注解包含了@EnableCircuitBreaker,任意使用一个即可):
@EnableHystrix
一个简单的Hstrix示例
@Controller
public class HystrixController {
// 说明:Hystrix基于AOP编写.这里不一定限制Hystrix的功能在Controller中使用,同样可以在Service层中使用
@PostMapping("/sever4/hystrix/api0")
@ResponseBody
// @HystrixCommand注解声明当前方法开启Hystrix功能.
// fallbackMethod属性:当被注解的方法产生异常(比如调用其他服务失败),则会触发defaultErrorMethod(String isHtstrix)方法,即业务回退方法
// 注意:回退方法的形参必须和被注解的方法一致。比如这里的:methodA(String isHtstrix)和defaultErrorMethod(String isHtstrix)
@HystrixCommand(fallbackMethod = "defaultErrorMethod")
public String methodA(String isHtstrix) {
if("1".equals(isHtstrix)) {
// 假设里面的代码是在调用其他服务,产生了异常
throw new RuntimeException("模拟程序异常");
}
return "success";
}
public String defaultErrorMethod(String isHtstrix) {
return "system exception";
}
}
测试
1、访问上面的接口:localhost:9004/sever4/hystrix/api0 响应:"success",给定一个请求参数:isHtstrix=1,响应:"system exception"。
2、去掉@HystrixCommand注解,访问该接口,同时指定一个请求参数:isHtstrix=1,则会抛出服务500异常。
更多Hystrix设置
@HystrixCommand注解在上面使用了fallbackMethod属性指定服务回退的目标方法。
常用的另一个属性:commandProperties,属性值用嵌套的注解@HystrixProperty指定,支持@HystrixProperty数组,配置示例如下:
@HystrixCommand(fallbackMethod = "defaultErrorMethod", commandProperties = {
// 指定隔离策略
@HystrixProperty(name = "execution.isolation.strategy", value = "THREAD"),
// 被@HystrixCommand注解的方法执行超时时间,一旦超过该时间进行降级处理
@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "2000")
})
更多配置项参考:https://github.com/Netflix/Hystrix/wiki/Configuration
Feign和Hystrix整合
在使用Feign的项目,application.properties配置文件中,开启Feign对Hystrix的支持:
feign.hystrix.enabled=true
在@FeignClient注解中,有两个属性:fallback和fallbackFactory,都能指定Hystrix的回退/降级方法。
先声明一个Feign客户端,如下:
@FeignClient(value = "cloud-server0", path = "/server0")
public interface FeignWithHystrixService {
@GetMapping("/api0")
String methodA();
}
1、fallback方式
改造上面的Feign客户端:
// fallback指定回退/降级的类
@FeignClient(value = "cloud-server0", path = "/server0", fallback = FeignWithHystrixServiceHystrix.class)
public interface FeignWithHystrixService {
@GetMappin