Springboot采用JestClient连接ElasticSearch实现基础操作:增、删、改、查

年爸 1年前 ⋅ 4234 阅读

说明:最近公司要做一个负载均衡设备监控系统,数据库采用ElasticSearch,框架采用Springboot,考虑再三采用了JestClient,不多说了,上代码!

1、定义ElasticSearch数据库访问助手

package com.xxx.project.core.utils.dbHelper.impl;

import com.broader.project.core.framework.page.PageInfo;
import com.broader.project.core.utils.dbHelper.model.ElasticSearch;
import com.google.gson.JsonObject;
import io.searchbox.client.JestClient;
import io.searchbox.client.JestClientFactory;
import io.searchbox.client.JestResult;
import io.searchbox.client.config.HttpClientConfig;
import io.searchbox.core.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * ESDBHelper:ElasticSearch数据库访问助手(基于:JestClient)
 *
 * @author 年爸
 * @QQ     526704425
 * @version 1.0
 * @date    2019-02-21
 */
@Component
public class ESDBHelper {

    // ElasticSearch URL
    private String url = "http://192.168.1.11:9200";


    /**
     * 创建JestClient 对象
     */
    private static JestClient jestClient;

    /**
     * 创建JestClient连接
     * @return
     */
    private JestClient getJestClient() {
        JestClientFactory factory = new JestClientFactory();
        factory.setHttpClientConfig(new HttpClientConfig.Builder(url).connTimeout(6000).readTimeout(6000).multiThreaded(true).build());
        return factory.getObject();
    }

    /**
     * 查询-Document实体
     * @param indexName _index名称
     * @param typeName _type名称
     * @param id 文档_id
     * @param clz 类clas
     * @return Document实体
     * @throws Exception
     */
    public Object search4Id(String indexName, String typeName, String id, Class clz) throws Exception{
        // 返回结果
        JestResult jr = null;
        try {
            // jestClient对象
            jestClient = getJestClient();
            Get get = new Get.Builder(indexName, id).type(typeName).build();
            jr = jestClient.execute(get);
        }catch (Exception e){
            throw new Exception(e);
        }finally {
            // 关闭
            jestClient.close();
        }
        return jr.getSourceAsObject(clz);
    }

    /**
     * 查询-String
     * @param indexName _index名称
     * @param typeName _type名称
     * @param query 查询语句
     * @return 查询结果
     * @throws Exception
     */
    public String search4SourceString(String indexName, String typeName, String query) throws Exception {
        // 返回结果
        JestResult jr = null;
        try {
            // jestClient对象
            jestClient = getJestClient();
            Search search = new Search.Builder(query).addIndex(indexName).addType(typeName).build();
            jr = jestClient.execute(search);
        }catch (Exception e){
            throw new Exception(e);
        }finally {
            // 关闭
            jestClient.close();
        }
        return jr.getSourceAsString();
    }

    /**
     * 查询-JsonObject
     * @param indexName _index名称
     * @param query 查询语句
     * @return 查询结果
     * @throws Exception
     */
    public JsonObject search4Query(String indexName, String query) throws Exception {
        JestResult jr = null;
        try {
            jestClient = getJestClient();
            Search search = new Search.Builder(query).addIndex(indexName).build();
            jr = jestClient.execute(search);
        }catch (Exception e){
            throw new Exception(e);
        }finally {
            // 关闭
            jestClient.close();
        }
        return jr.getJsonObject();
    }

    /**
     * 查询-JsonObject
     * @param indexName _index名称
     * @param typeName _type名称
     * @param query 查询语句
     * @return 查询结果
     * @throws Exception
     */
    public JsonObject search4JsonObject(String indexName, String typeName, String query) throws Exception{
        // 返回结果
        JestResult jr = null;
        try {
            // jestClient对象
            jestClient = getJestClient();
            Search search = new Search.Builder(query).addIndex(indexName).addType(typeName).build();
            jr = jestClient.execute(search);
        }catch (Exception e){
            throw new Exception(e);
        }finally {
            // 关闭
            //jestClient.close();
        }
        return jr.getJsonObject();
    }

    /**
     * 查询(分页)
     * @param indexName _index名称
     * @param typeName _type名称
     * @param query 查询语句
     * @param clz 实体类
     * @param <T> 反射T
     * @return 查询结果
     */
    public <T> PageInfo<T> search4Pages(String indexName, String typeName, String query, Class<T> clz) throws Exception {
        // 分页对象
        PageInfo<T> pageInfo = new PageInfo<>();
        // 返回结果
        JestResult jr = null;
        try {
            // jestClient对象
            jestClient = getJestClient();
            Search search = new Search.Builder(query).addIndex(indexName).addType(typeName).build();
            jr = jestClient.execute(search);
            int hitCount = jr.getJsonObject().get("hits").getAsJsonObject().get("total").getAsInt();

            // 总共条数
            pageInfo.setTotalCount(hitCount);
            // 结果集
            pageInfo.setResult(jr.getSourceAsObjectList(clz));

        } catch (IOException e) {
            throw new Exception(e);
        }
        if (jr == null && !jr.isSucceeded()){
            return null;
        }
        return pageInfo;
    }


    /**
     * 新增
     * @param indexName _index名称
     * @param typeName _type名称
     * @param objList 新增对象
     * @return 新增结果
     * @throws Exception
     */
    public boolean insert(String indexName, String typeName, List<Object> objList) throws Exception {
        // 返回结果
        BulkResult br = null;
        try {
            // jestClient对象
            jestClient = getJestClient();
            Bulk.Builder bulk = new Bulk.Builder().defaultIndex(indexName).defaultType(typeName);
            for (Object obj : objList) {
                Index index = new Index.Builder(obj).build();
                bulk.addAction(index);
            }
            br = jestClient.execute(bulk.build());
        }catch (Exception e){
            throw new Exception(e);
        }finally {
            // 关闭
            jestClient.close();
        }
        return br.isSucceeded();
    }

    /**
     * 更新
     * @param json 更新内容
     * @param indexName _index名称
     * @param typeName _type名称
     * @param id 索引id
     * @return 更新结果
     * @throws Exception
     */
    public boolean update(String json, String indexName, String typeName, String id) throws Exception{
        // 返回结果
        JestResult jr = null;
        try {
            // jestClient对象
            jestClient = getJestClient();
            Update update = new Update.Builder(json).index(indexName).type(typeName).id(id).build();
            jr = jestClient.execute(update);
        }catch (Exception e){
            throw new Exception(e);
        }finally {
            // 关闭
            jestClient.close();;
        }
        return jr.isSucceeded();
    }

    /**
     * 删除
     * @param indexName _index名称
     * @param typeName _type名称
     * @param id 索引id
     * @return 删除结果
     * @throws Exception
     */
    public boolean delete(String indexName, String typeName, String id) throws Exception{
        // 返回结果
        DocumentResult jr = null;
        try {
            // jestClient对象
            jestClient = getJestClient();
            Delete delete = new Delete.Builder(id).index(indexName).type(typeName).build();
            jr = jestClient.execute(delete);
        }catch (Exception e){
            throw new Exception(e);
        }finally {
            // 关闭
            jestClient.close();;
        }
        return jr.isSucceeded();
    }
}

2、定义分页实体类

package com.xxx.project.core.framework.page;

import com.broader.project.core.framework.base.BaseModel;

import java.io.Serializable;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

/**
 * Page: 分页实体类
 *
 * @author 年爸
 * @QQ     526704425
 * @version 1.0
 * @date    2019-04-18
 */
public class PageInfo<T> extends BaseModel implements Serializable, Iterable<T> {

    // 当前第N页
    private int pageNumber = 1;

    // 每页条数
    private int pageSize = 10;

    // 总页数
    private int totalPageNumber = 0;

    // 总共条数
    private int totalCount = 0;

    // 查询索引
    private int from = 0;

    // 结果集
    private List<T> result;

    public int getPageNumber() {
        if(pageNumber <= 0)
            pageNumber =1;
        else if(pageNumber > getTotalPageNumber())
            pageNumber = getTotalPageNumber();
        return pageNumber;
    }

    public void setPageNumber(int pageNumber) {
        this.pageNumber = pageNumber;
    }

    public int getPageSize() {
        return pageSize;
    }

    public void setPageSize(int pageSize) {
        this.pageSize = pageSize;
    }

    public int getTotalPageNumber() {
        return totalCount%pageSize>0 ? totalCount/pageSize + 1 : totalCount/pageSize;
    }

    public void setTotalPageNumber(int totalPageNumber) {
        this.totalPageNumber = totalPageNumber;
    }

    public int getTotalCount() {
        return totalCount;
    }

    public void setTotalCount(int totalCount) {
        this.totalCount = totalCount;
    }

    public int getFrom() {
        if(pageNumber <=0)
            from = 0;
        else if(pageNumber > getTotalPageNumber())
            from = getTotalPageNumber() * pageSize;
        else
            from = pageNumber * pageSize;
        return from;
    }

    public void setFrom(int from) {
        this.from = from;
    }

    public List<T> getResult() {
        return result;
    }

    public void setResult(List<T> result) {
        this.result = result;
    }

    public Iterator<T> iterator() {
        return (Iterator<T>) (result == null ? Collections.emptyList().iterator() : result.iterator());
    }
}

3、定义BaseModel类

package com.xxx.project.core.framework.base;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.google.gson.JsonNull;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.lang.reflect.Field;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Collection;

/**
 * base:BaseModel
 *
 * @author 年爸
 * @QQ     526704425
 * @version 1.0
 * @date    2019-03-05
 */
public class BaseModel implements Serializable, Cloneable {
    /**
     * serialVersionUID
     */
    private static final long serialVersionUID = -1915753774576617010L;

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

    private SimpleDateFormat dateFormat = new SimpleDateFormat(BaseConstants.FORMAT_TIMESTAMP);

    /**
     * 重写toString方法,便于Bean对象的日志存放
     */
    public String toString(){
        return JSON.toJSONString(this, new SerializerFeature[]{SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullListAsEmpty,
                SerializerFeature.WriteNullStringAsEmpty, SerializerFeature.WriteNullNumberAsZero, SerializerFeature.WriteNullBooleanAsFalse,
                SerializerFeature.UseISO8601DateFormat });
    }

    /**
     * 对象拷贝(浅拷贝)
     * @return
     */
    public BaseModel clone() {
        return clone(false);
    }

    /**
     * 对象拷贝
     *
     * @param flag 拷贝模式  <b>true</b>:深拷贝 <b>false</b>:浅拷贝
     * @return
     */
    public BaseModel clone(boolean flag) {
        if(flag){
            // 深拷贝:采用对象序列化/反序列化的机制,进行对象的深度copy
            try {
                // 序列化
                ByteArrayOutputStream bout = new ByteArrayOutputStream();
                ObjectOutputStream out = new ObjectOutputStream(bout);
                out.writeObject(this);
                out.close();
                // 反序列化
                ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
                ObjectInputStream in = new ObjectInputStream(bin);
                Object ret = in.readObject();
                in.close();
                return (BaseModel) ret;
            } catch (Exception e) {
                return null;
            }
        }else{
            // 浅拷贝:Object的clone只是对象的影子copy,除了基础数据和String类型copy的是值,其他复杂类型还是copy的应用
            BaseModel o = null;
            try {
                o = (BaseModel)super.clone();
            } catch(CloneNotSupportedException e) {
                logger.error("BaseModel clone failed", e);
            }
            return o;
        }
    }
}

全部评论: 0

    我有话说: