Peri
Peri

Reputation: 1

Hystrix Command in Spring Cloud Gateway

I'm using Spring cloud starter gateway 2.0.1.RELEASE along with Starter netflix hystrix. Is it possible to provide a HystrixCommand in route definition like below?.

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

My goal is to execute a fallback method without forwarding the request to a fallback uri. Also I cannot use static fallback uri option as I need path params and request params to determine the fallback response. Any help is highly appreciated!.

Upvotes: 0

Views: 2356

Answers (1)

I faced the same issue. This is how I solved it:

First, These are the routes:

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

The path predicate processes the url and extracts the path variables, those are saved into ServerWebExchange.getAttributes(), with a key defined as PathRoutePredicate.URL_PREDICATE_VARS_ATTR or ServerWebExchangeUtils.URI_TEMPLATE_VARIABLES_ATTRIBUTE

You can find more information about path predicate here

Second, I created a @RestController to handle the forward from Hystrix injecting the 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";
    }
}

Upvotes: 0

Related Questions