目前用到的
1.方法中添加参数
public String getIp(ServerWebExchange serverWebExchange){
ServerHttpRequest request = serverWebExchange.getRequest();
HttpHeaders headers = request.getHeaders();
String ip = headers.getFirst("x-forwarded-for");
if (ip != null && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) {
// 多次反向代理后会有多个ip值,第一个ip才是真实ip
if (ip.indexOf(",") != -1) {
ip = ip.split(",")[0];
}
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = headers.getFirst("Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = headers.getFirst("WL-Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = headers.getFirst("HTTP_CLIENT_IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = headers.getFirst("HTTP_X_FORWARDED_FOR");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = headers.getFirst("X-Real-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddress().getAddress().getHostAddress();
}
return ip.replaceAll(":", ".");
}
2.切面中需要用到ip做日志
public void doAfterThrowing(JoinPoint joinPoint, Throwable throwable){
Object[] objects = joinPoint.getArgs(); ServletRequestAttributes attributes = (ServletRequestAttributes) ServerWebExchange serverWebExchange = null; for (Object o : objects) { if(o instanceof ServerWebExchange){ serverWebExchange = (ServerWebExchange)o; } } ServerHttpRequest request = serverWebExchange.getRequest(); String ip = request.getRemoteAddress().getAddress().toString(); }