In Zuul gateway,How to modify the service path in custom filter?

余生长醉 提交于 2019-12-13 03:39:16

问题


I have implemented a zuul gateway service for the communication between some micro services that i have wrote. I have a specific scenario like i want to change the service path in one of my custom filter and redirected to some other service. Is this possible with the zuul gateway?. I have tried putting "requestURI" parameter with the updated uri to the request context in my route filter but that didn't worked out well

Please help me out guys thanks in advance


回答1:


yes, you can. for that you need to implement ZuulFilter with type PRE_TYPE, and update response with specified Location header and response status either 301 or 302.

@Slf4j
public class CustomRedirectFilter extends ZuulFilter {

    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return FilterConstants.SEND_FORWARD_FILTER_ORDER;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() {
        RequestContext ctx = RequestContext.getCurrentContext();
        String requestUrl = ctx.getRequest().getRequestURL().toString();

        if (shouldBeRedirected(requestUrl)) {
            String redirectUrl = generateRedirectUrl(ctx.getRequest());
            sendRedirect(ctx.getResponse(), redirectUrl);
        }
        return null;
    }

    private void sendRedirect(HttpServletResponse response, String redirectUrl){
        try {
            response.setHeader(HttpHeaders.LOCATION, redirectUrl);
            response.setStatus(HttpStatus.MOVED_PERMANENTLY.value());
            response.flushBuffer();
        } catch (IOException ex) {
            log.error("Could not redirect to: " + redirectUrl, ex);
        }
    }

    private boolean shouldBeRedirected(String requestUrl) {
        // your logic whether should we redirect request or not
        return true;
    }

    private String generateRedirectUrl(HttpServletRequest request) {
        String queryParams = request.getQueryString();
        String currentUrl =  request.getRequestURL().toString() + (queryParams == null ? "" : ("?" + queryParams));
        // update url
        return updatedUrl;
    }
}


来源:https://stackoverflow.com/questions/51551073/in-zuul-gateway-how-to-modify-the-service-path-in-custom-filter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!