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

        

        该项目是基于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;
    }

}


阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页