美文网首页
SpringCloud网关修改请求头使微服务获取客户端真实ip

SpringCloud网关修改请求头使微服务获取客户端真实ip

作者: 爱的旋转体 | 来源:发表于2018-05-05 15:06 被阅读0次

1.网关添加过滤器:

import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Component;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;

@Component
public class XForwardedForFilter extends ZuulFilter {
    private static final String HTTP_X_FORWARDED_FOR = "HTTP_X_FORWARDED_FOR";

    @Override
    public Object run() {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        String remoteAddr = request.getRemoteAddr();
        ctx.getZuulRequestHeaders().put(HTTP_X_FORWARDED_FOR, remoteAddr);
        return null;
    }

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

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

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

2.微服务获取ip:

String ip = request.getHeader("HTTP_X_FORWARDED_FOR");

相关文章

网友评论

      本文标题:SpringCloud网关修改请求头使微服务获取客户端真实ip

      本文链接:https://www.haomeiwen.com/subject/thterftx.html