0

I have controller with method that blocks the Play server thread due to very slow Database query. I need to implement controller method in a way that it don't block the thread. I have read documentation: http://www.playframework.org/documentation/1.2.4/asynchronous

There's absolutely no examples anywhere on how to do this. The only thing that I found close is this https://github.com/playframework/play/blob/master/samples-and-tests/chat/app/controllers/LongPolling.java It simply wraps result in await();

When I try to do that it doesn't work.

routes:

GET /blog Controller.blog

Controller (this is not an actual slow query but everything else is identical):

public static void blog() {
    String queryStr = "SELECT b FROM Blog b ORDER BY createTime DESC";
    JPAQuery q = Blog.find(queryStr);

    List<Blog> bList = q.fetch(100);
    List<BlogDTO> list = new ArrayList<BlogDTO>(bList.size());
    for (Blog b : bList) {
        BlogDTO obj = new BlogDTO(b);
        list.add(obj);
    }
    renderJSON(list);
}

I tried List<Blog> bList = await(q.fetch(100)); but that doesn't work.

I have not worked with Future and promises before. Can anyone give me any pointers on how to approach this?

4

2 回答 2

0

因为 JDBC 使用阻塞 IO,任何慢速数据库查询都会阻塞一个线程。唯一的方法似乎是为此目的使用 Job。

于 2012-07-09T10:35:28.197 回答
0

For me the best way to do this is to use a Job that returns a List object. Then in your controller you can await for the job termination :

public static void blog() {
    List<BlogDTO> list = await(new BlogPostJob().now());
    renderJSON(list);
}

and you put your jpa code in your job

于 2012-07-09T10:36:38.937 回答