我的 grails 应用程序在其 Controller 之一中异步发送电子邮件。异步,因为它应该在一个漫长的过程之后发送。我目前正在使用 executor
插件和 runAsync
关闭。
def sendEmails() {
...
runAsync {
// ... Some lengthy process before emailing
myMailService.send('someone@somecompany.net',
g.render(template: 'mail', model: resultOfLengthyProcess))
}
...
}
我在漫长的过程之后运行它,因为
render
中的模型函数调用包含该过程的结果。我想使用
g.render()
方法,因为电子邮件是一个包含大量图片和内容的大型 gsp 模板。现在
g.render
call 将失败,因为它是从另一个线程调用的。它抛出 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.
我该如何解决这个问题?我愿意接受任何答案/建议。
最佳答案
您需要一个请求才能直接使用渲染,并使用异步 block 将其松开。
但是,您应该能够通过在 Controller 中注入(inject) PageRender 并从异步 block 中调用它来实现您想要的。
class MyController {
grails.gsp.PageRenderer groovyPageRenderer
def sendEmails() {
// ... Some lengthy process before emailing
myMailService.send(
'someone@somecompany.net',
groovyPageRenderer.render(template: 'mail', model: resultOfLengthyProcess)
)
}
}
我建议使用 JMS(带有 jms 插件),将冗长的过程封装在服务中。
关于grails - 如何在另一个异步线程中使用 grails 模板渲染方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33410903/