Rest Controller 如何同时处理单个实例应用程序的多个请求? [英] How Rest Controller handle multiple request at same time for a single instance application?

查看:357
本文介绍了Rest Controller 如何同时处理单个实例应用程序的多个请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  1. 如果在应用程序中同时向单个 RestController 发出多个请求,如何处理不同的场景(多个请求到单个端点(仅 GET),或多个端点的多个请求(GET、POST、放...))
  2. 是否使用了多线程概念?如果是,是否可以以 FIFO 模式处理请求?
  3. RestController 可以接受的最大请求是多少?
  4. RestController 范围是否会影响请求的处理(默认范围为单例的请求范围的行为)?
  5. 还有它是如何由应用程序上下文处理的(流程示例会有所帮助)

考虑使用 Spring Boot 2 构建微服务.

推荐答案

从 Spring (Application Context) 的角度来看,rest controller 是单例的,如果没有另外指定.

From the point of view of Spring (Application Context) rest controller is a singleton if not specified otherwise.

所以控制器的代码必须准备好被多个线程同时调用.

So the code of controller must be ready to be invoked by multiple threads simultaneously.

当新请求到达服务器时,在传统的每请求线程模型中,Web 服务器(如 tomcat)负责从预定义的线程池中为请求分配一个线程.然后请求在此线程的上下文中由控制器处理.

When a new request reaches the server, in a tradition thread-per-request model the web server (like tomcat) is responsible to allocate a thread from the predefined pool of threads to the request. Then the request gets processed by controller in the context of this thread.

实际的线程池实现通常会因服务器而异,但总的来说,它是可以配置的(每个循环的线程数,如果池已满,则存储请求以供将来处理的队列大小等.)

The actual thread pool implementation can in general vary from server to server, but in general, its something that can be configured (number of threads per loop, queue size to store requests for future processing if the pool is full, etc.)

现在关于 RestController 的作用域.如果控制器是无状态的(并且在许多情况下应该是无状态的,只需保持单例).如果您需要为每个请求创建新的控制器实例,请更改范围.显然,每个线程都必须使用相同的(在单例作用域的情况下)rest 控制器的实例,或者如果您指定另一个作用域,spring mvc 将创建一个新的控制器实例.

Now regarding the Scope of RestController. If the controller is stateless (and it should be for many cases, just keep it singleton). If you need the new Instance of controller to be created per request, than change the scope. Obviously each thread will have to use the same (in case of singleton scope) instance of rest controller or spring mvc will create a new instance of controller if you specify another scope.

以上所有答案都适用于传统的"线程每请求模型.

All the answer above applies to a "traditional" thread-per-request model.

请注意,从 spring 5/spring boot 2 开始,spring 还支持带有 webflux 的Reactive"模型.它在 netty 之上工作,并且不使用每个请求的线程模型.如果您对这个模型而不是我试图简要描述的传统模型感兴趣,请在问题中说明.

Note that since spring 5 / spring boot 2 spring also supports "Reactive" model with a webflux. It works on top of netty and doesn't utilize a thread-per-request model. Please specify in the question if you're interested in this model rather than a tradition model that I've tried to briefly describe.

这篇关于Rest Controller 如何同时处理单个实例应用程序的多个请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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