0
votes

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!.

1
Not currently as it is built. Why can't you fallback to a uri? In this example github.com/spring-cloud-samples/spring-cloud-gateway-sample/… the fallback uri is only "forward:/hystrixfallback". This allows you to use a local webflux endpoint where you can access the request parameters, headers etc... With a custom command you couldn't access those things. - spencergibb
Thank you @spencergibb for your response. I couldn't figure out how to access the actual URI as I have an id that is a path param. My route looks like /api/{appid}/users/{userid} and I need to be able to access appId and userId in the forward URI. All the examples that I'm encountering are static URIs. - Peri
Put a ServerHttpRequest as a parameter. It's a normal spring webflux app. - spencergibb

1 Answers

0
votes

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