SearchCommonService.java 6 KB
package com.yoho.search.common;

import com.yoho.error.event.SearchEvent;
import com.yoho.search.base.monitor.PerformanceMonitor;
import com.yoho.search.base.constants.EventReportEnum;
import com.yoho.search.base.constants.ProductIndexEsField;
import com.yoho.search.core.es.IElasticsearchClient;
import com.yoho.search.core.es.model.SearchParam;
import com.yoho.search.core.es.model.SearchResult;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.get.MultiGetItemResponse;
import org.elasticsearch.action.get.MultiGetResponse;
import org.elasticsearch.index.query.QueryBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class SearchCommonService implements ApplicationEventPublisherAware {

	private static final Logger ES_PERFORMANCE = LoggerFactory.getLogger("ES_PERFORMANCE");
	
	@Autowired
	private ElasticsearchClientFactory elasticsearchClientFactory;

	private ApplicationEventPublisher publisher;
	private PerformanceMonitor performanceMonitor;
	
	@PostConstruct
	void init(){
		performanceMonitor = new PerformanceMonitor("ES_PERFORMANCE",ES_PERFORMANCE, 10);
	}
	
	@Override
	public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
		this.publisher = applicationEventPublisher;
	}

	private void publishSearchResultEvent(final String indexName, SearchParam searchParam, SearchResult searchResult) {
		if (searchParam == null || searchResult == null) {
			return;
		}
		if (searchResult.getTotal() > 0 || searchParam.getFiter() == null) {
			return;
		}
		QueryBuilder filter = searchParam.getFiter();
		String filterString = (filter == null ? "" : filter.toString());
		if (!filterString.contains(ProductIndexEsField.poolIds)) {
			return;
		}
		publisher.publishEvent(new SearchEvent(indexName, EventReportEnum.SEARCHCOMMONSERVICE_DOSEARCH.getFunctionName(), EventReportEnum.SEARCHCOMMONSERVICE_DOSEARCH
				.getMoudleName(), "empty_result", null, "[" + indexName + "][" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(System.currentTimeMillis()) + "]["
				+ filterString + "]"));
	}

	/**
	 * 通用的查询接口
	 *
	 * @param indexName
	 * @param
	 * @return
	 */
	public List<SearchResult> doMutiSearch(final String indexName, final List<SearchParam> searchParams) {
		long begin = System.currentTimeMillis();
		performanceMonitor.addVisitCount(searchParams==null?0:searchParams.size());
		try {
			if (searchParams == null || searchParams.isEmpty()) {
				return new ArrayList<SearchResult>();
			}
			IElasticsearchClient client = elasticsearchClientFactory.getClient(indexName);
			List<SearchResult> results = client.multiSearch(indexName, indexName, searchParams);
			for (int i = 0; i < searchParams.size(); i++) {
				SearchResult searchResult = results.get(i);
				SearchParam searchParam = searchParams.get(i);
				this.publishSearchResultEvent(indexName, searchParam, searchResult);
			}
			return results;
		} catch (Exception e) {
			throw e;
		}finally{
			performanceMonitor.addCost(System.currentTimeMillis() - begin);
		}
	}

	/**
	 * 通过id获取内容
	 *
	 * @param indexName
	 * @param id
	 * @return
	 */
	public Map<String, Object> doGetCommon(final String indexName, final String id) {
		long begin = System.currentTimeMillis();
		performanceMonitor.addVisitCount(StringUtils.isBlank(id)?0:1);
		try {
			if (StringUtils.isBlank(id)) {
				return null;
			}
			IElasticsearchClient client = elasticsearchClientFactory.getClient(indexName);
			GetResponse response = client.get(indexName, indexName, id);
			// 判断是否为空
			if (response == null || response.getSource() == null || response.getSource().isEmpty()) {
				return null;
			}
			return response.getSourceAsMap();
		} catch (Exception e) {
			throw e;
		}finally{
			performanceMonitor.addCost(System.currentTimeMillis() - begin);
		}
	}

	/**
	 * 通用的查询接口
	 *
	 * @param indexName
	 * @param searchParam
	 * @return
	 */
	public SearchResult doSearch(final String indexName, final SearchParam searchParam) {
		long begin = System.currentTimeMillis();
		performanceMonitor.addVisitCount();
		try {
			IElasticsearchClient client = elasticsearchClientFactory.getClient(indexName);
			SearchResult searchResult = client.search(indexName, indexName, searchParam);
			this.publishSearchResultEvent(indexName, searchParam, searchResult);
			return searchResult;
		} catch (Exception e) {
			throw e;
		}finally{
			performanceMonitor.addCost(System.currentTimeMillis() - begin);
		}
	}

	/**
	 * 通过id获取内容
	 *
	 * @param indexName
	 * @return
	 */
	public List<Map<String, Object>> doMultiGetCommon(final String indexName, final Collection<?> idList) throws Exception {
		long begin = System.currentTimeMillis();
		performanceMonitor.addVisitCount(idList==null||idList.isEmpty()?0:1);
		try {
			if (idList == null || idList.isEmpty()) {
				return new ArrayList<Map<String, Object>>();
			}
			IElasticsearchClient client = elasticsearchClientFactory.getClient(indexName);
			Set<String> idSet = new HashSet<String>();
			for (Object id : idList) {
				idSet.add(id.toString());
			}
			MultiGetResponse response = client.multiGet(indexName, indexName, idSet, null);
			List<Map<String, Object>> results = new ArrayList<Map<String, Object>>();
			for (MultiGetItemResponse item : response.getResponses()) {
				if (item.getResponse().isExists()) {
					results.add(item.getResponse().getSource());
				}
			}
			return results;
		} catch (Exception e) {
			throw e;
		}finally{
			performanceMonitor.addCost(System.currentTimeMillis() - begin);
		}
	}

}