java拆分Zuul过滤器中的serivceId和真实请求路径

码农公社  210.net.cn   210= 1024  10月24日一个重要的节日--码农(程序员)节

背景

由于项目所需,需要在Zuul网关中解析请求URL,并将URL中路由服务部分与真实请求路径部分区分开。

localhost:8080/serviceA/api/xxx --> /api/xxx

这个功能比较简单,可以用String API轻松实现,但也可以用Spring-Web内置工具来解决。

实现

Talk is cheap,show me the code.

关键的组件是 RouteLocator 和 UrlPathHelper ,前者通过注入,后者可以实例化为常量

@Component@Slf4jpublic class ResourceFilter extends ZuulFilter {    @Autowired    private RouteLocator routeLocator;    private final UrlPathHelper pathHelper = new UrlPathHelper();    @Override    public String filterType() {        return "pre";    }    @Override    public int filterOrder() {        return 0;    }    @Override    public boolean shouldFilter() {        return true;    }    @Override    public Object run() throws ZuulException {        //获取当前请求        HttpServletRequest request = RequestContext.getCurrentContext().getRequest();                log.info("current url {}", request.getRequestURL().toString());                //解析Zuul路由对象        Route matchingRoute = routeLocator.getMatchingRoute(pathHelper.getPathWithinApplication(request));                //matchingRoute.getId() -> 当前路由服务名,即service-id        //matchingRoute.getPath() -> 摘除service-id后的请求路径        log.info("current serviceId : {} , request path : {}", matchingRoute.getId(), matchingRoute.getPath());        return null;    } } 输出: current url http://localhost:8080/serviceA/api/xxx current serviceId : serviceA , request path : /api/xxx

评论