在Spring Cloud中,可以通过HttpServletRequest
对象获取到Remote_Addr
, X-Forwarded-For
, X-Real-IP
等HTTP请求头信息。
解决方案1:直接在Controller中注入HttpServletRequest对象
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class TestController {
@RequestMapping("/test")
public String test(HttpServletRequest request) {
String remoteAddr = request.getRemoteAddr();
String xForwardedFor = request.getHeader("X-Forwarded-For");
String xRealIp = request.getHeader("X-Real-IP");
return "RemoteAddr: " + remoteAddr + ", X-Forwarded-For: " + xForwardedFor + ", X-Real-IP: " + xRealIp;
}
}
解决方案2:使用@Autowired注入RequestContextHolder
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class TestController {
@RequestMapping("/test")
public String test() {
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
String remoteAddr = request.getRemoteAddr();
String xForwardedFor = request.getHeader("X-Forwarded-For");
String xRealIp = request.getHeader("X-Real-IP");
return "RemoteAddr: " + remoteAddr + ", X-Forwarded-For: " + xForwardedFor + ", X-Real-IP: " + xRealIp;
}
}
解决方案3:使用过滤器获取
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
public class MyFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {