【发布时间】:2018-06-22 05:21:58
【问题描述】:
我曾经调用 HttpServletRequest.getRemoteAddr() 来获取客户端 ip。
我想知道如何通过 ServerWebExchange 获取它。
我的最佳猜测是:
serverWebExchange.getRequest().getRemoteAddress().getAddress().getHostAddress();
对吗?
【问题讨论】:
标签: spring-webflux
我曾经调用 HttpServletRequest.getRemoteAddr() 来获取客户端 ip。
我想知道如何通过 ServerWebExchange 获取它。
我的最佳猜测是:
serverWebExchange.getRequest().getRemoteAddress().getAddress().getHostAddress();
对吗?
【问题讨论】:
标签: spring-webflux
你可以使用org.springframework.http.server.reactive.ServerHttpRequest,
String remoteAddress = serverHttpRequest.getRemoteAddress().getAddress().getHostAddress();
在文档中很伤心:.reactive.ServerHttpRequest
表示响应式服务器端 HTTP 请求。
【讨论】:
是的,这是实现这一目标的正确方法。 请注意,如果您希望支持 Forwarded 或 X-Forwarded-* HTTP 请求标头,则需要在服务器配置级别进行配置。
【讨论】:
您还可以将org.springframework.http.server.ServerHttpRequest 作为参数添加到@RerquestMapping 注释方法并从中获取IP 地址:
@GetMapping("/myPath")
public void someMethod(ServerHttpRequest request) {
System.out.println(request.getRemoteAddress().getAddress().getHostAddress();)
}
【讨论】: