2017-08-21 38 views
0

我有春天啓動的基於微服務環境設置與此配置 -Tomcat的Zuul代理服務器不轉發正確的客戶端IP地址(request.getRemoteAddr())結束的microService

  1. 作爲nginx的負載平衡器(配置爲使用x-forwarded-for)
  2. 基於netflix zuul代理服務器的Spring Boot Powered API Gateway。 Tomcat是嵌入式容器。
  3. 基於Spring Cloud的產品微服務。 Tomcat作爲嵌入式容器。

春天引導版本:1.5.6

當最終用戶正在通話產品的microService,它經歷的Nginx - > API網關 - >產品服務。

現在問題出現時,我想獲得產品Microservice中的遠程客戶端IP地址。我總是得到127.0.0.1作爲IP地址。這是在產品的microService是獲取客戶端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

P.S.代碼 當我嘗試從tomcat切換到在我的api-gateway中時,然後我開始獲取產品microservice中的真實客戶端IP地址。所以問題出在我的Tomcat配置中的API網關。

回答

0

,你可以創建一個這樣

zuul: 
    ignoreSecurityHeaders: false 
    routes: 
    app: 
     path: /app/** 
     sensitiveHeaders: 
     url: http://localhost:8082/app/ 
server: 
    compression: 
     enabled: true 
    port: 80 

zuul過濾器和改變位置和過濾

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(); 
    } 
} 
相關問題