Match route in spring zuul based on strict matching

For picking the route based on best match, i found this thread helpful (thanks to @maximdim). Basically you can write your own custom router to pick best matching route.

https://github.com/spring-cloud/spring-cloud-netflix/issues/2408

Hope this helps. (And as it's my first answer, my apologies if it is not a good one.)

An example taken from github thread goes as follows:

public class CustomRouteLocator extends SimpleRouteLocator {
    public CustomRouteLocator(String servletPath, ZuulProperties properties) {
        super(servletPath, properties);
    }

    @Override
    protected ZuulRoute getZuulRoute(String adjustedPath) {
        // Spring's AbstractUrlHandlerMapping already found best matching path for us
        // and stored it into request attribute. See AbstractUrlHandlerMapping.exposePathWithinMapping
        RequestContext ctx = RequestContext.getCurrentContext();
        String bestMatchingPattern = (String)ctx.getRequest().getAttribute(HandlerMapping.class.getName() + ".bestMatchingPattern");
        if (bestMatchingPattern == null) {
            return super.getZuulRoute(adjustedPath);
        }

        if (!matchesIgnoredPatterns(adjustedPath)) {
            return locateRoutes().get(bestMatchingPattern);
        }
        return null;
    }
}

@maximdim:

Instead of duplicating logic to find 'best match' I simply getting it from request attribute, where Spring's HandlerMapping saves it. A bit hacky perhaps, but seems to work for me.


Editing answer based on Zuul's official documentation: https://cloud.spring.io/spring-cloud-netflix/multi/multi__router_and_filter_zuul.html

If you need your routes to have their order preserved, you need to use a YAML file, as the ordering is lost when using a properties file. The following example shows such a YAML file:

application.yml.

 zuul:
  routes:
    users:
      path: /myusers/**
    legacy:
      path: /**

If you were to use a properties file, the legacy path might end up in front of the users path, rendering the users path unreachable.

Make sure you're using the latest stable version of Spring Cloud (currently 2.0.2)