Play 2.2 action not processed in parallel with web

2019-08-05 00:54发布

public class Application extends Controller {

    @BodyParser.Of(BodyParser.Json.class)
    public static Result action1() {
        WS.url(WS_URL).get().map(new Function<WS.Response, Result>() {
            public Result apply(WS.Response response) {
                try {
                    Thread.sleep(10000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                return null;
            }
        });
        return ok();
    }

    @BodyParser.Of(BodyParser.Json.class)
    public static Result action2() {
        return ok();
    }
}

The client first calls action1(), then, it calls action2(). However, it seems that Play process the second request after those 10 seconds. I thought that responses from web services are processed by Play in separate threads, but it seems that's not true. In this case, what should I do if I want to sleep or to execute some code after a timeout, without interrupting the server from serving other requests?

EDIT: this happens when the response from the WS arrives before the client calls action2().

2条回答
虎瘦雄心在
2楼-- · 2019-08-05 01:36

Play by default allocates the same number of threads as the number of CPU cores you have (although note that there are multiple thread pools), so configure it to allocate more threads if you want to do blocking operations such as sleep in a handler.

查看更多
神经病院院长
3楼-- · 2019-08-05 01:39

Not really sure what you're trying to achieve, but the code below will insert a 10 second delay between when the WS call returns, and when it returns an ok result:

public static F.Promise<SimpleResult> action1() {
    return WS.url(WS_URL).get().flatMap(new Function<WS.Response, F.Promise<WS.Response>>() {
        public F.Promise<WS.Response> apply(WS.Response response) {
           return F.Promise.timeout(response, 100000);
        }
    }).map(new Function<WS.Response, SimpleResult>() {
        public SimpleResult apply(WS.Response response) {
           return ok();
        }
    };
}

To understand Play's thread pools, read this:

http://www.playframework.com/documentation/2.2.x/ThreadPools

To understand how Play works with promises, read this:

http://www.playframework.com/documentation/2.2.x/JavaAsync

查看更多
登录 后发表回答