【问题标题】:How to get client IP in webflux?如何在 webflux 中获取客户端 IP?
【发布时间】:2018-06-22 05:21:58
【问题描述】:

我曾经调用 HttpServletRequest.getRemoteAddr() 来获取客户端 ip。

我想知道如何通过 ServerWebExchange 获取它。

我的最佳猜测是:

  serverWebExchange.getRequest().getRemoteAddress().getAddress().getHostAddress();

对吗?

【问题讨论】:

    标签: spring-webflux


    【解决方案1】:

    你可以使用org.springframework.http.server.reactive.ServerHttpRequest

    String remoteAddress = serverHttpRequest.getRemoteAddress().getAddress().getHostAddress();
    

    在文档中很伤心:.reactive.ServerHttpRequest 表示响应式服务器端 HTTP 请求。

    https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/http/server/reactive/ServerHttpRequest.html

    【讨论】:

    【解决方案2】:

    是的,这是实现这一目标的正确方法。 请注意,如果您希望支持 Forwarded 或 X-Forwarded-* HTTP 请求标头,则需要在服务器配置级别进行配置。

    【讨论】:

      【解决方案3】:

      您还可以将org.springframework.http.server.ServerHttpRequest 作为参数添加到@RerquestMapping 注释方法并从中获取IP 地址:

      @GetMapping("/myPath")
      public void someMethod(ServerHttpRequest request) {
          System.out.println(request.getRemoteAddress().getAddress().getHostAddress();)
      }
      

      【讨论】:

        猜你喜欢
        • 2012-03-31
        • 1970-01-01
        • 2020-09-27
        • 1970-01-01
        • 1970-01-01
        • 2016-10-07
        • 2015-06-06
        • 2020-11-10
        • 2012-03-14
        相关资源
        最近更新 更多