我使用了基于Spring的微服务环境设置这种配置-
春季启动版本: 1.5.6
终端用户呼叫产品微服务时,通过Nginx -> Api网关->产品服务。
现在,当我想在中获取远程客户端IP地址时,问题就出现了。我总是得到127.0.0.1作为ip地址。以下是获取客户端IP的产品微服务代码
private String getClientIP() {
String xfHeader = request.getRemoteAddr();
if (StringUtils.isBlank(xfHeader) || xfHeader.equals("127.0.0.1")) {
return request.getHeader("X-Forwarded-For");
}
return xfHeader.split(",")[0];
}
API网关application.properties配置为使用server.use-forward-headers: true
。
当我尝试从tomcat切换到我的api-网关时,我就开始在产品微服务中获得真正的客户端ip地址。所以问题就在我在API网关中的Tomcat配置中的某个地方。
发布于 2017-08-21 11:42:13
您可以创建zuul过滤器并像这样更改位置
zuul:
ignoreSecurityHeaders: false
routes:
app:
path: /app/**
sensitiveHeaders:
url: http://localhost:8082/app/
server:
compression:
enabled: true
port: 80
和过滤器
package smartHomeWebsite;
import java.util.Optional;
import org.springframework.cloud.netflix.zuul.filters.Route;
import org.springframework.cloud.netflix.zuul.filters.RouteLocator;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import org.springframework.web.util.UrlPathHelper;
import com.netflix.util.Pair;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
@Component
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;
}
public boolean shouldFilter() {
return extractLocationHeader(RequestContext.getCurrentContext()).isPresent();
}
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();
}
}
https://stackoverflow.com/questions/45801710
复制相似问题