我正在使用 Grails 服务闭包向另一个 Web 应用程序执行异步 HTTP 请求
。使用Grails 1.3.9
,我在这里受到很大限制。该代码在线程内运行。它是从预定作业和多个函数调用中调用的。我得到的错误如下:
错误:
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.
代码:
Thread.start {
def http = new HTTPBuilder(grailsApplication?.config?.smsConfig?.smsServiceAddress);
try {
http.request(POST) {
body = bodyRequest;
requestContentType = ContentType.JSON
response.success = { resp ->
println "SUCCESS! ${resp.status}"
def user = RequestContextHolder.currentRequestAttributes().getSession().user
if (user != null) {
if (termin) {
termin.withTransaction {
try {
// do desired action
} catch (e) {
println(e);
}
}
}
}
}
response.failure = { resp ->
println "FAILURE request failed with status ${resp.status}, response body was [${resp.entity.content.text}]"
System.out << resp
}
}
}
//here error is caught
catch (e) {
log.error "Error: " + e;
}
}
我尝试将此选项添加到 web.xml
<listener>
<listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
还有 WebXmlConfig.groovy
listener.add = true
listener.classNames = ["org.springframework.web.context.request.RequestContextListener"]
但是两者都没有帮助
最佳答案
这是没有详细记录的内容,或者您可以向您发送螺旋:
尝试this :
/*
* Fix for No thread-bound request found: Are you referring to request attributes
*/
def webRequest = RequestContextHolder.getRequestAttributes()
if(!webRequest) {
def servletContext = ServletContextHolder.getServletContext()
def applicationContext = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext)
webRequest = grails.util.GrailsWebMockUtil.bindMockWebRequest(applicationContext)
}
您需要在 build.gradle 中进行 spring 测试
compile 'org.springframework:spring-test:2.5'
有一个 grails 2 分支,因此如果是 grails 2,请在另一个分支中遵循相同的类
关于http - Grails 未找到线程绑定(bind)请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43250539/