ZuulPostFilter - 重写位置标题

时间:2016-09-28 13:45:26

标签: reverse-proxy microservices netflix-zuul

我将Zuul配置为本地后端服务器的反向代理。某些响应具有3XX HTTP代码(重定向)。我编写了下一个过滤器来处理位置标题的重写。

public class LocationHeaderRewritingFilter extends ZuulFilter {

    private final UrlPathHelper urlPathHelper = new UrlPathHelper();
    private final RouteLocator routeLocator;

    public LocationHeaderRewritingFilter(RouteLocator routeLocator) {
        this.routeLocator = routeLocator;
    }

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

    @Override
    public int filterOrder() {
        return 100;
    }

    @Override
    public boolean shouldFilter() {
        return extractLocationHeader(RequestContext.getCurrentContext()).isPresent();
    }

    @Override
    public Object run() {
        RequestContext ctx = RequestContext.getCurrentContext();
        Route route = routeLocator.getMatchingRoute(urlPathHelper.getPathWithinApplication(ctx.getRequest()));
        if (route != null) {
            Pair<String, String> lh = extractLocationHeader(ctx).get();
            lh.setSecond(lh.second().replace(route.getLocation(),
                    ServletUriComponentsBuilder.fromCurrentContextPath().path(route.getPrefix()).build().toUriString()));
        }
        return null;
    }


    private Optional<Pair<String, String>> extractLocationHeader(RequestContext ctx) {

        return ctx.getZuulResponseHeaders()
                .stream()
                .filter(p -> "Location".equals(p.first()))
                .findFirst();
    }
}

我的Zuul配置是:

zuul:
  ignoredServices: '*'
  routes:
    MyBackendService:
      paths: /hello/**
      url: http://localhost:8080/app1
      strip-prefix: false
      sensitiveHeaders:

过滤器工作正常,但当我将'url'更改为'service-id'时,过滤器无法重写标头。

 zuul:
  ignoredServices: '*'
  routes:
    MyBackendService:
      paths: /hello/**
      service-id: APP1
      strip-prefix: false
      sensitiveHeaders:

由于route.getLocation()方法返回的错误值导致过滤器挂起,新值为:APP1。

我正在寻找一种方法来修复我的过滤器,如何提取属于我的服务ID的特定地址?

0 个答案:

没有答案