Spring Cloud Zuul 过滤器拆分serivceId和请求路径

背景

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

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

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

实现

Talk is cheap,show me the code.

关键的组件是 RouteLocatorUrlPathHelper ,前者通过注入,后者可以实例化为私有变量

@Component
@Slf4j
public 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
 

就酱。

原文地址:https://www.cnblogs.com/notayeser/p/12390280.html