简体   繁体   English

Play Framework:为Spring RabbitMQ监听器手动打开JPA上下文

[英]Play Framework: Manually open JPA context for Spring RabbitMQ listener

I am using Spring-AMQP to monitor a RabbitMQ message queue in a Play application. 我使用Spring-AMQP来监视Play应用程序中的RabbitMQ消息队列。

The problem is I can not access my database from the listener code since the JPA context is not open in this scope. 问题是我无法从侦听器代码访问我的数据库,因为JPA上下文未在此范围内打开。

I understand Play Framework manages the JPA context so that it is open when processing HTTP requests, but is there a way I can use JPA from outside Play controllers/jobs? 我理解Play Framework管理JPA上下文,以便在处理HTTP请求时打开它,但有没有办法可以从外部Play控制器/作业中使用JPA?

Just found the answer was to use JPAPlugin! 刚发现答案是使用JPAPlugin!

Example listener method: 示例侦听器方法:

public void process(Message message) {
    JPAPlugin.startTx(false);
    boolean rollBack = false;
    try {
        // work with your models
        JPA.em().flush();
    } catch (RuntimeException e) {
        rollBack = true;
        // throw exception to prevent msg ACK, need to refine error handling :)
        throw e;
    } finally {
        JPAPlugin.closeTx(rollBack);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM