保持对生活的爱和热枕,把每一天都活的热气腾腾。
Hystrix
Hystrix:英 [hɪst’rɪks] 美 [hɪst’rɪks] ,翻译过来是“豪猪”的意思。 在分布式环境中,不可避免地会出现某些依赖的服务发生故障的情况。Hystrix是这样的一个库,它通过添加容许时延和容错逻辑来帮助你控制这些分布式服务之间的交互。Hystrix通过隔离服务之间的访问点,阻止跨服务的级联故障,并提供了退路选项,所有这些都可以提高系统的整体弹性
Hystrix特性
一,请求熔断
二,服务降级
三,依赖隔离(采用舱壁模式,Docker就是舱壁模式的一种)
四,请求缓存
五,请求合并
关于请求熔断和服务降级的区别,推荐一篇博客
请求熔断
在微服务的调用链中,如果不做任何保护,防范措施的话,如果当中某一个服务出现问题,就很容易导致整个系统的瘫痪不可用。为了提高系统的可靠性,我们想:当某一个服务出现故障的时候,调用可以走我们自己定义的“失败的方法”,从而不影响整个系统的正常的运行,而不是直接瘫痪。这就是服务的熔断,就象上个年代的电路保险丝一样,电流过大时为了保护整个电路,从而烧掉保险丝。
熔断的实现(被调用方)
一、添加的依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
配置文件
# 开启熔断
feign:
hystrix:
enabled: true
启动类
//启动熔断
@EnableCircuitBreaker
服务方法
@RestController
public class ServeController {
@Resource
RestTemplate restTemplate;
@RequestMapping(name = "/getAll",method = RequestMethod.GET)
//如果出现错误就需要调用的方法
@HystrixCommand(fallbackMethod = "fallback")
public List<User> getAll(){
//出现错误
int i = 1/0;
return restTemplate.getForObject("http://DaoService",List.class);
}
//失败后调用的方法
public List<User> fallback(){
return null;
}
}
服务降级(调用方)
服务降级是从整个系统的负荷情况出发和考虑的,对某些负荷会比较高的情况,为了预防某些功能(业务场景)出现负荷过载或者响应慢的情况,在其内部暂时舍弃对一些非核心的接口和数据的请求,而直接返回一个提前准备好的fallback(退路)错误处理信息。这样,虽然提供的是一个有损的服务,但却保证了整个系统的稳定性和可用性。
依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
配置文件
feign:
hystrix:
enabled: true
#hystric默认请求超过1秒未响应就降级,配置为3秒未响应再降级
hystrix:
command:
default:
execution:
isolation:
thread:
timeoutInMilliseconds: 3000
启动类(加注解)
@EnableHystrix
feign接口
在创建的feign接口上的注解中添加属性,表示在调用失败之后走的类
@FeignClient(value = "ServerService",fallback = ServiceFeignImpl.class)
feign的实现类
@Component
public class ServiceFeignImpl implements ServeFeign {
@Override
public List<User> getAll() {
System.out.println("调用失败,进行降级处理");
return null;
}
}