问题
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