一、前言
Hystrix是一个用于处理分布式系统的延迟和容错的开源库,在分布式系统里,许多依赖不可避免的会调用失败,比如超时,异常等,Hystrix能够保证在一个依赖出现问题的情况下,不会导致整体服务失败,避免级联故障,以提高分布式系统的弹性。
“断路器”本身是一种开关设置,当某个服务单元发生故障之后,通过断路器的故障监控(类似熔断保险丝),向调用方法返回一个服务预期的,可处理的备选响应(FallBack),而不是长时间的等待或者抛出调用方法无法处理的异常,这样就可以保证了服务调用方的线程不会被长时间,不必要的占用,从而避免了故障在分布式系统中的蔓延,乃至雪崩。
那么Hystrix能够做一些什么呢?
- 服务降级,服务熔断,服务限流,实时监控
以及一些分流,依赖分离之类等等。这里我们将用简单的介绍服务熔断和降级,并用代码简单演示一下。
当某个微服务不可用或者响应实践太长时,会进行服务的降级,进而熔断该节点微服务的调用,快速返回错误的响应信息。当检测到该节点微服务调用响应正常后恢复调用链路。在SpringCloud框架里熔断机制通过Hystrix实现。Hystrix会监控微服务间调用的状况,当失败的调用到一定的阈值,缺省是5秒内20次调用失败就会启动熔断机制。
二、服务降级(HystrixCommand
)
用@HystrixCommand fallbackMethod的方式不是很好,因为和业务代码耦合度太高,所有方法都在一个类,不利于后期维护 ,建议使用 fegin+Hystrix 整合 方式
1、导入依赖
实现方式如下,实际请结合业务逻辑进行使用,首先导入依赖
<!--hystrix依赖,主要是用 @HystrixCommand -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
2、加入注解
然后我们需要在启动类加入 @EnableCircuitBreaker 注解
@SpringBootApplication
@EnableCircuitBreaker
public class OrderServiceApplication {
public static void main(String[] args) {
SpringApplication.run(OrderServiceApplication.class, args);
}
}
3、服务提供接口实现,添加降级处理方法
服务降级方法,方法签名(参数+返回值)
需要同原方法一致,方法名不同即可,接下来我们在 在外层 api controller中可使用 @HystrixCommand(fallbackMethod = "saveOrderFail") 进行降级方法的配置
@RequestMapping("save")
@HystrixCommand(fallbackMethod = "saveOrderFail")
public Object save(@RequestParam("user_id") int userId, @RequestParam("product_id") int productId) {
Map<String, Object> data = new HashMap<>();
data.put("code", 0);
data.put("data", productOrderService.save(userId, productId));
return data;
}
//注意,方法签名一定要要和api方法一致
private Object saveOrderFail(int userId, int productId) {
return "服务熔断";
}
三、服务降级(fegin
+Hystrix
)
1、application.yml 配置,消费端添加配置 feign.hystrix.enabled=true
feign:
hystrix:
enabled: true
2、启动类,添加 @EnableCircuitBreaker 注解
@SpringBootApplication
@EnableFeignClients
@EnableCircuitBreaker
public class OrderServiceApplication {
public static void main(String[] args) {
SpringApplication.run(OrderServiceApplication.class, args);
}
}
3、新建 fallback 降级处理方法类 并实现 feignClient 接口 的方法
/**
* 针对商品服务,错降级处理
*/
@Component
public class ProductClientFallback implements ProductClient {
@Override
public String findById(int id) {
System.out.println("feign 调用product-service findbyid 异常");
return null;
}
}
四、超时时间调整
hystrix:
command:
default:
execution:
isolation:
thread:
timeoutInMilliseconds: 4000
参考文献
https://blog.csdn.net/lzb348110175/article/details/107295017