ElasticsearchClientFactory.java 1.77 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;

@Component
public class ElasticsearchClientFactory {

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

    private static final Logger logger = LoggerFactory.getLogger(ElasticsearchClientFactory.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);
        });
    }
}