iis服务器助手广告广告
返回顶部
首页 > 资讯 > 后端开发 > Python >spring cloud gateway集成hystrix实战篇
  • 186
分享到

spring cloud gateway集成hystrix实战篇

2024-04-02 19:04:59 186人浏览 泡泡鱼

Python 官方文档:入门教程 => 点击学习

摘要

spring cloud gateway集成hystrix 本文主要研究一下spring cloud gateway如何集成hystrix Maven <dependenc

spring cloud gateway集成hystrix

本文主要研究一下spring cloud gateway如何集成hystrix

Maven


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

添加spring-cloud-starter-netflix-hystrix依赖,开启hystrix

配置实例


hystrix.command.fallbackcmd.execution.isolation.thread.timeoutInMilliseconds: 5000
spring:
  cloud:
    gateway:
      discovery:
        locator:
          enabled: true
      routes:
      - id: employee-service
        uri: lb://employee-service
        predicates:
        - Path=/employee
public class HystrixGatewayFilterFactory extends AbstractGatewayFilterFactory<HystrixGatewayFilterFactory.Config> {
    public static final String FALLBACK_URI = "fallbackUri";
    private final DispatcherHandler dispatcherHandler;
    public HystrixGatewayFilterFactory(DispatcherHandler dispatcherHandler) {
        super(Config.class);
        this.dispatcherHandler = dispatcherHandler;
    }
    @Override
    public 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);
    }
    @Override
    public 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;
                    if (e.getFailureType() == TIMEOUT) { //TODO: optionally set status
                        setResponseStatus(exchange, httpstatus.GATEWAY_TIMEOUT);
                        return exchange.getResponse().setComplete();
                    }
                }
                return Mono.error(throwable);
            }).then();
        };
    }
    //......
}

这里创建了RouteHystrixCommand,将其转换为Mono,然后在onErrorResume的时候判断如果HystrixRuntimeException的failureType是FailureType.TIMEOUT类型的话,则返回GATEWAY_TIMEOUT(504, "Gateway Timeout")状态码。

RouteHystrixCommand


//TODO: replace with HystrixMonoCommand that we write
    private 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;
        }
        @Override
        protected Observable<Void> construct() {
            return RxReactiveStreams.toObservable(this.chain.filter(exchange));
        }
        @Override
        protected Observable<Void> resumeWithFallback() {
            if (this.fallbackUri == null) {
                return super.resumeWithFallback();
            }
            //TODO: copied from RouteToRequestUrlFilter
            URI uri = exchange.getRequest().getURI();
            //TODO: assume always?
            boolean encoded = containsEncodedParts(uri);
            URI requestUrl = UriComponentsBuilder.fromUri(uri)
                    .host(null)
                    .port(null)
                    .uri(this.fallbackUri)
                    .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(HystrixGatewayFilterFactory.this.dispatcherHandler.handle(mutated));
        }
    }
  • 这里重写了construct方法,RxReactiveStreams.toObservable(this.chain.filter(exchange)),将reactor的Mono转换为rxjava的Observable
  • 这里重写了resumeWithFallback方法,针对有fallbackUri的情况,重新路由到fallbackUri的地址

Config


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;
        }
    }

可以看到Config校验了fallbackUri,如果不为null,则必须以forward开头

小结

spring cloud gateway集成hystrix,分为如下几步:

  • 添加spring-cloud-starter-netflix-hystrix依赖
  • 在对应route的filter添加name为Hystrix的filter,同时指定hystrix command的名称,及其fallbackUri(可选)
  • 指定该hystrix command的超时时间等。

以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程网。

--结束END--

本文标题: spring cloud gateway集成hystrix实战篇

本文链接: https://www.lsjlt.com/news/130662.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • spring cloud gateway集成hystrix实战篇
    spring cloud gateway集成hystrix 本文主要研究一下spring cloud gateway如何集成hystrix maven <dependenc...
    99+
    2024-04-02
  • spring cloud gateway集成hystrix的方法
    本篇内容介绍了“spring cloud gateway集成hystrix的方法”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!spring ...
    99+
    2023-06-20
  • spring cloud gateway集成hystrix全局断路器操作
    gateway集成hystrix全局断路器 pom.xml添加依赖 <dependency> <groupId>org.springframework.c...
    99+
    2024-04-02
  • spring cloud gateway集成hystrix全局断路器的操作
    这篇文章主要讲解了“spring cloud gateway集成hystrix全局断路器的操作”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“spring cloud gateway集成hys...
    99+
    2023-06-20
  • 初探Spring Cloud Gateway实战
    目录关于Spring Cloud Gateway版本信息经典配置中的核心概念启动nacos-2.0.3源码下载《Spring Cloud Gateway实战》系列的父工程创建名为co...
    99+
    2024-04-02
  • Spring Cloud Gateway集成Sentinel流控详情
    目录概述快速开始添加Sentinel配置文件编写配置文件测试概述 Sentinel 支持对 Spring Cloud Gateway、Zuul 等主流的 API Gateway 进行...
    99+
    2024-04-02
  • Spring Cloud Gateway Hystrix fallback获取异常信息的处理
    Gateway Hystrix fallback获取异常信息 gateway fallback后,需要知道请求的是哪个接口以及具体的异常信息,根据不同的请求以及异常进行不同的处理。一...
    99+
    2024-04-02
  • Spring Cloud Gateway Hystrix fallback怎么获取异常信息
    本篇内容介绍了“Spring Cloud Gateway Hystrix fallback怎么获取异常信息”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能...
    99+
    2023-06-20
  • Spring Cloud中Hystrix的请求缓存怎么实现
    本篇内容介绍了“Spring Cloud中Hystrix的请求缓存怎么实现”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!通过方法重载开启缓存...
    99+
    2023-06-19
  • Spring Boot集成Redis实战操作
    最近在使用Spring Boot,发现其功能真是强大,可以快速的集成很多的组件功能,非常方便:今天就来介绍下,如何集成Redis。定义Redis 是一个高性能的key-value数据库。它支持存储的value类型很多,包括string(字符...
    99+
    2023-06-02
  • Spring Cloud集成项目有哪些
    这篇文章主要讲解了“Spring Cloud集成项目有哪些”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“Spring Cloud集成项目有哪些”吧!Spring Cloud Config配置...
    99+
    2023-06-05
  • Spring Cloud中如何使用Hystrix实现断路器
    这篇文章主要介绍了Spring Cloud中如何使用Hystrix实现断路器的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇Spring Cloud中如何使用Hystrix实现断路器文章都会有所收获,下面我们一起...
    99+
    2023-06-04
  • spring cloud集成ribbon负载均衡怎么实现
    这篇文章主要介绍“spring cloud集成ribbon负载均衡怎么实现”,在日常操作中,相信很多人在spring cloud集成ribbon负载均衡怎么实现问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法...
    99+
    2023-06-21
  • 基于OpenID Connect及Token Relay实现Spring Cloud Gateway
    目录前言实现Keycloak网关依赖项代码配置测试资源服务器依赖项代码配置测试结论前言 当与Spring Security 5.2+ 和 OpenID Provi...
    99+
    2024-04-02
  • Spring Cloud Gateway动态路由Apollo实现详解
    目录背景路由的加载实现动态路由背景 在之前我们了解的Spring Cloud Gateway配置路由方式有两种方式 通过配置文件 spring: cloud: gatew...
    99+
    2022-11-13
    Spring Cloud Gateway Apollo Spring Cloud Gateway 动态路由
  • spring cloud如何集成nacos配置中心
    目录spring cloud集成nacos配置中心一、添加依赖二、添加bootstrap.yml配置文件三、添加远程配置nacos作为SpringCloud配置中心一、背景介绍二、项...
    99+
    2024-04-02
  • spring cloud微服务分布式云架构 - Spring Cloud集成项目简介
    Spring Cloud集成项目有很多,下面我们列举一下和Spring Cloud相关的优秀项目,我们的企业架构中用到了很多的优秀项目,说白了,也是站在巨人的肩膀上去整合的。在学习Spring Cloud之前大家必须了解一下相关项目,希望可...
    99+
    2023-06-05
  • 基于OpenID Connect及Token Relay怎么实现Spring Cloud Gateway
    这篇文章主要介绍“基于OpenID Connect及Token Relay怎么实现Spring Cloud Gateway”的相关知识,小编通过实际案例向大家展示操作过程,操作方法简单快捷,实用性强,...
    99+
    2023-07-02
  • Nacos+Spring Cloud Gateway动态路由配置实现步骤
    目录前言一、Nacos环境准备1、启动Nacos配置中心并创建路由配置2、连接Nacos配置中心二、项目构建1、项目结构2、编写测试代码三、测试动态网关配置1、启动服务,观察注册中心...
    99+
    2024-04-02
  • Nacos+Spring Cloud Gateway动态路由如何配置实现
    小编给大家分享一下Nacos+Spring Cloud Gateway动态路由如何配置实现,希望大家阅读完这篇文章之后都有所收获,下面让我们一起去探讨吧!前言  Nacos最近项目一直在使用,其简单灵活,支持更细粒度的命令空间,分组等为麻烦...
    99+
    2023-06-20
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作