REST控制器是多线程的吗? [英] Is REST controller multithreaded?

查看:192
本文介绍了REST控制器是多线程的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在做这个教程关于如何返回异步可调用对象。它按预期工作。 但是,当第一个请求休眠5秒钟时,我得到了第二个请求,控制器等待用于上一个芬兰语请求,然后再处理第二个请求。

I've been doing this tutorial about how to return async callable object. It works as intended. But while the first request sleeps for 5 seconds I get the second request, controller waits for the previous request to finnish before handling the second one.

如何让控制器立即处理每个请求并在后台睡觉?

How to make controller handle immediately every request and make sleeping in a background?

@Edit

示例:
想象一下,我的控制器需要向外部api发出请求并根据其响应发送自己的响应。外部api调用需要2秒钟。我希望我的应用程序的用户只等待2.5秒,而不是放在队列中,因为控制器一次只能处理一个请求。

Example: Imagine a situation, that my controller needs to make a request to external api and based on its response it should send his own response. External api call takes lets say 2 seconds. I want users of my application to wait only that 2,5 seconds and not be placed in queue, because the controller can handle only one request at a time.

推荐答案


REST控制器是多线程的吗?

Is REST controller multithreaded?

REST控制器是多线程的 DisptcherServlet 同时处理来自客户端的多个请求,并使用相应的控制器方法提供服务。您可以参考请求处理流程此处

REST controller is multithreaded as the DisptcherServlet handles multiple requests from the clients concurrently and serves using the respective controller methods. You can refer the request handling flow here


如何让控制器立即处理每个请求并让
在后台休息?

How to make controller handle immediately every request and make sleeping in a background?

你可以通过在Spring控制器方法中返回 Callable< String> 来做到这一点,如下所示:

You can do that by returning Callable<String> in the Spring controller method as shown below:

@Controller
public class MyController {

    @RequestMapping(value="/sleep")
    public Callable<String> myControllerMethod() {
        Callable<String> asyncTask = () -> { try {
            System.out.println(" WAITING STARTED:"+new Date());
            Thread.sleep(5000);
            System.out.println(" WAITING COMPLETED:"+new Date());
            return "Return";//Send the result back to View Return.jsp
        } catch(InterruptedException iexe) {
            //log exception
            return "ReturnFail";
        }}; 
    return asyncTask;
  }

输出:

等待开始:2016年11月24日星期二21:03:12 GMT

WAITING STARTED: Thu Nov 24 21:03:12 GMT 2016

等待完成:11月24日星期四21:03:17 GMT 2016

WAITING COMPLETED: Thu Nov 24 21:03:17 GMT 2016

此后,视图将返回Return.jsp页面。

After this, the view will be returned "Return.jsp" page.

此处, controller方法将在一个单独的线程中运行(释放实际的servlet线程),一旦任务完成,Result将再次发送回客户端(View等..)。

PS: 您需要添加 @EnableAsync 作为应用配置的一部分,你可以看看这里就此而言。

P.S.: You need to add @EnableAsync as part of your application configuration, you can look here on this.

这篇关于REST控制器是多线程的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆