使用方式
pom依赖增加
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-hystrix</artifactId>
<version>1.4.5.RELEASE</version>
</dependency>
代码
在启动类中添加:
@EnableHystrix
@EnableCircuitBreaker
添加注解:@HystrixCommand
设置熔断方法:fallbackMethod
@PostMapping(value = "product/list")
@HystrixCommand(
fallbackMethod = "productListHystrixMethod",
commandKey = "productListHystrix",
threadPoolKey = "productListHystrix"
)
public ResponseEntity<?> productList(@RequestBody Map<String, String> paramMap, HttpServletRequest request) {
setLocalRequest(request);
log.info("product/list:{}", paramMap);
return omsClient.productList(paramMap);
}
public ResponseEntity<?> productListHystrixMethod(Map<String, String> paramMap,
HttpServletRequest request,
Throwable e){
return hystrixResponse(log, "商品列表", e);
}
配置文件
#(熔断)
#初始线程数
hystrix.threadpool.productListHystrix.coreSize = 10
#最大线程数
hystrix.threadpool.productListHystrix.maximumSize = 20
#最大队列数
hystrix.threadpool.productListHystrix.maxQueueSize = 10
#最大队列,还有xx个时触发熔断
hystrix.threadpool.productListHystrix.queueSizeRejectionThreshold = 5
#超时时间
hystrix.command.productListHystrix.execution.isolation.thread.timeoutInMilliseconds = 5000
#熔断持续时间
hystrix.command.productListHystrix.circuitBreaker.sleepWindowInMilliseconds = 5000
#错误比率
#hystrix.command.default.circuitBreaker.errorThresholdPercentage=50
问题
注解参数 fallbackMethod 熔断回调接口使用
fallbackMethod 传参、返回类型必须与@HystrixCommand注解的接口保持一致
注解参数 commandKey 熔断回调接口使用
commandKey 与apollo 配置一致
注解参数 threadPoolKey 熔断回调接口使用
threadPoolKey 与apollo 配置一致
请求header无法获取
描述:
- 上游服务,调用下游feign时,下游服务无法获取到header
- 添加@HystrixCommand 的接口链路上无法获取到request
解决办法:
在Controller方法参数中新增HttpServletRequest参数,并且强制设置当前线程request
protected void setLocalRequest(HttpServletRequest request) {
RequestContextHolder.setRequestAttributes(
new ServletRequestAttributes(request)
);
}
保证上游服务配置熔断,无法保证服务不受影响
SpringCloudHystrix熔断机制配置及使用示例
文章介绍了如何在SpringCloud应用中使用Hystrix进行熔断处理,包括在启动类上添加@EnableHystrix和@EnableCircuitBreaker注解,使用@HystrixCommand注解定义熔断方法,配置熔断参数如超时时间、线程池大小等,并展示了当服务调用失败时如何通过fallbackMethod提供降级策略。同时,文中提到了在处理Feign调用时如何传递HttpServletRequest来获取请求头信息。
821





