定时任务(就一个定时任务)调一个service,service中注入了HttpServletRequest request作为参数,定时任务进入方法时,参数request为Current HttpServletRequest,request.getHeader("X-Real-IP")时就报错了,两个类似的项目,配置基本相同,另一个却没事。希望各路大神能给指点一下迷津。
异常信息:
java.lang.IllegalStateException: No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread? If you are actually operating within a web request and still receive this message, your code is probably running outside of DispatcherServlet/DispatcherPortlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request.
at org.springframework.web.context.request.RequestContextHolder.currentRequestAttributes(RequestContextHolder.java:131)
at org.springframework.web.context.support.WebApplicationContextUtils.currentRequestAttributes(WebApplicationContextUtils.java:271)
at org.springframework.web.context.support.WebApplicationContextUtils.access$0(WebApplicationContextUtils.java:270)
at org.springframework.web.context.support.WebApplicationContextUtils$RequestObjectFactory.getObject(WebApplicationContextUtils.java:286)
at org.springframework.web.context.support.WebApplicationContextUtils$RequestObjectFactory.getObject(WebApplicationContextUtils.java:1)
at org.springframework.beans.factory.support.AutowireUtils$ObjectFactoryDelegatingInvocationHandler.invoke(AutowireUtils.java:178)
.................
方法就是普通的方法:
public static String getRemoteHost(HttpServletRequest request){
if(null != request){
try {
String ip = request.getHeader("X-Real-IP");
if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
ip = request.getHeader("x-forwarded-for");
}
if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
ip = request.getHeader("Proxy-Client-IP");
}
if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
ip = request.getHeader("WL-Proxy-Client-IP");
}
if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
ip = request.getRemoteAddr();
}
return ip.equals("0:0:0:0:0:0:0:1")?"127.0.0.1":ip;
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
return "127.0.0.1";
}
}else{
return "127.0.0.1";
}
}
<p>原因是,外部没有单独的线程绑定到 这个请求。</p>
In this case, use RequestContextListener or RequestContextFilter to expose the current request
你想要获取这个参数 ,需要使用上面的 的方式 。
你可以,在收到请求时,就把内容获取出来,那个时候,tcp的连接应该还在,在你运行定时,任务时,这个请求的对应的线程已经 ,停了。
<p>定时任务哪来的客户请求IP 就根本不应该yourequest对象</p>
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。