我正在使用 jersey 客户端向第三方网络服务发送 POST 请求。由于创建 Jersey 客户端很昂贵,我在 Spring 管理的服务客户端类的构造函数中执行此操作。我的想法是,当我的服务器启动时,Spring 将创建我的服务客户端 bean,这反过来会导致构造函数被调用,因此我的 Jersey 客户端将被创建一次。只要服务器启动,这个 Jersey 客户端就会负责发送请求,不需要进一步的客户端初始化。但是,我将为每次调用创建一个新的网络资源,因为创建 Jersey 网络资源要便宜得多。
package com.mypackage;
//Bunch of imports
class MyWebserviceClient {
//jersey client member variable
private Client jClient;
public MyWebserviceClient(){
//Create jersey client
jClient = Client.create();
//Other stuff
}
public void sendRequest(){
WebResource wr = jClient.resource(someUrl);
//Use the webresource to make webservice call
}
}
MyWebserviceClient
在 Spring 配置 xml 中是这样管理的:
<bean id="myClient" class="com.mypackage,MyWebserviceClient"></bean>
然后 bean myClient
将被注入(inject)到需要进行服务调用的适当位置。
我的问题
1) 如果我的应用程序每小时处理数千个请求,它是否足以通过一个 jersey 客户端处理所有请求。
2) 我是否需要某种 Jersey 客户端池,以便更有效地处理大量请求。如果可以,有什么办法吗?
3) 我想知道服务器端如何处理来自最终用户的多个请求。每个请求都是服务器上一个单独的执行线程,并且所有请求都可以访问同一个 jersey 客户端对象。如果 Jersey 客户端对象正忙于一个这样的请求,来自不同最终用户的其他请求是否会等到收到对正在进行的请求的响应?
4) 任何比我正在使用的更好的替代品。
最佳答案
您的想法是正确的。
1 - 是的,建议重用客户端实例:
来自 https://jersey.java.net/documentation/1.18/client-api.html#d4e623 :
Client instances are expensive resources. It is recommended a configured instance is reused for the creation of Web resources. The creation of Web resources, the building of requests and receiving of responses are guaranteed to be thread safe. Thus a Client instance and WebResource instances may be shared between multiple threads.
2 - 不需要,客户端自己可以处理请求。在异步请求的情况下,它在内部使用一个可配置的线程池。
3 - Jersey 客户端是线程安全的,所以线程不会互相阻塞
4 - 您还可以考虑将客户端作为对 MyWebserviceClient 的依赖项提供,并可能在多个类之间重用相同的客户端
关于java - 在 spring 托管 bean 的构造函数中初始化 Jersey 客户端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22227914/