简体   繁体   中英

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.

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?

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);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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