解释:在高并发情况下,重复的创建Client对象会大量占用内存,并且开销昂贵,将其保存到队列当中,避免重复创建对象;调用Client的时候先从队列中取,如果有则使用队列中的Client,如果没有则创建,最后都还将client对象重新放入队列供下次使用。 注:同一客户端同一时刻只能被一个线程消费,否则可能会因争用导致莫名其妙的错误,所以阻塞队列。 代码示例:
public class ClientUtil {
private static final BlockingQueue<Client> blockingQueue = new LinkedBlockingQueue<>(50);
public static Client getClient() throws InterruptedException {
Client client = blockingQueue.poll();
if(client == null){
JaxWsDynamicClientFactory clientFactory = JaxWsDynamicClientFactory.newInstance();
client = clientFactory.createClient("http://xxx/xxx/xxx?wsdl");
}
HTTPConduit conduit = (HTTPConduit) client.getConduit();
HTTPClientPolicy policy = new HTTPClientPolicy();
policy.setConnectionTimeout(5000);
policy.setAllowChunking(false);
policy.setReceiveTimeout(5000);
conduit.setClient(policy);
blockingQueue.offer(client);
return client;
}
|