实现自己的SpringBoot starter

在学习Spring Boot的过程中,接触最多的就是starter。可以认为starter是一种服务——使得使用某个功能的开发者不需要关注各种依赖库的处理,不需要具体的配置信息,由Spring Boot自动通过classpath路径下的类发现需要的Bean,并织入bean。

 

本篇将通过一个简单的例子来演示如何编写自己的starter。

Starter要实现的功能,很简单,提供一个Service,包含一个能够将字符串加上前后缀的方法String wrap(String word)。而具体的前缀和后缀是通过读取SpringBoot配置文件而获取的。

这里说下artifactId的命名问题,Spring 官方 Starter通常命名为 spring-boot-starter-{name} 如 spring-boot-starter-web。Spring官方建议非官方Starter命名应遵循 {name}-spring-boot-starter 的格式。

添加必须的maven依赖:

<!-- @ConfigurationProperties annotation processing (metadata for IDEs)
                 生成spring-configuration-metadata.json类,需要引入此类-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-autoconfigure</artifactId>
        </dependency>

注意其中 spring-boot-configuration-processor 的作用是编译时生成 spring-configuration-metadata.json ,此文件主要给IDE使用,用于提示使用。

本例讲解的是封装一个自定义的elasticsearch的start,因此还有添加必须的业务jar,完整的pom依赖如下:

<?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>com.ganinfo</groupId>
    <artifactId>elastic-spring-boot-starter</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
        <boot.processor.version>1.4.3.RELEASE</boot.processor.version>
        <boot.version>2.0.4.RELEASE</boot.version>
        <elasticsearch.version>5.6.1</elasticsearch.version>
        <google.gson.version>2.8.5</google.gson.version>
        <lombok.version>1.16.20</lombok.version>
    </properties>

    <dependencies>
        <dependency><!-- 以下两个依赖是自动配置的依赖 -->
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-autoconfigure</artifactId>
            <version>${boot.processor.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <version>${boot.processor.version}</version>
            <optional>true</optional>
        </dependency>

        <!--X-Pack 安全插件-->
        <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>x-pack-transport</artifactId>
            <version>${elasticsearch.version}</version>
        </dependency>

        <!--boot web-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <version>${boot.version}</version>
            <optional>true</optional>
        </dependency>

        <!-- gson -->
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>${google.gson.version}</version>
            <optional>true</optional>
        </dependency>

        <!-- lombok -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>${lombok.version}</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>1.5.10.RELEASE</version>
                <configuration>
                    <skip>true</skip>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

属性类:

package com.ganinfo.elastic.config;

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

/**
 * @package:com.ganinfo.elastic
 * @className:ElasticProperties
 * @description:
 * @author:Shuyu.Wang
 * @date:2018-12-09 22:06
 * @version:V1.0
 **/

@ConfigurationProperties(prefix="ganinfo.elastic")
@Data
public class ElasticProperties {
    /**
     * @Field: 服务器地址
     */
    private String host;
    /**
     * @Field:端口
     */
    private int port;
    /**
     * @Field:节点名
     */
    private String clusterName;
}

本例提供两个service类,分别是连接池的ClientHelper和提供接口服务的ESService;

package com.ganinfo.elastic;

import com.ganinfo.elastic.config.ElasticProperties;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import com.ganinfo.elastic.constant.ESConstant;
import lombok.extern.slf4j.Slf4j;
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.elasticsearch.transport.client.PreBuiltTransportClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @package:com.ganinfo.elastic
 * @className:ClientHelper
 * @description:
 * @author:Shuyu.Wang
 * @date:2018-12-09 22:19
 * @version:V1.0
 **/
@Slf4j
public class ClientHelper {

    private ElasticProperties elasticProperties;

    public ClientHelper() {
    }

    public ClientHelper(ElasticProperties elasticProperties) {
        super();
        this.elasticProperties = elasticProperties;
    }

    private Settings setting;

    private ConcurrentHashMap<String, TransportClient> clientMap = new ConcurrentHashMap<String, TransportClient>();

    private Map<String, Integer> ips = new HashMap<String, Integer>();

    public static final ClientHelper getInstance() {
        return ClientHolder.INSTANCE;
    }

    private static class ClientHolder {
        private static final ClientHelper INSTANCE = new ClientHelper();
    }

    /**
     * @author:shuyu.wang
     * @description:初始化默认的client
     * @date: 2018/12/3 22:20
     * @param: null
     * @return: null
     */
    private void init() {
        log.info("host:" + elasticProperties.getHost());
        log.info("clusterName:" + elasticProperties.getClusterName());
        if (elasticProperties.getHost().contains(",")) {
            String[] split = elasticProperties.getHost().split(",");
            for (String ip : split) {
                ips.put(ip, elasticProperties.getPort());
            }
        } else {
            ips.put(elasticProperties.getHost(), elasticProperties.getPort());
        }
        setting = Settings.builder().put(ESConstant.CLUSTER_NAME_STRING, elasticProperties.getClusterName()).put(ESConstant.CLIENT_TRANSPORT_SNIFF_STRING, true).build();
        addClient(setting, ips);
    }

    /**
     * @author:shuyu.wang
     * @description:获得所有的地址端口
     * @date: 2018/12/3 22:20
     * @param: ips
     * @return: null
     */
    private List<InetSocketTransportAddress> getAllAddress(Map<String, Integer> ips) {
        List<InetSocketTransportAddress> addressList = new ArrayList<InetSocketTransportAddress>();
        for (String ip : ips.keySet()) {
            try {
                addressList.add(new InetSocketTransportAddress(InetAddress.getByName(ip), Integer.valueOf(ips.get(ip).toString())));
            } catch (UnknownHostException e) {
                e.printStackTrace();
            }
        }
        return addressList;
    }

    /**
     * @author:shuyu.wang
     * @description:获得client连接
     * @date: 2018/12/3 22:20
     * @param: null
     * @return: Client
     */
    public Client getClient() {
        if ((clientMap != null && !clientMap.isEmpty()) || (ips != null && !ips.isEmpty())) {
            init();
        }
        return getClient(elasticProperties.getClusterName());
    }

    /**
     * @author:shuyu.wang
     * @description:获得client连接
     * @date: 2018/12/3 22:20
     * @param: clusterName
     * @return: Client
     */
    public Client getClient(String clusterName) {
        if (clientMap == null || clientMap.isEmpty()) {
            init();
        }
        return clientMap.get(clusterName);
    }

    /**
     * @author:shuyu.wang
     * @description:建立client连接
     * @date: 2018/12/3 22:20
     * @param: clusterName
     * @return: Client
     */
    private void addClient(Settings setting, Map<String, Integer> ips) {
        TransportClient client = null;
        for (String ip : ips.keySet()) {
            try {
                client = new PreBuiltTransportClient(setting).addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(ip), Integer.valueOf(ips.get(ip).toString())));
            } catch (UnknownHostException e) {
                e.printStackTrace();
            }
        }
        if (client != null) {
            clientMap.put(setting.get(ESConstant.CLUSTER_NAME_STRING), client);
        }

    }
}
/**
 * @package:com.ganinfo.elasticsearch
 * @className:ESQueryParams
 * @description:ESService
 * @author:Shuyu.Wang
 * @date:2018-12-03 22:13
 * @version:V1.0
 * @NOTICE:本内容仅限于新疆感知科技有限公司内部传阅,禁止外泄以及用于其他的商业目
 * @ Copyright © 2017-ganinfo. All rights reserved.
 **/
public interface ESService {

    /**
     * @param index 索引
     * @param type  类型
     * @param obj   插入的对象
     * @author:shuyu.wang
     * @description:新增接口
     * @date: 2018/3/29 10:20
     * @return: Boolean
     */
    Boolean add(String index, String type, Object obj);

    /**
     * @param index           索引
     * @param type            类型
     * @param id
     * @param xContentBuilder 更新内容
     * @author:shuyu.wang
     * @description:更新接口
     * @date: 2018/4/9 12:05
     * @return: Boolean
     */
    Boolean update(String index, String type, String id, XContentBuilder xContentBuilder);

    /**
     * @param index        索引
     * @param type         类型
     * @param queryBuilder 拼接的查询条件
     * @param sort         排序字段,默认降序
     * @param from         起始记录位置
     * @param size         返回条数
     * @author:shuyu.wang
     * @description:查询接口
     * @date: 2018/3/29 10:33
     * @return: ESReturn<List<Map<String,Object>>>
     */
    ESReturn<List<Map<String, Object>>> query(String index, String type, QueryBuilder queryBuilder, String sort, Integer from, Integer size);

    /**
     * @param esQueryParams
     * @author:shuyu.wang
     * @description:es查询封装
     * @date: 2018/5/22 18:22
     * @return: ESReturn<List<Map<String,Object>>>
     */
    ESReturn<List<Map<String, Object>>> queryES(ESQueryParams esQueryParams);


    /**
     * @param index   索引
     * @param type    类型
     * @param id
     * @param jsonDoc json串数据
     * @author:shuyu.wang
     * @description:es查询封装
     * @date: 2018/5/22 18:22
     * @return: Boolean
     */
    Boolean updateES(String index, String type, String id, String jsonDoc);

}

 

package com.ganinfo.elastic;

import com.ganinfo.elastic.config.ElasticProperties;
import com.ganinfo.elastic.service.ESService;
import com.ganinfo.elastic.service.impl.ESServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;

/**
 * @package:com.ganinfo.elastic
 * @className:
 * @description:
 * @author:Shuyu.Wang
 * @date:2018-12-09 22:34
 * @version:V1.0
 **/
@Configuration // 配置注解
@EnableConfigurationProperties(ElasticProperties.class) // 开启指定类的配置
@ConditionalOnClass(ClientHelper.class)// 当PersonService这个类在类路径中时,且当前容器中没有这个Bean的情况下,开始自动配置
@ConditionalOnProperty(prefix = "ganinfo.elastic", value = "enabled", matchIfMissing = true)// 指定的属性是否有指定的值
public class ElasticAutoConfiguration {
    @Autowired
    private ElasticProperties elasticProperties;

    @Bean("clientHelper")
    @ConditionalOnMissingBean(ClientHelper.class)// 当容器中没有指定Bean的情况下,自动配置PersonService类
    public ClientHelper getClientHelper() {
        ClientHelper cientHelper = new ClientHelper(elasticProperties);
        return cientHelper;
    }


    @Bean
    @ConditionalOnMissingBean(ESService.class)// 当容器中没有指定Bean的情况下,自动配置PersonService类
    public ESService getESService(@Qualifier("clientHelper") ClientHelper clientHelper) {
        ESServiceImpl esService = new ESServiceImpl(clientHelper);
        return esService;
    }
}

其他辅助类:

package com.ganinfo.elastic.service.impl;


import com.ganinfo.elastic.ClientHelper;
import com.ganinfo.elastic.constant.ESConstant;
import com.ganinfo.elastic.po.ESQueryParams;
import com.ganinfo.elastic.po.ESReturn;
import com.ganinfo.elastic.po.RangeEntity;
import com.ganinfo.elastic.service.ESService;
import com.ganinfo.elastic.util.CommonUtil;
import com.google.gson.JsonObject;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkRequestBuilder;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.*;
import org.elasticsearch.rest.RestStatus;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.stereotype.Service;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;

/**
 * @package:com.ganinfo.elasticsearch
 * @className:ESServiceImpl
 * @description:ES实现服务层
 * @author:Shuyu.Wang
 * @date:2018-12-03 22:13
 * @version:V1.0
 **/
@Slf4j
public class ESServiceImpl implements ESService {

    private ClientHelper clientHelper;


    public ESServiceImpl(ClientHelper clientHelper) {
        this.clientHelper=clientHelper;
    }


    @Override
    public Boolean add(String index, String type, Object obj) {
        JsonObject jsonObject = objToJson(obj);
        Client client = clientHelper.getClient();
        try {
            IndexResponse response = client.prepareIndex(index, type).setSource(jsonObject.toString(), XContentType.JSON).get();
            RestStatus status = response.status();
            int status1 = status.getStatus();
            log.info(">>>>>ES新增执行结果" + status1);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public Boolean update(String index, String type, String id, XContentBuilder xContentBuilder) {
        UpdateRequest updateRequest = new UpdateRequest();
        updateRequest.index(index);
        updateRequest.type(type);
        updateRequest.id(id);
        updateRequest.doc(xContentBuilder);
        Client client = clientHelper.getClient();
        try {
            UpdateResponse updateResponse = client.update(updateRequest).get();
            int status = updateResponse.status().getStatus();
            log.info(">>>>>ES更新执行结果:" + status);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public ESReturn<List<Map<String, Object>>> query(String index, String type, QueryBuilder queryBuilder, String sort, Integer from, Integer size) {
        ESReturn<List<Map<String, Object>>> esReturn = new ESReturn<List<Map<String, Object>>>();
        Client client = clientHelper.getClient();
        SearchRequestBuilder srb = client.prepareSearch(index).setTypes(type);
        SearchResponse sr = srb.setQuery(queryBuilder).setFrom(from).setSize(size).addSort(SortBuilders.fieldSort(sort).unmappedType("integer").order(SortOrder.DESC)).execute().actionGet(); // 分页排序所有
        long totalHits = sr.getHits().totalHits();
        esReturn.setTotal(totalHits);
        SearchHits hits = sr.getHits();
        List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();
        for (SearchHit hit : hits) {
            Map<String, Object> map = (Map<String, Object>) hit.getSource();
            result.add(map);
        }
//        log.info("返回结果:" + totalHits + "条数据");
        esReturn.setData(result);
        return esReturn;
    }

    public JsonObject objToJson(Object obj) {
        Field[] fields = obj.getClass().getDeclaredFields();
        JsonObject jsonObject = new JsonObject();
        for (int i = 0, len = fields.length; i < len; i++) {
            // 对于每个属性,获取属性名
            String varName = fields[i].getName();
            try {
                // 获取原来的访问控制权限
                boolean accessFlag = fields[i].isAccessible();
                // 修改访问控制权限
                fields[i].setAccessible(true);
                // 获取在对象f中属性fields[i]对应的对象中的变量
                Object o;
                try {
                    o = fields[i].get(obj);
                    if (o != null) {
                        jsonObject.addProperty(varName, o.toString());
                    }
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
                // 恢复访问控制权限
                fields[i].setAccessible(accessFlag);
            } catch (IllegalArgumentException ex) {
                ex.printStackTrace();
            }
        }
        return jsonObject;
    }

    @Override
    public ESReturn<List<Map<String, Object>>> queryES(ESQueryParams esQueryParams) {
        ESReturn<List<Map<String, Object>>> esReturn = new ESReturn<List<Map<String, Object>>>();
        if (!CommonUtil.isNotNullEmpty(esQueryParams.getIndex())) {
            log.error(ESConstant.INDEX_NULL_STRING);
            return esReturn;
        }
        if (!CommonUtil.isNotNullEmpty(esQueryParams.getType())) {
            log.error(ESConstant.TYPE_NULL_STRING);
            return esReturn;
        }
        if (!CommonUtil.isNotNullEmpty(esQueryParams.getSort())) {
            log.error(ESConstant.SORT_NULL_STRING);
            return esReturn;
        }
        if (esQueryParams.getFrom() == null) {
            esQueryParams.setFrom(0);
        }
        if (esQueryParams.getSize() == null) {
            esQueryParams.setSize(10);
        }
        BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();
        //完全不匹配查询
        if (CommonUtil.isNotMapNull(esQueryParams.getNoTermsList())) {
            for (String key : esQueryParams.getNoTermsList().keySet()) {
                TermsQueryBuilder notTermsQueryBuilder = QueryBuilders.termsQuery(key, esQueryParams.getNoTermsList().get(key));
                queryBuilder.mustNot(notTermsQueryBuilder);
            }
        }
        //完全匹配查询
        if (CommonUtil.isNotMapNull(esQueryParams.getTerms())) {
            for (String key : esQueryParams.getTerms().keySet()) {
                TermsQueryBuilder termsQueryBuilder = QueryBuilders.termsQuery(key, esQueryParams.getTerms().get(key));
                queryBuilder.must(termsQueryBuilder);
            }
        }
        //完全匹配查询
        if (CommonUtil.isNotMapNull(esQueryParams.getTermsList())) {
            for (String key : esQueryParams.getTermsList().keySet()) {
                TermsQueryBuilder termsQueryBuilder = QueryBuilders.termsQuery(key, esQueryParams.getTermsList().get(key));
                queryBuilder.must(termsQueryBuilder);
            }
        }
        //完全模糊查询
        if (CommonUtil.isNotMapNull(esQueryParams.getAllWildcards())) {
            for (String key : esQueryParams.getAllWildcards().keySet()) {
                WildcardQueryBuilder wildcardQueryBuilder = QueryBuilders.wildcardQuery(key, "*" + esQueryParams.getAllWildcards().get(key) + "*");
                queryBuilder.must(wildcardQueryBuilder);
            }
        }

        //右模糊查询
        if (CommonUtil.isNotMapNull(esQueryParams.getRightWildcards())) {
            for (String key : esQueryParams.getRightWildcards().keySet()) {
                WildcardQueryBuilder wildcardQueryBuilder = QueryBuilders.wildcardQuery(key, esQueryParams.getRightWildcards().get(key) + "*");
                queryBuilder.must(wildcardQueryBuilder);
            }
        }
        //范围查询
        if (CommonUtil.isNotMapNull(esQueryParams.getRanges())) {
            for (String key : esQueryParams.getRanges().keySet()) {
                RangeEntity rangeEntity = (RangeEntity) esQueryParams.getRanges().get(key);
                if (CommonUtil.isNotNullEmpty(rangeEntity.getFrom()) && CommonUtil.isNotNullEmpty(rangeEntity.getTo())) {
                    RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery(key).from(rangeEntity.getFrom(), true).to(rangeEntity.getTo(), true);// 包含上届
                    queryBuilder.must(rangeQueryBuilder);
                }

                if (CommonUtil.isNotNullEmpty(rangeEntity.getFrom()) && !CommonUtil.isNotNullEmpty(rangeEntity.getTo())) {
                    RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery(key).from(rangeEntity.getFrom(), true);// 包含上届
                    queryBuilder.must(rangeQueryBuilder);
                }
            }
        }
        //判断字段非空
        if (CommonUtil.isNotListNull(esQueryParams.getExistsFiles())) {
            for (String name : esQueryParams.getExistsFiles()) {
                queryBuilder.must(QueryBuilders.existsQuery(name));
            }
        }
//        log.info("ES查询条件>>>" + GsonUtil.GsonString(queryBuilder));
        Client client = clientHelper.getClient();
        SearchRequestBuilder srb = client.prepareSearch(esQueryParams.getIndex()).setTypes(esQueryParams.getType());
        SearchResponse sr = srb.setQuery(queryBuilder).setFrom(esQueryParams.getFrom()).setSize(esQueryParams.getSize()).addSort(SortBuilders.fieldSort(esQueryParams.getSort()).unmappedType("integer").order(SortOrder.DESC)).execute().actionGet(); // 分页排序所有
        long totalHits = sr.getHits().totalHits();
        esReturn.setTotal(totalHits);
        SearchHits hits = sr.getHits();
        List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();
        for (SearchHit hit : hits) {
            Map<String, Object> map = (Map<String, Object>) hit.getSource();
            map.put(ESConstant.ES_ID_STRING, hit.getId());
            result.add(map);
        }
//        log.info("ES查询结果:" +esReturn.getTotal()+"条数据");
        esReturn.setData(result);
        return esReturn;
    }

    /**
     * @param index
     * @param type
     * @param jsonDoc json串数据  @author:shuyu.wang
     * @description:es查询封装
     * @date: 2018/5/22 18:22
     */
    @Override
    public Boolean updateES(String index, String type, String id, String jsonDoc) {
        Client client = clientHelper.getClient();
        BulkRequestBuilder prepareBulk = client.prepareBulk();
        UpdateResponse updateResponse = client.prepareUpdate(index, type, id).setDoc(jsonDoc, XContentType.JSON).get();
        RestStatus status = updateResponse.status();
        if (status.name().equals(ESConstant.OK_STRING)) {
//            log.info("處理狀態—————————" + status.name());
            return true;
        }
        return false;
    }
}

public class ESConstant {

    public static final String CLUSTER_NAME_STRING="cluster.name";

    public static final String CLIENT_TRANSPORT_SNIFF_STRING="client.transport.sniff";

    public static final String INDEX_NULL_STRING="索引不能为空!";

    public static final String TYPE_NULL_STRING="类型不能为空!";

    public static final String SORT_NULL_STRING="排序字段不能为空!";

    public static final String ES_ID_STRING="es_id";

    public static final String OK_STRING="OK";
}
@Data
public class ESReturn<T> {

    /**
     * @Field: Result data
     */
    private T data;
    /**
     * @Field:Total item size
     */
    private long total;

}
@Data
public class ESQueryParams {
    /**
    * @Field:索引
    */
    private String index;
    /**
     * @Field:类型
     */
    private String type;
    /**
     * @Field:完全匹配字段
     */
    private Map<String,String> terms;
    /**
     * @Field:完全不匹配字段
     */
    private Map<String,List<String>> noTermsList;
    /**
     * @Field:右模糊查询
     */
    private Map<String,String> rightWildcards;
    /**
     * @Field:完全模糊查询
     */
    private Map<String,String> allWildcards;
    /**
     * @Field:范围查询
     */
    private Map<String,RangeEntity> ranges;
    /**
     * @Field:一次匹配多个值
     */
    private Map<String,List<String>> termsList;
    /**
     * @Field:判断字段非空
     */
    private List<String> existsFiles=new ArrayList<String>();

    /**
     * @Field:排序字段
     */
    private String sort;
    /**
     * @Field:起始记录条数
     */
    private Integer from;
    /**
     * @Field:返回条数
     */
    private Integer size;

    public ESQueryParams() {
    }

    public ESQueryParams(String index, String type, String sort) {
        this.index = index;
        this.type = type;
        this.sort = sort;
    }

}
@Data
public class RangeEntity {
    private String from;
    private String to;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值