1. 程式人生 > >spring boot 2.X 集成 Elasticsearch 5.x 實戰 增刪改查

spring boot 2.X 集成 Elasticsearch 5.x 實戰 增刪改查

springboot2.x Elasticsearch5.x 集成 實戰 增刪改查

其實這種博客網上一大片,為啥還要寫出來這篇博客?
網上的例子都是基於elasticsearch2.x版本的,並不是5.x版本,而且還有好多是錯的,拿過來根本不能直接用來測試,還有就是spring-data沒有對應的5.x版本,出於對方面考慮,所以就用spring boot 2.x來做一個demo,分享出來。如果有錯誤,歡迎指出。

具體的代碼網址githup:https://github.com/growup818/springboot-es-search

實戰:

ES數據配置類

package org.githup.es.config;

import java.net.InetAddress;

import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

/**
 * 數據配置,進行初始化操作
 * 
 * @author sdc
 *
 */
@Configuration
public class ESConfiguration implements FactoryBean<TransportClient>, InitializingBean, DisposableBean {

    private static final Logger logger = LoggerFactory.getLogger(ESConfiguration.class);

    /**
     * es集群地址
     */
    @Value("${elasticsearch.ip}")
    private String hostName;
    /**
     * 端口
     */
    @Value("${elasticsearch.port}")
    private String port;
    /**
     * 集群名稱
     */
    @Value("${elasticsearch.cluster.name}")
    private String clusterName;

    /**
     * 連接池
     */
    @Value("${elasticsearch.pool}")
    private String poolSize;

    private TransportClient client;

    @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 {
        try {
            // 配置信息
            Settings esSetting = Settings.builder().put("cluster.name", clusterName).put("client.transport.sniff", true)// 增加嗅探機制,找到ES集群
                    .put("thread_pool.search.size", Integer.parseInt(poolSize))// 增加線程池個數,暫時設為5
                    .build();

            client = new PreBuiltTransportClient(esSetting);
            InetSocketTransportAddress inetSocketTransportAddress = new InetSocketTransportAddress(InetAddress.getByName(hostName), Integer.valueOf(port));
            client.addTransportAddresses(inetSocketTransportAddress);

        } catch (Exception e) {
            logger.error("elasticsearch TransportClient create error!!!", e);
        }
    }

}

dao層,數據層,增刪改查進行簡單數據封裝

package org.githup.es.dao;

import java.util.Map;
import java.util.UUID;

import org.elasticsearch.action.admin.indices.create.CreateIndexResponse;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexResponse;
import org.elasticsearch.action.admin.indices.exists.indices.IndicesExistsRequest;
import org.elasticsearch.action.admin.indices.exists.indices.IndicesExistsResponse;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetRequestBuilder;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONObject;

/**
 * ES的操作數據類
 * 
 * 備註:對es的一些操作做了一些封裝,抽出來一些操作,就是傳統的dao層,數據服務
 * 
 * @author sdc
 *
 */
@Component
public class ESRepository {

    private static final Logger log = LoggerFactory.getLogger(ESRepository.class);

    @Autowired
    private TransportClient client;

    /**
     * 創建索引
     *
     * @param index
     * @return
     */
    public boolean buildIndex(String index) {
        if (!isIndexExist(index)) {
            log.info("Index is not exits!");
        }
        CreateIndexResponse buildIndexresponse = client.admin().indices().prepareCreate(index).execute().actionGet();
        log.info(" 創建索引的標誌: " + buildIndexresponse.isAcknowledged());

        return buildIndexresponse.isAcknowledged();
    }

     /**
     * 刪除索引
     *
     * @param index
     * @return
     */
    public boolean deleteIndex(String index) {
        if (!isIndexExist(index)) {
            log.info(" 索引不存在 !!!!!!");
        }
        DeleteIndexResponse diResponse = client.admin().indices().prepareDelete(index).execute().actionGet();
        if (diResponse.isAcknowledged()) {
            log.info("刪除索引**成功** index->>>>>>>" + index);
        } else {
            log.info("刪除索引**失敗** index->>>>> " + index);
        }
        return diResponse.isAcknowledged();
    }

    /**
     * 查詢數據
     * @param index 索引<----->關系型數據庫
     * @param type  類型<----->關系型數據表
     * @param id    數據ID<----->id
     * @return
     */
    public Map<String, Object> searchDataByParam(String index, String type, String id) {
        if(index == null || type == null || id == null) {
            log.info(" 無法查詢數據,缺唯一值!!!!!!! ");
            return null;
        }
        //來獲取查詢數據信息
        GetRequestBuilder getRequestBuilder = client.prepareGet(index, type, id);
        GetResponse getResponse = getRequestBuilder.execute().actionGet(); 
        //這裏也有指定的時間獲取返回值的信息,如有特殊需求可以

        return getResponse.getSource();
    }

    /**
     * 更新數據
     *
     * @param data  添加的數據類型 json格式的
     * @param index 索引<----->關系型數據庫
     * @param type  類型<----->關系型數據表
     * @param id    數據ID<----->id
     * @return
     */
    public void updateDataById(JSONObject data, String index, String type, String id) {
        if(index == null || type == null || id == null) {
            log.info(" 無法更新數據,缺唯一值!!!!!!! ");
            return;
        }

        //更新步驟
        UpdateRequest up = new UpdateRequest();
        up.index(index).type(type).id(id).doc(data);

        //獲取響應信息
        //.actionGet(timeoutMillis),也可以用這個方法,當過了一定的時間還沒得到返回值的時候,就自動返回。
        UpdateResponse response = client.update(up).actionGet();
        log.info("更新數據狀態信息,status{}", response.status().getStatus());
    }

    /**
     * 添加數據
     *
     * @param data  添加的數據類型 json格式的
     * @param index 索引<----->關系型數據庫
     * @param type  類型<----->關系型數據表
     * @param id    數據ID<----->id
     * @return
     */
    public String addTargetDataALL(JSONObject data, String index, String type, String id) {
        //判斷一下次id是否為空,為空的話就設置一個id
        if(id == null) {
            id = UUID.randomUUID().toString();
        }
        //正式添加數據進去
        IndexResponse response = client.prepareIndex(index, type, id).setSource(data).get();

        log.info("addTargetDataALL 添加數據的狀態:{}", response.status().getStatus());

        return response.getId();
    }

    /**
     * 通過ID刪除數據
     *
     * @param index 索引,類似數據庫
     * @param type  類型,類似表
     * @param id    數據ID
     */
    public void delDataById(String index, String type, String id) {

        if(index == null || type == null || id == null) {
            log.info(" 無法刪除數據,缺唯一值!!!!!!! ");
            return;
        }
        //開始刪除數據
        DeleteResponse response = client.prepareDelete(index, type, id).execute().actionGet();

        log.info("刪除數據狀態,status-->>>>{},", response.status().getStatus());
    }

    /**
     * 判斷索引是否存在
     *
     * @param index
     * @return
     */
    public boolean isIndexExist(String index) {
        IndicesExistsResponse iep = client.admin().indices().exists(new IndicesExistsRequest(index)).actionGet();
        if (iep.isExists()) {
            log.info("此索引 [" + index + "] 已經在ES集群裏存在");
        } else {
            log.info(" 沒有此索引 [" + index + "] ");
        }
        return iep.isExists();
    }

}

service層,進行接口數據封裝:

package org.githup.es.service;

import java.util.Map;

import com.alibaba.fastjson.JSONObject;

/**
 * ES服務端
 * 
 * @author sdc
 *
 */
public interface ESSearchService {

    /**
     * 構建索引
     * @param index
     * @return
     */
    public boolean buildIndex(String index);

    /**
     * 刪除索引
     * @param index
     * @return
     */
    public boolean delIndex(String index);

    /**
     * 查詢數據
     * @param index 索引<----->關系型數據庫
     * @param type  類型<----->關系型數據表
     * @param id    數據ID<----->id
     * @return
     */
    public Map<String, Object> searchDataByParam(String index, String type, String id);

    /**
     * 更新數據
     *
     * @param data  添加的數據類型 json格式的
     * @param index 索引<----->關系型數據庫
     * @param type  類型<----->關系型數據表
     * @param id    數據ID<----->id
     * @return
     */
    public void updateDataById(JSONObject data, String index, String type, String id);

    /**
     * 添加數據
     *
     * @param data  添加的數據類型 json格式的
     * @param index 索引<----->關系型數據庫
     * @param type  類型<----->關系型數據表
     * @param id    數據ID<----->id
     * @return
     */
    public String addTargetDataALL(JSONObject data, String index, String type, String id);

    /**
     * 通過ID刪除數據
     *
     * @param index 索引,類似數據庫
     * @param type  類型,類似表
     * @param id    數據ID
     */
    public void delDataById(String index, String type, String id);

    /**
     * 判斷索引是否存在
     *
     * @param index
     * @return
     */
    public boolean isIndexExist(String index);

}

package org.githup.es.service.impl;

import java.util.Map;

import org.githup.es.dao.ESRepository;
import org.githup.es.service.ESSearchService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;

/**
 * ES具體實現類
 * 
 * 備註:抽出ES的分類信息
 * 
 * @author sdc
 *
 */
@Service
public class ESSearchServiceImpl implements ESSearchService{

    @Autowired
    private ESRepository eSRepository;

    @Override
    public boolean buildIndex(String index) {
        return eSRepository.buildIndex(index);
    }

    @Override
    public boolean delIndex(String index) {
        return eSRepository.deleteIndex(index);
    }

    @Override
    public Map<String, Object> searchDataByParam(String index, String type, String id) {
        // TODO Auto-generated method stub
        return eSRepository.searchDataByParam(index, type, id);
    }

    @Override
    public void updateDataById(JSONObject data, String index, String type, String id) {
        // TODO Auto-generated method stub
        eSRepository.updateDataById(data, index, type, id);
    }

    @Override
    public String addTargetDataALL(JSONObject data, String index, String type, String id) {
        // TODO Auto-generated method stub
        return eSRepository.addTargetDataALL(data, index, type, id);
    }

    @Override
    public void delDataById(String index, String type, String id) {
        // TODO Auto-generated method stub
        eSRepository.delDataById(index, type, id);
    }

    @Override
    public boolean isIndexExist(String index) {
        // TODO Auto-generated method stub
        return eSRepository.isIndexExist(index);
    }

}


maven環境:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

    <modelVersion>4.0.0</modelVersion>

    <groupId>org.githup.es</groupId>
    <artifactId>springboot-es-sample-search</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>spring-boot-es</name>
    <description>搜索服務的實現類</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.0.RELEASE</version>
        <relativePath /> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>

        <elasticsearch.version>5.5.3</elasticsearch.version>
        <log4j2.version>2.6.2</log4j2.version>
        <fastjson.version>1.2.31</fastjson.version>
        <commons.lang3.version>3.4</commons.lang3.version>
    </properties>

    <repositories>
        <repository>
            <id>spring-releases</id>
            <url>https://repo.spring.io/libs-release</url>
        </repository>
    </repositories>

    <!-- elasticsearch 5.x 依賴 -->
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-web -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.elasticsearch</groupId>
            <artifactId>elasticsearch</artifactId>
            <version>${elasticsearch.version}</version>
        </dependency>

        <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>transport</artifactId>
            <version>${elasticsearch.version}</version>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>${fastjson.version}</version>
        </dependency>

        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>${commons.lang3.version}</version>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>${fastjson.version}</version>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <configuration>
                    <skip>true</skip>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

具體的代碼網址githup:https://github.com/growup818/springboot-es-search

可以下載下來,熟悉springboot的小夥伴可以很快進行demo檢測。

spring boot 2.X 集成 Elasticsearch 5.x 實戰 增刪改查