grails - 如何在另一个异步线程中使用 grails 模板渲染方法

标签 grails asynchronous

我的 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/

相关文章:

c# - 当异步方法在线程上使用时间时,这意味着什么?

c# - C# 游戏中 NPC 的异步行为

angular - 如何使用 observables 在 angular2 中异步绑定(bind)下拉列表?

c++ - 在 boost::asio 中,为什么异步接受处理程序需要重新启动异步接受?

grails - 将请求参数绑定(bind)到过滤器中的域对象

unit-testing - 使用 @TestFor 和 @Mixin 进行 Grails 2.0 单元测试

mysql - 查询 mysql 导致错误 : Illegal mix of collations (latin1_swedish_ci, IMPLICIT)

grails - Grails:使用 “jumps”在范围内创建选择

python - 在 Tornado 中,如何查看在 PeriodicCallback 调用的协程中引发的异常?

sql - Grails:使用普通SQL连接两个表