Play Framework: Manually open JPA context for Spring RabbitMQ listener

孤街醉人 提交于 2020-03-18 10:03:42

问题


I am using Spring-AMQP to monitor a RabbitMQ message queue in a Play application.

The problem is I can not access my database from the listener code since the JPA context is not open in this scope.

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?


回答1:


Just found the answer was to use 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);
    }
}


来源:https://stackoverflow.com/questions/10808378/play-framework-manually-open-jpa-context-for-spring-rabbitmq-listener

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!