【问题标题】:Hystrix Command in Spring Cloud GatewaySpring Cloud Gateway 中的 Hystrix 命令
【发布时间】:2019-01-21 21:35:58
【问题描述】:

我正在使用 Spring cloud starter gateway 2.0.1.RELEASE 和 Starter netflix hystrix。是否可以像下面这样在路由定义中提供 HystrixCommand?

builder.routes()
        .route( r -> r.path("path")
                    .and().method(HttpMethod.GET)
                    .filters(f -> f.hystrix("myHystrixCommandName"))
        .uri("/destination")
                    .id("route_1"));

我的目标是在不将请求转发到后备 uri 的情况下执行后备方法。 此外,我不能使用静态后备 uri 选项,因为我需要路径参数和请求参数来确定后备响应。非常感谢任何帮助!。

【问题讨论】:

  • 目前还没有构建。为什么不能回退到 uri?在此示例中github.com/spring-cloud-samples/spring-cloud-gateway-sample/… 后备 uri 仅是“forward:/hystrixfallback”。这允许您使用本地 webflux 端点,您可以在其中访问请求参数、标头等...使用自定义命令您无法访问这些内容。
  • 感谢@spencergibb 的回复。我无法弄清楚如何访问实际的 URI,因为我有一个作为路径参数的 id。我的路线看起来像 /api/{appid}/users/{userid} 并且我需要能够在转发 URI 中访问 appId 和 userId。我遇到的所有示例都是静态 URI。
  • ServerHttpRequest作为参数。这是一个普通的 spring webflux 应用程序。

标签: spring-cloud hystrix spring-cloud-gateway


【解决方案1】:

我遇到了同样的问题。我就是这样解决的:

首先,这些是路线:

builder.routes()
    .route( r -> r.path("/api/{appid}/users/{userid}")
                .and().method(HttpMethod.GET)
                .filters(f -> f.hystrix("myHystrixCommandName")
                               .setFallbackUri("forward:/hystrixfallback"))
    .uri("/destination")
                .id("route_1"));

path 谓词处理 url 并提取路径变量,这些变量保存到 ServerWebExchange.getAttributes() 中,键定义为 PathRoutePredicate.URL_PREDICATE_VARS_ATTRServerWebExchangeUtils.URI_TEMPLATE_VARIABLES_ATTRIBUTE

你可以找到更多关于路径谓词here的信息

第二,我创建了一个@RestController来处理来自Hystrix的转发注入ServerWebExchange

@RestController
@RequestMapping("/hystrixfallback")
public class ServiceFallBack {
    @RequestMapping(method = {RequestMethod.GET})
    public String get(ServerWebExchange serverWebExchange) {
        //Get the PathMatchInfo
        PathPattern.PathMatchInfo pathMatchInfo = serverWebExchange.getAttribute(ServerWebExchangeUtils.URI_TEMPLATE_VARIABLES_ATTRIBUTE);

        //Get the template variables
        Map<String, String> urlTemplateVariables = pathMatchInfo.getUriVariables();

        //TODO Logic using path variables

        return "result";
    }
}

【讨论】:

    猜你喜欢
    • 2019-01-09
    • 2018-10-11
    • 2016-06-18
    • 2016-07-04
    • 2021-06-27
    • 2015-12-05
    • 2016-03-31
    • 2015-05-31
    • 2018-07-21
    相关资源
    最近更新 更多