ESClientMgr.java 1.7 KB
package com.yoho.search.common;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import javax.annotation.PostConstruct;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import com.yoho.search.core.es.IElasticsearchClient;
import com.yoho.search.core.es.IYohoIndexClientFactory;
import com.yoho.search.core.es.impl.YohoIndexClientFactoryImpl;

/**
 * Created by ginozhang on 2016/11/2.
 */
@Component
public class ESClientMgr {

	private volatile Map<String, IElasticsearchClient> nameToClientMap = new ConcurrentHashMap<String, IElasticsearchClient>(50);

	private static final Logger logger = LoggerFactory.getLogger(ESClientMgr.class);

	@Autowired
	private SearchServiceConfiger configer;

	@PostConstruct
	void init() {
		this.getClient("productindex");
		this.getClient("default");
	}

	public IElasticsearchClient getClient(String indexName) {
		if (!indexName.equalsIgnoreCase("productindex")) {
			indexName = "defalut";
		}
		return nameToClientMap.computeIfAbsent(indexName, (name) -> {
			IYohoIndexClientFactory factory = new YohoIndexClientFactoryImpl();
			String clusterName = configer.getSearchEsClusterName();
			String servers = configer.getSearchEsServers();
			Assert.notNull(clusterName, "ClusterName for ES cannot be null.");
			Assert.notNull(servers, "Servers for ES cannot be null.");
			logger.warn("begin to createIndexClient, clusterName is [{}],servers is [{}],name is[{}]", clusterName, servers, name);
			return factory.createIndexClient(clusterName, servers, name);
		});
	}
}