gpt4 book ai didi

java - 如何以线程安全的方式在 JAX-RS 资源中使用 JerseyClient

转载 作者:太空宇宙 更新时间:2023-11-04 09:21:55 26 4
gpt4 key购买 nike

在以下UserResource类中:

public class UserResource {
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Path("/users")
public void createUser() {
//JerseyClient is needed to send a REST request to another RESTful service
}
}

JerseyClient 需要将请求发送到评论中提到的另一个 RESTful API。

由于可能有多个线程同时调用此 UserResource,因此 JerseyClient 可能应该在每个线程的每次调用中初始化,以确保线程安全。然而,JAX-RS Client提到过

Clients are heavy-weight objects that manage the client-side communication infrastructure. Initialization as well as disposal of a Client instance may be a rather expensive operation. It is therefore advised to construct only a small number of Client instances in the application. Client instances must be properly closed before being disposed to avoid leaking resources.

根据文档,在createUser主体内初始化JerseyClient可能会昂贵,从而带来性能问题。

问题:如何以线程安全的方式高效优化JerseyClient实例的数量?

最佳答案

如果将 Client 实例化为类字段就足够了,因为 Client 类是线程安全的。

Jersey documentation说:

Client instances are expensive resources. It is recommended a configured instance is reused for thecreation of Web resources. The creation of Web resources, the building of requests and receiving ofresponses are guaranteed to be thread safe. Thus a Client instance and WebResource instances maybe shared between multiple threads.

关于java - 如何以线程安全的方式在 JAX-RS 资源中使用 JerseyClient,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58225041/

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