ESHttpClient.java 13.5 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421
package com.zhaoonline.common.es;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;

import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
import org.apache.http.ParseException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.zhaoonline.common.Utils.IOUtils;
import com.zhaoonline.common.es.bean.BulkResponse;
import com.zhaoonline.common.es.bean.DeleteResponse;
import com.zhaoonline.common.es.bean.GetResponse;
import com.zhaoonline.common.es.bean.IndexResponse;
import com.zhaoonline.common.es.bean.InterSearchHits;
import com.zhaoonline.common.es.bean.InterSearchResponse;
import com.zhaoonline.common.es.bean.QueryResponse;
import com.zhaoonline.common.json.JsonUtils;


/**
 * class name:ESClient <BR>
 * class description:Elastic的客户端 <BR>
 * Remark: <BR>
 * @version 1.00 2016年10月24日
 * @author zhaoonline)yangyoupeng
 */
public class ESHttpClient {
	private static final Logger LOG = LoggerFactory.getLogger(ESHttpClient.class);
	private static final String PATH_SEPERATOR = "/";
	private String _index;
	private String _type;
	private static final AtomicReference<CloseableHttpClient> httpClient = new AtomicReference<CloseableHttpClient>();
	private static final Thread monitorThread=createMonitorThread();
	private ESClientConfiguration config;
	private String path;
	private List<HttpHost> hostsList=new ArrayList<HttpHost>();
	
	
    private static final Timer CONNECTION_MANAGER_TIMER = new Timer(true);
    
    static {
	        CONNECTION_MANAGER_TIMER.schedule(new TimerTask() {
	            @Override
				public void run() {
	                try {
	                    final CloseableHttpClient hc = httpClient.get();
	                    if (hc == null) return;
	                    hc.getConnectionManager().closeExpiredConnections();
	                    hc.getConnectionManager().closeIdleConnections(30, TimeUnit.SECONDS);
	                } catch (Throwable t) {
	                    LOG.error("error closing expired connections", t);
	                }
	            }
	        }, 30000, 5000);
	        Runtime.getRuntime().addShutdownHook(monitorThread);
	}
    
    
    
	public ESHttpClient(String index,String type,ESClientConfiguration config){
		this._index=index;
		this._type=type;
		concatPathWithIndexType();
		this.config=config;
	}

	private static Thread createMonitorThread() {
		Thread monitorThread =new Thread(new Runnable() {
			@Override
			public void run() {
				CONNECTION_MANAGER_TIMER.cancel();
				LOG.info("pool Manager check timer cancel running");
			}
		});
		return monitorThread;
	}
	private void concatPathWithIndexType() {
		this.path=_index+PATH_SEPERATOR+_type;
	}
	public void init(){
		getClient();
		List<String> hostPosts=config.getHostPorts();
		hostsList=buildHostPortListFromString(hostPosts);
		
	}

	private CloseableHttpClient getClient() {
		if(httpClient.get() ==null){
			httpClient.set(HttpClientFactory.newClient());
		}
		return httpClient.get();
	}

	
	private static List<HttpHost> buildHostPortListFromString(List<String> stringhostPortList) {
		List<HttpHost> hostPorts=new ArrayList<HttpHost>(stringhostPortList.size());
		for(String hostPortString: stringhostPortList){
			
			String[] hostPortArray= hostPortString.split(":");
			if(hostPortArray!=null &&  hostPortArray.length>=2){
				String host=String.valueOf(hostPortArray[0]);
				String port=String.valueOf(hostPortArray[1]);
				HttpHost hostPort= new HttpHost(host,Integer.valueOf(port));
				hostPorts.add(hostPort);
			}
		}
		return hostPorts;
	}
	
	/**
	 * Method name: addDoc <BR>
	 * Description:  添加doc,指定id <BR>
	 * Remark: <BR>
	 * @param id
	 * @param docString
	 * @return  boolean<BR>
	 * @throws IOException 
	 * @throws UnsupportedOperationException 
	 * @throws JsonMappingException 
	 * @throws JsonParseException 
	 */
	public boolean addDoc(String id, String docString) throws JsonParseException, JsonMappingException, UnsupportedOperationException, IOException {
		String pathWithId=path+PATH_SEPERATOR+id;
		CloseableHttpResponse response=	sendPostRequest(docString, pathWithId,this.hostsList);
		
		HttpEntity responseEntity=response.getEntity();
		IndexResponse indexResponse=JsonUtils.toObject(responseEntity.getContent(), IndexResponse.class);
		if(indexResponse !=null){
			return indexResponse.isSuccess();
		}
		IOUtils.closeStream(response);
		return  false;
	}


	public Map searchById(String id) throws JsonParseException, JsonMappingException, UnsupportedOperationException, IOException{
		String pathWithId=path+PATH_SEPERATOR+id;
		HttpRequest request=RequestBuilder.get(pathWithId).build();
		CloseableHttpResponse httpresponse=	sendRequest(request,this.hostsList);
		if(httpresponse ==null){
			return null;
		}
		HttpEntity responseEntity=httpresponse.getEntity();
		GetResponse response=JsonUtils.toObject(responseEntity.getContent(), GetResponse.class);
		IOUtils.closeStream(httpresponse);
		return response.getSource();
	}
	
	
	/**
	 * Method name: search <BR>
	 * Description: search 利用post方法查询doc<BR>
	 * Remark: <BR>
	 * @param queryString
	 * @return
	 * @throws JsonParseException
	 * @throws JsonMappingException
	 * @throws UnsupportedOperationException
	 * @throws IOException  List<Map><BR>
	 */
	public QueryResponse query(String queryString) throws JsonParseException, JsonMappingException, UnsupportedOperationException, IOException{
		String pathWithId=path+PATH_SEPERATOR+"_search";
		CloseableHttpResponse response= sendPostRequest(queryString,pathWithId,this.hostsList);
		HttpEntity responseEntity=response.getEntity();
		String str=EntityUtils.toString(responseEntity);
		InterSearchResponse searchResponse=JsonUtils.toObject(str, InterSearchResponse.class);
		if(searchResponse ==null){
			return null;
		}
		QueryResponse queryResponse =new QueryResponse();
		InterSearchHits searchHits=searchResponse.getHits();
		queryResponse.setTotal(searchHits.getTotal());
		queryResponse.addData(searchHits.getHits());
		IOUtils.closeStream(response);
		return queryResponse;
	}
	
	
	/**
	 * Method name: query <BR>
	 * Description: 根据pagesize返回内容 <BR>
	 * Remark: <BR>
	 * @param queryBuilder
	 * @return
	 * @throws JsonParseException
	 * @throws JsonMappingException
	 * @throws UnsupportedOperationException
	 * @throws IOException  QueryResponse<BR>
	 */
	public QueryResponse query(ZhaoQueryBuilder queryBuilder) throws JsonParseException, JsonMappingException, UnsupportedOperationException, IOException{
		QueryResponse queryResponse=this.query(queryBuilder.toQueryString());
		return queryResponse;
	}
	
	/**
	 * Method name: queryAll <BR>
	 * Description: 返回所有doc <BR>
	 * Remark: <BR>
	 * @param queryBuilder
	 * @return
	 * @throws JsonParseException
	 * @throws JsonMappingException
	 * @throws UnsupportedOperationException
	 * @throws IOException  QueryResponse<BR>
	 */
	public QueryResponse queryAll(ZhaoQueryBuilder queryBuilder) throws JsonParseException, JsonMappingException, UnsupportedOperationException, IOException{
		QueryResponse returnResponse=new QueryResponse();
		
		int size=queryBuilder.getPage().getSize();
		if(size ==0){
			return null;
		}
		
		LoopCount loopcount=null;
		
		boolean readDone=false;
		while(!readDone){
			QueryResponse queryResponse=this.query(queryBuilder);
			int totalSize=queryResponse.getTotal().intValue();
			int returnDataSize=queryResponse.getDataList().size();
		
			
			returnResponse.addData(queryResponse.getDataList());
			int alreadyReadSize=queryBuilder.getPage().getStart()+returnDataSize;
			if(alreadyReadSize >=totalSize ){
				readDone=true;
				returnResponse.setTotal(new Long(totalSize));
				break;
			}
			//为了防止异常的出现死循环
			if(loopcount==null){
				loopcount=new LoopCount();
				loopcount.maxLoopcount=totalSize/size;
			}else if(loopcount.maxLoopcount <= 0){
				break;
			}else{
				loopcount.maxLoopcount=loopcount.maxLoopcount-1;
			}
			queryBuilder.setPage(alreadyReadSize, size);
			
		}
		return returnResponse;
	}
	
	private  class LoopCount{
		int maxLoopcount=0;
	}
	
	
	/**
	 * Method name: addDoc <BR>
	 * Description: 添加doc,id由ES自动生成 <BR>
	 * Remark: <BR>
	 * @param docString
	 * @return  boolean<BR>
	 * @throws IOException 
	 * @throws UnsupportedOperationException 
	 */
	public boolean addDoc(String docString) throws UnsupportedOperationException, IOException {
		CloseableHttpResponse response= sendPostRequest(docString, this.path,this.hostsList);
		HttpEntity responseEntity=response.getEntity();
		IndexResponse indexResponse=JsonUtils.toObject(responseEntity.getContent(), IndexResponse.class);
		if(indexResponse !=null){
			return true;
		}
		IOUtils.closeStream(response);
		return  false;
	}
	
	
	
	private CloseableHttpResponse sendPostRequest(String source, String path,List<HttpHost> hostsList) {
		HttpEntity entity=new StringEntity(source,ContentType.APPLICATION_JSON);
		HttpRequest request=RequestBuilder.post(path).setEntity(entity).build();
		CloseableHttpResponse response=sendRequest(request,hostsList);
		return response;
	}

	private CloseableHttpResponse sendRequest(HttpRequest request,List<HttpHost> hostsList) {
		CloseableHttpResponse response=null;
		for(HttpHost httpHost:hostsList){
			try {
				response= getClient().execute(httpHost, request);
				if(response !=null){
					return response;
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return response;
	}
	
	public void close(){
		IOUtils.closeStream(getClient());
		httpClient.set(null);
	}

	public boolean deleteDoc(String id) throws JsonParseException, JsonMappingException, UnsupportedOperationException, IOException {
		String pathWithId=path+PATH_SEPERATOR+id;
		HttpRequest request=RequestBuilder.delete(pathWithId).build();
		CloseableHttpResponse response=	sendRequest(request,this.hostsList);
		if(response ==null){
			return false;
		}
		HttpEntity responseEntity=response.getEntity();
		DeleteResponse deleteResponse=JsonUtils.toObject(responseEntity.getContent(), DeleteResponse.class);
		IOUtils.closeStream(response);
		return deleteResponse.isSuccess();
	}

	/**
	 * Method name: bulkAddDoc <BR>
	 * Description: 批量添加指定ID <BR>
	 * Remark: <BR>
	 * @param ids
	 * @param dataList
	 * @return
	 * @throws UnsupportedOperationException
	 * @throws IOException  boolean<BR>
	 */
	public boolean bulkAddDoc(List ids,List dataList) throws UnsupportedOperationException, IOException {
		if(!validateBulkInput(ids, dataList)){
			throw new IllegalArgumentException("the ids size is not equal to dataList ");
		};
		
		StringBuilder builder=buildBulkIndexScript(ids,dataList);
		if(builder.length()==0){
			return false;
		}
		return bulkAdd(builder.toString());
	}

	private boolean validateBulkInput(List ids, List dataList) {
		if(ids ==null || dataList == null){
			return false;
		}
		if(ids.size() != dataList.size() ){
			return false;
		}
		return true;
	}
	
	
	/**
	 * Method name: bulkAddDoc <BR>
	 * Description: 批量添加自动生成ID <BR>
	 * Remark: <BR>
	 * @param dataList
	 * @return
	 * @throws UnsupportedOperationException
	 * @throws IOException  boolean<BR>
	 */
	public boolean bulkAddDoc(List dataList) throws UnsupportedOperationException, IOException {
		StringBuilder builder=buildBulkIndexScript(null,dataList);
		if(builder.length()==0){
			return false;
		}
		return bulkAdd(builder.toString());
	}
	
	public boolean bulkAdd(String bulkScripts) throws ParseException, IOException{
		String bulkPath=path+PATH_SEPERATOR+"_bulk";
		CloseableHttpResponse response= sendPostRequest(bulkScripts,bulkPath,this.hostsList);
		if(response ==null){
			return false;
		}
		HttpEntity responseEntity=response.getEntity();
		BulkResponse bulkResponse=JsonUtils.toObject(responseEntity.getContent(), BulkResponse.class);
		IOUtils.closeStream(response);
		return !bulkResponse.isErrors();
	}
	

	public  StringBuilder buildBulkIndexScript(List ids,List dataList) throws JsonProcessingException {
		StringBuilder bulkBuilder=new StringBuilder();
		if(ids !=null && ids.size() !=0){
			for(int i=0;i<ids.size();i++){
				StringBuilder itemBuilder=new StringBuilder();
				itemBuilder.append("{ \"index\" :").append("{ \"_index\" : \"").
													append(this._index).append("\"").append(",\"_type\" :\"").append(this._type).append("\"")
													.append(",\"_id\" :\"").append(ids.get(i)).append("\"")
													.append("} }").append("\n");
				String objectjson=JsonUtils.toJson(dataList.get(i));
				itemBuilder.append(objectjson).append("\n");
				bulkBuilder.append(itemBuilder);
			}
		}else {
			for(Object object:dataList){
				StringBuilder itemBuilder=new StringBuilder();
				itemBuilder.append("{ \"index\" :").append("{ \"_index\" : \"").
				append(this._index).append("\"").append(",\"_type\" :\"").append(this._type).append("\"")
				//.append(",\"_id\" :\"").append(1).append("\"")
				.append("} }").append("\n");
				String objectjson=JsonUtils.toJson(object);
				bulkBuilder.append(itemBuilder);
			}
		}
		return bulkBuilder;
	}
}