zoukankan      html  css  js  c++  java
  • 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
     
    

    就酱。

  • 相关阅读:
    InterView
    单例设计模式(附AS3)
    网络游戏的分类
    flex的动态链接库和静态链接库
    flash 中位图九宫格的用法
    删除Flex Builder中没用的工作空间
    一个3D游戏DEMO, 同步教程更新
    LVS NET部署
    zabbix安装
    MySQL+keepalived高可用配置
  • 原文地址:https://www.cnblogs.com/notayeser/p/12390280.html
Copyright © 2011-2022 走看看