【spring-data-elasticsearch升级兼容6.1.1ES版本】----基于注解配置

原创 2018年04月17日 17:57:02
        

        该项目是基于spring-data-elasticsearch改造的,向上兼容ES6.1.1版本,由于公司底层ES升级,对于业务系统来说,最新版本的spring-data-elasticsearch已经无法支持了。(下面是spring-data-elasticsearch对ES各个版本的支持)

                                                      

     本篇主要讲解elasticsearch在spring boot里配置。

     由于spring boot用的是<version>2.0.0.RELEASE</version>,默认的属性配置是在spring-boot-autoconfigure项目里面,(如下图所示)

                            

但该属性配置会使用到部分5.5.0的类。因此我就自己处理了一下client的bean注册。一个配置类,一个属性类,一个工厂类,具体代码如下所示

/**
 * Project Name:fire-industry-DM-center
 * File Name:ElasticsearchConfig.java
 * Package Name:com.firestone.config.elasticsearch
 * Date:2018年3月13日下午2:18:10
 *
*/

package com.firestone.config.elasticsearch;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.lease.Releasable;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.util.ReflectionUtils;

/**
 * @Description: TODO(ES client连接)
 * @author CAIYJ
 * @date 2018年3月13日 下午2:18:10
 */
@Configuration
@ConditionalOnClass({Client.class, TransportClientFactoryBean.class})
@EnableConfigurationProperties({ElasticsearchProperties.class})
public class ElasticsearchConfig implements DisposableBean {
    private static final Logger logger = LogManager
            .getLogger(ElasticsearchConfig.class);
    private final ElasticsearchProperties properties;
    private Releasable releasable;

    public ElasticsearchConfig(ElasticsearchProperties properties) {
        this.properties = properties;
    }

    @Bean
    @ConditionalOnMissingBean
    public Client elasticsearchClient() {
        try {
            return createTransportClient();
        } catch (Exception var2) {
            throw new IllegalStateException(var2);
        }
    }

    @Bean
    public ElasticsearchTemplate elasticsearchTemplate(Client client){
        return new ElasticsearchTemplate(client);
    }

    private Client createTransportClient() throws Exception {
        TransportClientFactoryBean factory = new TransportClientFactoryBean();
        factory.setClusterNodes(this.properties.getClusterNodes());
        factory.setClusterName(this.properties.getClusterName());
        factory.afterPropertiesSet();
        TransportClient client = factory.getObject();
        this.releasable = client;
        return client;
    }


    public void destroy() throws Exception {
        if(this.releasable != null) {
            try {
                if(logger.isInfoEnabled()) {
                    logger.info("Closing Elasticsearch client");
                }

                try {
                    this.releasable.close();
                } catch (NoSuchMethodError var2) {
                    ReflectionUtils.invokeMethod(ReflectionUtils.findMethod(Releasable.class, "release"), this.releasable);
                }
            } catch (Exception var3) {
                if(logger.isErrorEnabled()) {
                    logger.error("Error closing Elasticsearch client: ", var3);
                }
            }
        }

    }
}
/**
 * Project Name:fire-industry-DM-center
 * File Name:ElasticsearchProperties.java
 * Package Name:com.firestone.config.elasticsearch
 * Date:2018年3月14日下午4:26:09
 *
*/

package com.firestone.config.elasticsearch;

import java.util.HashMap;
import java.util.Map;

import org.springframework.boot.context.properties.ConfigurationProperties;

/**
 * @Description: TODO(ES配置)
 * @author CAIYJ
 * @date 2018年3月14日 下午4:26:09
 */
@ConfigurationProperties(prefix = "spring.elasticsearch")
public class ElasticsearchProperties {
    /**
     * Elasticsearch cluster name.
     */
    private String clusterName = "elasticsearch";

    /**
     * Comma-separated list of cluster node addresses. If not specified, starts a client
     * node.
     */
    private String clusterNodes;

    /**
     * Additional properties used to configure the client.
     */
    private Map<String, String> properties = new HashMap<String, String>();

    public String getClusterName() {
        return this.clusterName;
    }

    public void setClusterName(String clusterName) {
        this.clusterName = clusterName;
    }

    public String getClusterNodes() {
        return this.clusterNodes;
    }

    public void setClusterNodes(String clusterNodes) {
        this.clusterNodes = clusterNodes;
    }

    public Map<String, String> getProperties() {
        return this.properties;
    }

    public void setProperties(Map<String, String> properties) {
        this.properties = properties;
    }

}


/**
 * Project Name:fire-industry-DM-center
 * File Name:TransportClientFactoryBean.java
 * Package Name:com.firestone.config.elasticsearch
 * Date:2018年3月14日下午4:13:38
 *
*/

package com.firestone.config.elasticsearch;

import java.net.InetAddress;

import org.apache.commons.lang.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.util.Assert;

/**
 * @Description: TODO(ES连接池)
 * @author CAIYJ
 * @date 2018年3月14日 下午4:13:38
 */
public class TransportClientFactoryBean implements FactoryBean<TransportClient>,
        InitializingBean, DisposableBean {

    private static final Logger logger = LogManager
            .getLogger(TransportClientFactoryBean.class);

    private String clusterNodes = "127.0.0.1:9300";
    private String clusterName = "elasticsearch";
    private Boolean clientTransportSniff = true;
    private Boolean clientIgnoreClusterName = Boolean.FALSE;
    private String clientPingTimeout = "5s";
    private String clientNodesSamplerInterval = "5s";
    private TransportClient client;
    static final String COLON = ":";
    static final String COMMA = ",";

    @Override
    public void destroy() throws Exception {
        try {
            logger.info("Closing elasticSearch  client");
            if (client != null) {
                client.close();
            }
        } catch (final Exception e) {
            logger.error("Error closing ElasticSearch client: ", e);
        }
    }

    @Override
    public TransportClient getObject() throws Exception {
        return client;
    }

    @Override
    public Class<TransportClient> getObjectType() {
        return TransportClient.class;
    }

    @Override
    public boolean isSingleton() {
        return false;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        buildClient();
    }

    protected void buildClient() throws Exception {

        this.client = new PreBuiltTransportClient(settings());
        Assert.hasText(clusterNodes,
                "[Assertion failed] clusterNodes settings missing.");
        for (String clusterNode : StringUtils.split(clusterNodes, COMMA)) {
            String hostName = StringUtils.substringBeforeLast(clusterNode,
                    COLON);
            String port = StringUtils.substringAfterLast(clusterNode, COLON);
            Assert.hasText(hostName,
                    "[Assertion failed] missing host name in 'clusterNodes'");
            Assert.hasText(port,
                    "[Assertion failed] missing port in 'clusterNodes'");
            logger.info("adding transport node : " + clusterNode);
            this.client.addTransportAddress(new TransportAddress(
                    InetAddress.getByName(hostName), Integer.valueOf(port)));
        }
    }

    private Settings settings() {
        return Settings.builder().put("cluster.name", clusterName)
                .put("client.transport.sniff", clientTransportSniff)
                .put("client.transport.ignore_cluster_name",
                        clientIgnoreClusterName)
                .put("client.transport.ping_timeout", clientPingTimeout)
                .put("client.transport.nodes_sampler_interval",
                        clientNodesSamplerInterval)
                .build();
    }

    public void setClusterNodes(String clusterNodes) {
        this.clusterNodes = clusterNodes;
    }

    public void setClusterName(String clusterName) {
        this.clusterName = clusterName;
    }

    public void setClientTransportSniff(Boolean clientTransportSniff) {
        this.clientTransportSniff = clientTransportSniff;
    }

    public String getClientNodesSamplerInterval() {
        return clientNodesSamplerInterval;
    }

    public void setClientNodesSamplerInterval(
            String clientNodesSamplerInterval) {
        this.clientNodesSamplerInterval = clientNodesSamplerInterval;
    }

    public String getClientPingTimeout() {
        return clientPingTimeout;
    }

    public void setClientPingTimeout(String clientPingTimeout) {
        this.clientPingTimeout = clientPingTimeout;
    }

    public Boolean getClientIgnoreClusterName() {
        return clientIgnoreClusterName;
    }

    public void setClientIgnoreClusterName(Boolean clientIgnoreClusterName) {
        this.clientIgnoreClusterName = clientIgnoreClusterName;
    }

}


openstack从入门到精通—基于Ocata版本

-
  • 1970年01月01日 08:00

【spring-data-elasticsearch升级兼容6.1.1ES版本】向上兼容粗略说明

声明:本次改造是站在巨人的肩膀上改的,主要是公司Elasticsearch升级到了6.1.1。然后。问题就来了,spring-data-elasticsearch只最高兼容到5.5.0,这就很烦了,本...
  • youzi_or_youzi
  • youzi_or_youzi
  • 2018-04-18 15:29:09
  • 3

解决spring-data-elasticsearch 5.4.0 不支持 5.4.1的elasticsearch问题

  • 2017年06月27日 18:08
  • 31.73MB
  • 下载

最新spring-data-elasticsearch版本下载列表

https://github.com/spring-projects/spring-data-elasticsearch/releases 最新spring-data-elasticsear...
  • newbornzhao
  • newbornzhao
  • 2017-12-18 15:02:35
  • 376

吐个槽 Spring Data Elasticsearch 3.0M1还不支持Elasticsearch 5.X

Spring Data Elasticsearch的最新版本还是不支持5.1.1,本以为只是初始化的地方不一样,结果修改了一部分,发现jpa的支持实现全都变了,只好放弃,白整合了一个上午。拿最新3.0...
  • applebomb
  • applebomb
  • 2017-01-12 17:00:49
  • 3016

android apk版本更新,兼容android7.0

转载地址:http://blog.csdn.net/yulianlin/article/details/52775160
  • LVOEWZDG
  • LVOEWZDG
  • 2017-08-13 22:59:52
  • 550

APP版本兼容,伤不起!

之前bert君一直从事web和微信公众号开发,基本没有接触过APP开发。现在的工作,需要给APP客户端提供服务器接口。因为之前设计不周,在一次版本升级后,造成旧版APP用户无法正常使用,影响了系统订单...
  • u013628152
  • u013628152
  • 2016-06-30 00:15:38
  • 3132

Sping Data与Elasticsearch整合

介绍了Spring Data与Elastic search整合方式以及优缺点
  • u011923621
  • u011923621
  • 2017-01-16 20:27:32
  • 7129

spring-data-elasticsearch 2.1.4 升级 3.0.0 RC2 失败记录

由于ES2.X的client使用的是jetty3,和系统使用的jetty4不兼容,并且看到最新的spring-data-elasticsearch支持了ES5.5.1,于是尝试升级: ste...
  • applebomb
  • applebomb
  • 2017-08-04 21:24:49
  • 763

Spring-data +elasticsearch 2.4.4 整合搭建指南

Spring-data +elasticsearch 2.4.4 整合搭建指南 最后更新: 17-3-24 1. 简介 spring data是一个统一包括数据库系统和NoSQL数据...
  • jek123456
  • jek123456
  • 2017-03-28 17:16:18
  • 6296
收藏助手
不良信息举报
您举报文章:【spring-data-elasticsearch升级兼容6.1.1ES版本】----基于注解配置
举报原因:
原因补充:

(最多只允许输入30个字)