如何以线程安全的方式在 JAX-RS 资源中使用 JerseyClient
How to use JerseyClient in a JAX-RS resource in thread-safe manner
在下面UserResource
class:
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
实例化为 class 字段就足够了,因为 Client
class 是线程安全的。
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.
在下面UserResource
class:
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
实例化为 class 字段就足够了,因为 Client
class 是线程安全的。
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.