import java.util.HashMap;
import java.util.Map;
import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.jboss.resteasy.client.jaxrs.ResteasyClient;
import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;
import org.jboss.resteasy.client.jaxrs.engines.ApacheHttpClient4Engine;
import org.springframework.beans.factory.InitializingBean;
public class RestClientUtil implements InitializingBean{
private HttpClient httpClient;
private ResteasyWebTarget target;
//访问地址。e.g http://127.0.0.1:8080
private String targetAddress ;
public RestClientUtil(){
try{
ThreadSafeClientConnManager connectionManager = new ThreadSafeClientConnManager();
connectionManager.setMaxTotal(2000);
connectionManager.setDefaultMaxPerRoute(200);
this.httpClient =new DefaultHttpClient(connectionManager);
((DefaultHttpClient)this.httpClient).setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler());
}catch(Exception e){
throw new RuntimeException(e);
}
}
[@Override](https://my.oschina.net/u/1162528)
public void afterPropertiesSet() throws Exception {
ResteasyClient client = new ResteasyClientBuilder().httpEngine(new ApacheHttpClient4Engine(httpClient)).build();
target = client.target(targetAddress);
}
private Map<Class<?>,Object> proxyMap = new HashMap<Class<?>,Object>();
public <T> T proxy(Class<T> cls){
T obj = (T)proxyMap.get(cls);
synchronized(this){
if(obj == null){
obj = (T)target.proxy(cls);
proxyMap.put(cls, obj);
}
}
return obj;
}
public String getTargetAddress() {
return targetAddress;
}
public void setTargetAddress(String targetAddress) {
this.targetAddress = targetAddress;
}
}
转载于:https://my.oschina.net/v512345/blog/1536722