欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

基于spring data的Elastic Search的配置示例

程序员文章站 2022-07-10 16:17:45
...
基于spring data的Elastic Search的配置示例


import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;

import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.commons.lang3.tuple.Pair;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.repository.config.EnableElasticsearchRepositories;

import com.xxx.cms.config.props.EsProps;
xxx
@Configuration
@EnableElasticsearchRepositories(
		basePackages={"com.xxx.cms.elasticsearch.repositories"}
		)
public class ElasticSearchConfig {

	private Logger logger = LoggerFactory.getLogger(getClass());
	
	@Autowired
	Environment env;
	
	@Bean
    public ElasticsearchOperations elasticsearchTemplate() {
        return new ElasticsearchTemplate(elasticsearchClient());
    }
	
	@Bean
	public EsProps esProps(){
		
		EsProps esProps = new EsProps();
		esProps.setInit(Boolean.valueOf(env.getProperty("hs.cms.srv.es.init")));
		return esProps;
	}
	
	@Bean
	public Client elasticsearchClient(){
		
		String esNodes = env.getProperty("hs.cms.srv.es.cluster.nodes"),
				clusterName = env.getProperty("hs.cms.srv.es.cluster.name");
		ArrayList<Pair<String, Integer>> nodePairs = new ArrayList<>();
		for (String nodeStr : esNodes.split(",")) {
			
			String[] nodeSpliArr = nodeStr.split(":");
			Pair<String, Integer> pair = new ImmutablePair<>(nodeSpliArr[0], Integer.valueOf(nodeSpliArr[1]));
			nodePairs.add(pair);
		}
		
		Settings settings = Settings.settingsBuilder()
                .put("cluster.name", clusterName)
                .build();
		TransportClient client = TransportClient.builder()
                .settings(settings)
                .build();
		for (Pair<String, Integer> pair : nodePairs) {
			
			try {
				client.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(pair.getLeft()), pair.getRight()));
			} catch (UnknownHostException e) {
				
				logger.error("初始化Es配置出错", e);
				return null;
			}
		}
		return client;
	}
	
}