gpt4 book ai didi

java - 当用户从资源类访问资源时,Rest Service 将如何执行?

转载 作者:搜寻专家 更新时间:2023-11-01 01:40:10 28 4
gpt4 key购买 nike

当多个用户从服务类请求相同的资源方法时,服务器将如何处理请求?

休息服务将如何为每个请求执行? rest 服务的执行生命周期与 servlet 执行有何不同?

例如下面是一个Resource,在下面的场景下,它是如何被实例化和执行的:

case 1: two users call the two different methods at a time

case 2: two users call the same method at a time

@Path("greet")
public class GreetingResource {

@GET
@Path("welcome/{username}")
@Produces(MediaType.TEXT_PLAIN)
public String sayWelcome(@PathParam("username") String User) {
return "Welcome!" + User;
}

@GET
@Path("hello/{username}")
@Produces(MediaType.TEXT_PLAIN)
public String sayHello(@PathParam("username") String User) {
return "Hello " + User;
}
}

最佳答案

来自 Jersey documentation这是 JAX-RS 实现:

Default lifecycle (applied when no annotation is present). In this scope the resource instance is created for each new request and used for processing of this request. If the resource is used more than one time in the request processing, always the same instance will be used. This can happen when a resource is a sub resource and is returned more times during the matching. In this situation only one instance will serve the requests.

来自 Life Cycle of JAX-RS Resource Class :

By default the life-cycle of root resource classes is per-request which, namely that a new instance of a root resource class is created every time the request URI path matches the root resource.

In short, following things happen in sequence.

Path’s are matched with Resource classes.
Constructor is called.
Dependencies are injected.
Appropriate method is called.
Resource is garbage collected.

Strangely, JAX-RS resource classes are not by default singleton. In general this is unlikely to be a cause of performance issues. Class construction and garbage collection of JVMs has vastly improved over the years and many objects will be created and discarded to serve and process the HTTP request and return the HTTP response.

虽然默认情况下根据请求创建端点类,但您可以将其设为单例,使每个 JAX-RS 应用程序拥有一个实例:JAX-RS Resource Lifecycle Performance Impact

关于您的示例,在这两种情况下,实例化 1 和实例化 2 都没有区别,用户将使用 GreetingResource 的 2 个实例并在返回时获取他们的名字。在情况 2 中,如果该方法将使用数据库并且 2 个用户将修改同一资源,则您需要使用 optimistic locking 管理并发访问。或其他解决方案。

关于java - 当用户从资源类访问资源时,Rest Service 将如何执行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49257122/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com