如何在webflux中获取客户端IP?

5

我曾经使用HttpServletRequest.getRemoteAddr()获取客户端IP。

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

我的最佳猜测是:

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

这正确吗?

3个回答

3

EZ,这是您需要的链接:https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/http/server/reactive/ServerHttpRequest.html。@DavidBuck - Blednov Roman

2

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


0

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

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接