Reputation: 13040
Just starting out on Play. The documentation talks about how Play can be run asynchronously.
But how to run MySQL queries when running Play asynchronously? Normal MySQL queries are blocking, right? So that wouldn't work.
Node.js has its own non-blocking MySQL clients just for this purpose, but I can't find anything similar for Play.
How do you run MySQL queries within an asynchronous Play application?
Upvotes: 6
Views: 5739
Reputation: 3908
In general execution of SQL Calls to DB is usually blocking and executed sequentially. Play has great support for Asynchronous execution which improves performance of your app.
Working code sample for Play 2.0
public static Result slow() {
Logger.debug("slow started");
// Start execution
Promise<DataObject> userObject1 = SlowQuery.getUser(440);
Promise<DataObject> userObject2 = SlowQuery.getCategory(420);
// ... here execution is already in progress ...
// Map to Promise Objects
Promise<DataObject> res1 = userObject1.map(new Function<DataObject, DataObject>() {
public DataObject apply(DataObject res) {
Logger.debug("Got result (userObject1): " + res.toString());
return res;
}
});
Promise<DataObject> res2 = userObject2.map(new Function<DataObject, DataObject>() {
public DataObject apply(DataObject res) {
Logger.debug("Got result (userObject2): " + res.toString());
return res;
}
});
// here we wait for completion - this blocks
userObject1.getWrappedPromise().await();
userObject2.getWrappedPromise().await();
// the result is available
Logger.debug(res1.get().toString());
Logger.debug(res2.get().toString());
Logger.debug("slow finished");
return ok("done");
}
feel free to improve using community wiki feature - I am sure some parts can be shortened.
Upvotes: 0
Reputation: 54884
Play Jobs are executed in a separate thread and release the main http thread. The main http thread is then started where it left off when the Job (wrapped in a Promise object) returns after completing.
So, the main http thread is not held up, and can be made available for handling other incoming http requests.
Upvotes: 2