基于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; } }
下一篇: 混个球给宝宝喂奶
推荐阅读
-
02Spring基于xml的IOC配置--实例化Bean的三种方式
-
Spring-Data-JPA整合MySQL和配置的方法
-
01Spring基于xml的IOC配置--入门
-
spring cloud 入门系列七:基于Git存储的分布式配置中心--Spring Cloud Config
-
Spring Boot加密配置文件特殊内容的示例代码详解
-
Spring整合Struts 2与Hibernate(基于XML配置的S2SH整合)
-
基于spring JdbcTemplate的扩展,结合velocity模板实现sql语句的可配置可动态添加
-
基于spring JdbcTemplate的扩展,结合velocity模板实现sql语句的可配置可动态添加
-
Spring5参考指南:基于注解的容器配置
-
基于spring data的Elastic Search的配置示例