引入maven

<dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>

在配置文件,路由上添加HystrixGatewayFilterFactory过滤器,name为Hystrix。

spring:cloud:gateway:routes:- id: 用户服务uri: lb://user-serverpredicates:- Path=/user-server/**filters:- name: Hystrixargs:name: fallbackcmd

另外在配置文件上设置请求超时时间

hystrix:command:default:execution:isolation:thread:# 请求超时时间5000毫秒timeoutInMilliseconds: 5000

请求接口,并出发降级,返回如下:

{"timestamp": "2022-08-16T01:23:11.939+0000","path": "/user-server/open/a","status": 504,"error": "Gateway Timeout","message": "Response took longer than configured timeout"
}

使用自定义降级策略返回,配置文件修改,添加fallbackUri

spring:cloud:gateway:routes:- id: 用户服务uri: lb://user-serverpredicates:- Path=/user-server/**filters:- name: Hystrixargs:name: fallbackcmd# 使用自定义fallbackfallbackUri: forward:/fallback

然后添加Fallback类

@RestController
public class FallbackController {@RequestMapping("/fallback")public Object fallback() {// 这里可以自定义返回json内容return "errorjson";}
}

此时降级返回:

errorjson

org.springframework.cloud.gateway.filter.factory.HystrixGatewayFilterFactory 源码

public class HystrixGatewayFilterFactory extends AbstractGatewayFilterFactory<HystrixGatewayFilterFactory.Config> {public static final String FALLBACK_URI = "fallbackUri";private final ObjectProvider<DispatcherHandler> dispatcherHandlerProvider;// do not use this dispatcherHandler directly, use getDispatcherHandler() instead.private volatile DispatcherHandler dispatcherHandler;public HystrixGatewayFilterFactory(ObjectProvider<DispatcherHandler> dispatcherHandlerProvider) {super(Config.class);this.dispatcherHandlerProvider = dispatcherHandlerProvider;}private DispatcherHandler getDispatcherHandler() {if (dispatcherHandler == null) {dispatcherHandler = dispatcherHandlerProvider.getIfAvailable();}return dispatcherHandler;}@Overridepublic List<String> shortcutFieldOrder() {return Arrays.asList(NAME_KEY);}public GatewayFilter apply(String routeId, Consumer<Config> consumer) {Config config = newConfig();consumer.accept(config);if (StringUtils.isEmpty(config.getName()) && !StringUtils.isEmpty(routeId)) {config.setName(routeId);}return apply(config);}@Overridepublic GatewayFilter apply(Config config) {//TODO: if no name is supplied, generate one from command id (useful for default filter)if (config.setter == null) {Assert.notNull(config.name, "A name must be supplied for the Hystrix Command Key");HystrixCommandGroupKey groupKey = HystrixCommandGroupKey.Factory.asKey(getClass().getSimpleName());HystrixCommandKey commandKey = HystrixCommandKey.Factory.asKey(config.name);config.setter = Setter.withGroupKey(groupKey).andCommandKey(commandKey);}return (exchange, chain) -> {RouteHystrixCommand command = new RouteHystrixCommand(config.setter, config.fallbackUri, exchange, chain);return Mono.create(s -> {Subscription sub = command.toObservable().subscribe(s::success, s::error, s::success);s.onCancel(sub::unsubscribe);}).onErrorResume((Function<Throwable, Mono<Void>>) throwable -> {if (throwable instanceof HystrixRuntimeException) {HystrixRuntimeException e = (HystrixRuntimeException) throwable;HystrixRuntimeException.FailureType failureType = e.getFailureType();switch (failureType) {case TIMEOUT:return Mono.error(new TimeoutException());case COMMAND_EXCEPTION: {Throwable cause = e.getCause();/** We forsake here the null check for cause as HystrixRuntimeException will* always have a cause if the failure type is COMMAND_EXCEPTION.*/if (cause instanceof ResponseStatusException || AnnotatedElementUtils.findMergedAnnotation(cause.getClass(), ResponseStatus.class) != null) {return Mono.error(cause);}}default: break;}}return Mono.error(throwable);}).then();};}//TODO: replace with HystrixMonoCommand that we writeprivate class RouteHystrixCommand extends HystrixObservableCommand<Void> {private final URI fallbackUri;private final ServerWebExchange exchange;private final GatewayFilterChain chain;RouteHystrixCommand(Setter setter, URI fallbackUri, ServerWebExchange exchange, GatewayFilterChain chain) {super(setter);this.fallbackUri = fallbackUri;this.exchange = exchange;this.chain = chain;}@Overrideprotected Observable<Void> construct() {return RxReactiveStreams.toObservable(this.chain.filter(exchange));}@Overrideprotected Observable<Void> resumeWithFallback() {if (this.fallbackUri == null) {return super.resumeWithFallback();}//TODO: copied from RouteToRequestUrlFilterURI uri = exchange.getRequest().getURI();//TODO: assume always?boolean encoded = containsEncodedParts(uri);URI requestUrl = UriComponentsBuilder.fromUri(uri).host(null).port(null).uri(this.fallbackUri).scheme(null).build(encoded).toUri();exchange.getAttributes().put(GATEWAY_REQUEST_URL_ATTR, requestUrl);ServerHttpRequest request = this.exchange.getRequest().mutate().uri(requestUrl).build();ServerWebExchange mutated = exchange.mutate().request(request).build();return RxReactiveStreams.toObservable(getDispatcherHandler().handle(mutated));}}public static class Config {private String name;private Setter setter;private URI fallbackUri;public String getName() {return name;}public Config setName(String name) {this.name = name;return this;}public Config setFallbackUri(String fallbackUri) {if (fallbackUri != null) {setFallbackUri(URI.create(fallbackUri));}return this;}public URI getFallbackUri() {return fallbackUri;}public void setFallbackUri(URI fallbackUri) {if (fallbackUri != null && !"forward".equals(fallbackUri.getScheme())) {throw new IllegalArgumentException("Hystrix Filter currently only supports 'forward' URIs, found " + fallbackUri);}this.fallbackUri = fallbackUri;}public Config setSetter(Setter setter) {this.setter = setter;return this;}}}

Spring Cloud Gateway 使用 HystrixGatewayFilterFactory 熔断降级相关推荐

  1. 深入学习spring cloud gateway 限流熔断

    目前,Spring Cloud Gateway是仅次于Spring Cloud Netflix的第二个最受欢迎的Spring Cloud项目(就GitHub上的星级而言).它是作为Spring Clo ...

  2. Spring Cloud Alibaba:Sentinel 熔断降级

    1. 前言 Sentinel版本:1.8.0 1.8.0 对熔断特性做了大量升级,低于此版本的谨慎参考 2. 熔断策略 2.1 慢调用比例 最大 RT(即最大的响应时间):请求的响应时间大于RT则统计 ...

  3. Spring Cloud Gateway(续)

    本文主要介绍 Spring Cloud Gateway 的路由熔断.路由重试和高可用. 路由熔断 在前面学习 Hystrix 的时候,我们知道 Hystrix 有服务降级的能力,即如果服务调用出现了异 ...

  4. 熬夜肝了这篇Spring Cloud Gateway的功能及综合使用

    前言 SpringCloud 是微服务中的翘楚,最佳的落地方案. Spring Cloud Gateway 是 Spring Cloud 新推出的网关框架,之前是 Netflix Zuul.网关通常在 ...

  5. Spring Cloud Gateway配置熔断CircuitBreaker

    我们使用的SpringCloud版本是Hoxton.SR9,小于G版本的是不支持CircuitBreaker的 CircuitBreaker原理 CircuitBreaker是由一个有限状态机实现的, ...

  6. 进一步学习spring cloud gateway的 限流熔断

    目前,Spring Cloud Gateway是仅次于Spring Cloud Netflix的第二个最受欢迎的Spring Cloud项目(就GitHub上的星级而言).它是作为Spring Clo ...

  7. 实战 Spring Cloud Gateway 之限流篇

    来源:https://www.aneasystone.com/archives/2020/08/spring-cloud-gateway-current-limiting.html 话说在 Sprin ...

  8. Spring Cloud Gateway 入门

    认识 Spring Cloud Gateway Spring Cloud Gateway 是一款基于 Spring 5,Project Reactor 以及 Spring Boot 2 构建的 API ...

  9. 网关Spring Cloud Gateway科普

    点击上方"朱小厮的博客",选择"设为星标" 后台回复"加群"获取公众号专属群聊入口 欢迎跳转到本文的原文链接:https://honeypp ...

  10. 网关服务Spring Cloud Gateway(三)

    上篇文章介绍了 Gataway 和注册中心的使用,以及 Gataway 中 Filter 的基本使用,这篇文章我们将继续介绍 Filter 的一些常用功能. 修改请求路径的过滤器 StripPrefi ...

最新文章

  1. 从零开始写个编译器吧 - 单词化简述(Tokenization)
  2. Android Java虚拟机拦截技术分析
  3. lombok 中的@Data注解
  4. android弹球动画,Android动画之自定义Evaluator实现弹球效果
  5. python imshow彩色_python中plt.imshow与cv2.imshow显示颜色问题
  6. golang如何生成随机数
  7. python counter_Python神奇的10个技巧
  8. 【信息系统项目管理师】第11章-项目风险管理 知识点详细整理
  9. 【掩码机制】解决LSTM中特征长度不一致问题
  10. python math库函数
  11. 单片机外部RAM如何用C 语言访问,C51中访问外部RAM的方法
  12. 冬暖夏凉究竟香不香?带恒温的TaoTronics暖风机开箱实测
  13. vue-pdf插件不翻页预览
  14. 小程序 获取今天日期 星期几 不墨迹就是快
  15. 天猫四大独门利器,助力品牌引领消费趋势
  16. 训练赛一:bfs广搜题目 CF115B Lawnmower
  17. 服务监控可以监控哪些
  18. Life with qmail -- 中文版(英文版本16 Aug 2003)
  19. 到底怎么能精准挑到“报恩榴莲”?
  20. mysql gmt格式_将MySQL数据库时区设置为GMT

热门文章

  1. 京牌车辆过户以后车辆保险怎么办?
  2. 关于北京工作居住证相关问题
  3. 阵道计算机,太古神王电脑版
  4. 仿微信.QQ聊天界面
  5. 回头看一看我的2018年
  6. win10 mstsc 设置
  7. 快速成为脚本小子_什么是脚本小子? 如何成为脚本小子?
  8. 《马哥出品高薪linux运维教程》wingkeung学习笔记-linux基础入门课程
  9. SAP中利用标准成本报表计算成品人工成本及组成实例
  10. SLAM技术课程总结