@RestController 中如何获取访问的IP地址
时间: 2023-07-26 12:15:09 浏览: 61
在Spring WebFlux中,可以通过在处理方法中注入`ServerWebExchange`对象来获取请求对象和响应对象。然后,通过请求对象获取请求相关的信息,例如请求的IP地址和请求头。例如:
```
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
@RestController
public class HelloController {
@GetMapping("/hello")
public Mono<String> hello(ServerWebExchange exchange) {
String ipAddress = exchange.getRequest().getRemoteAddress().getAddress().getHostAddress();
return Mono.just("Hello, " + ipAddress + "!");
}
}
```
在上面的例子中,我们使用`@GetMapping`注解标记了`hello()`方法,并注入了一个`ServerWebExchange`类型的参数,名为`exchange`,它代表了当前的请求和响应对象。在`hello()`方法中,我们通过`exchange.getRequest().getRemoteAddress().getAddress().getHostAddress()`方法获取了请求的IP地址,并返回了一个包含了IP地址的字符串。
需要注意的是,`getRemoteAddress()`方法返回的是`InetSocketAddress`类型的对象,需要通过`getAddress()`方法获取IP地址。在获取IP地址时,还需要注意安全性问题,防止恶意攻击。