0

我正在使用 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 选项,因为我需要路径参数和请求参数来确定后备响应。任何帮助都非常感谢!

4

1 回答 1

0

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

首先,这些是路线:

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"));

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

您可以在此处找到有关路径谓词的更多信息

其次,我创建了一个@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";
    }
}
于 2018-09-06T20:13:55.033 回答