Grails没有发现线程绑定请求

时间:2017-04-06 09:03:58

标签: http grails

我正在使用Grails服务关闭来对另一个Web应用程序执行async HTTP request。使用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.

CODE:

    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"]

但两人都没有帮助

1 个答案:

答案 0 :(得分:1)

这是没有详细记录的内容,或者你可以向你发送螺旋:

尝试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中进行弹簧测试

  compile 'org.springframework:spring-test:2.5'

有一个grails 2分支,所以如果是grails 2,则在另一个分支中跟随同一个类