且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Rest Controller 如何同时处理单个实例应用程序的多个请求?

更新时间:2023-11-22 22:06:04

从 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.