【问题标题】:Zuul route doesn't map propertly with ribbon listOfServers (without Eureka)Zuul 路由无法与功能区 listOfServers 正确映射(没有 Eureka)
【发布时间】:2018-10-25 05:08:34
【问题描述】:

我正在尝试为我的 zuul 路由配置功能区,所以当我转到 http://host1:port1/restful-service/app1 时,它应该将我路由到 http://host2:port2/rest-example/app1。 当我使用“url”属性定义路由而不使用功能区时,它可以正常工作:

zuul:
  routes:
      restful-service:
          path: /restful-service/**
          url: http://host2:port2/rest-example

但是当我尝试使用功能区时,它看起来像这样:

zuul:
  routes:
    restful-service:
      path: /restful-service/**
      serviceId: restful-service

ribbon:
  eureka:
    enabled: false

restful-service:
  ribbon:
    listOfServers: host2:port2/rest-example

它只允许我路由到http://host2:port2/rest-example,但不能直接路由到所选服务http://host2:port2/rest-example/app1(它返回404状态码)。

【问题讨论】:

  • 你可以写一个前置过滤器来改变请求的uri。很快就会发布示例。

标签: java spring-cloud spring-cloud-netflix netflix-ribbon


【解决方案1】:

将您的配置属性更改为以下 -

    zuul:
        routes:
              restful-service:
                       serviceId:restful-service
                       stripPrefix:false

   ribbon:
        eureka:
             enabled:false

   restful-service:
        ribbon:
            listOfServers: host2:port2

然后你需要写一个zuul Pre-Filter来改变requestURI

      public class CustomPreFilter extends ZuulFilter {

      public Object run() {

       RequestContext context=RequestContext.getCurrentContext();
       String oldrequestURI=(String) context.get("requestURI");
       String newrequestURI=oldrequestURI.replace("restful-service", "rest-example");
       context.put("requestURI",newrequestURI);
       return null;
     }

      public boolean shouldFilter() {

       HttpServletRequest httpServletRequest=RequestContext.getCurrentContext().getRequest();
    if(httpServletRequest.getRequestURI().contains("/restful-service"))
        return true;
    else
        return false;
   }

       @Override
       public int filterOrder() {
       return PreDecorationFilter.FILTER_ORDER+1;
   }

      @Override
      public String filterType() {
      return "pre";
   }

 }

现在提出请求,这将适用于您想要做的事情。

【讨论】:

  • 感谢您的解决方案。不幸的是,它似乎只适用于一项服务,因为过滤器中有硬编码的名称。我的示例包含一个服务,但最终配置将包含其中的几个。
  • 您能否根据您的所有要求编辑您的问题。我可以编辑我的答案并尝试使其通用。
  • 或者你可以为不同的路由编写多个过滤器。只需更改应该过滤的条件。
【解决方案2】:

listOfServers 属性只支持主机和端口,不支持路径。

【讨论】:

    猜你喜欢
    • 2016-03-21
    • 1970-01-01
    • 2016-08-31
    • 2017-11-13
    • 1970-01-01
    • 2016-12-23
    • 2016-07-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多