ElasticSearch(八):springboot集成ElasticSearch集群并使用

摘要:
如下:当我排除org.elasticsearch.client.transport的elasticsearch的依赖之后,重新添加elasticsearch6.3.2的依赖之后,就显示的是同样的elasticsearch6.3.2。这就需要导入jar:org.elasticsearch.plugin----transport-netty4-client的jar,,这时候transport-netty4-client的版本也是6.3.2了。

1. 集群的搭建

见:ElasticSearch(七)

2. springboot配置集群

2.1 创建springboot项目,使用idea创建,不过多介绍(创建项目时候建议不要勾选elasticsearch,springboot目前自带的elasticsearch版本为5.6.10,如果你版本高于这个版本,还是自己手动导入。)

2.2 导入依赖

   <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>6.3.2</elasticSearch.version>
   </properties>
<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> <exclusions> <exclusion> <groupId>org.elasticsearch</groupId> <artifactId>elasticsearch</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.elasticsearch.client</groupId> <artifactId>elasticsearch-rest-high-level-client</artifactId> <version>${elasticSearch.version}</version> </dependency> <dependency> <groupId>org.elasticsearch.plugin</groupId> <artifactId>transport-netty4-client</artifactId> <version>${elasticSearch.version}</version> </dependency>

对于依赖需要说明的几点:

2.2.1.org.elasticsearch.client--transport 依赖添加之后,会依赖一系列的插件,客户端等,虽然在springboot2.0中依旧依赖 org.elasticsearch-elasticsearch-6.3.2,但是在依赖列表中,其添加的依赖依然是elasticSearch5.6.10的依赖,所以必须排除这个依赖,手动添加org.elasticsearch-elasticsearch6.3.2的依赖,目前只有这种解决方法,否则导致版本不一致冲突。如下:

ElasticSearch(八):springboot集成ElasticSearch集群并使用第1张ElasticSearch(八):springboot集成ElasticSearch集群并使用第2张

当我排除 org.elasticsearch.client.transport的elasticsearch的依赖之后,重新添加elasticsearch 6.3.2的依赖之后,就显示的是同样的elasticsearch6.3.2。显示如下:

ElasticSearch(八):springboot集成ElasticSearch集群并使用第3张

2.2.2. 这时候如果你再springboot中配置了TransportClient的方法Bean,则启动项目,会报错:

ElasticSearch(八):springboot集成ElasticSearch集群并使用第4张

这是因为:transport-netty4-client的版本是5.6.0,而我们使用的所有的elasticsearch版本都是6.3.2,导致jar包冲突,所以,我们必须将transport-netty4-client的版本更新到6.3.2。

这就需要导入jar:org.elasticsearch.plugin----transport-netty4-client 的jar,(具体依赖将上面),这时候transport-netty4-client的版本也是6.3.2了。

2.2.3. 到这里已经可以使用elasticsearch的集群了,不过我们又导入了一个elasticsearch-rest-high-level-client的jar,目的是:为了使用某些特殊的api。参见:https://www.cnblogs.com/ginb/p/8716485.html

3. 启动项目,连接elasticSearch集群

3.1 配置集群信息

importorg.elasticsearch.client.transport.TransportClient;
importorg.elasticsearch.common.settings.Settings;
importorg.elasticsearch.common.transport.TransportAddress;
importorg.elasticsearch.transport.client.PreBuiltTransportClient;
importorg.slf4j.Logger;
importorg.slf4j.LoggerFactory;
importorg.springframework.beans.factory.annotation.Value;
importorg.springframework.context.annotation.Bean;
importorg.springframework.context.annotation.Configuration;
importjava.net.InetAddress;
/**
 * @Auther: cc
 * @Date: 
 * @Description:
 */
@Configuration
public classESConfig {
    private Logger logger  = LoggerFactory.getLogger(this.getClass());
    @Value("${elasticsearch.firstIp}")
    privateString firstIp;
    @Value("${elasticsearch.secondIp}")
    privateString secondIp;
    @Value("${elasticsearch.thirdIp}")
    privateString thirdIp;
    @Value("${elasticsearch.firstPort}")
    privateString firstPort;
    @Value("${elasticsearch.secondPort}")
    privateString secondPort;
    @Value("${elasticsearch.thirdPort}")
    privateString thirdPort;
    @Value("${elasticsearch.clusterName}")
    privateString clusterName;
    @Bean
    publicTransportClient getTransportClient() {
        logger.info("ElasticSearch初始化开始。。");
        logger.info("要连接的节点1的ip是{},端口是{},集群名为{}", firstIp , firstPort , clusterName);
        logger.info("要连接的节点2的ip是{},端口是{},集群名为{}", secondIp , secondPort , clusterName);
        logger.info("要连接的节点3的ip是{},端口是{},集群名为{}", thirdIp , thirdPort , clusterName);
        TransportClient transportClient = null;
        try{
            Settings settings =Settings.builder()
                    .put("cluster.name",clusterName)    //集群名称
                    .put("client.transport.sniff",true)  //目的是为了可以找到集群,嗅探机制开启
                    .build();
            transportClient = newPreBuiltTransportClient(settings);
            TransportAddress firstAddress = newTransportAddress(InetAddress.getByName(firstIp),Integer.parseInt(firstPort));
            TransportAddress secondAddress = newTransportAddress(InetAddress.getByName(secondIp),Integer.parseInt(secondPort));
            TransportAddress thirdAddress = newTransportAddress(InetAddress.getByName(thirdIp),Integer.parseInt(thirdPort));
            transportClient.addTransportAddress(firstAddress);
            transportClient.addTransportAddress(secondAddress);
            transportClient.addTransportAddress(thirdAddress);
            logger.info("ElasticSearch初始化完成。。");
        }catch(Exception e){
            e.printStackTrace();
            logger.error("ElasticSearch初始化失败:" +e.getMessage(),e);
        }
        returntransportClient;
    }
}

对于上面代码解释:

3.1.1 首先需要再配置文件中配置服务器集群的所有ip,端口,然后通过@value导入到config类中。

3.2.2 类上必须加@Configuration注解,方法上必须加@Bean注解。

3.2 启动项目,连接集群

启动项目,如果不报错就可行了。

4. 使用springboot操作索引

4.1 创建索引

主要使用方法:

CreateIndexRequest createIndexRequest =Requests.createIndexRequest(index).settings(settings).mapping(type,mapping);  //指定setting,mapping创建索引,如果非结构化索引的话,不指定mapping
CreateIndexResponse response =transportClient.admin().indices().create(createIndexRequest).get();
logger.info("建立索引映射成功:" + response.isAcknowledged());

4.2 删除索引

DeleteIndexRequest deleteIndexRequest =Requests.deleteIndexRequest(index);                  //创建删除索引的请求
DeleteIndexResponse response =transportClient.admin().indices().delete(deleteIndexRequest).get();    //删除索引的响应
logger.info("删除索引结果:{}",response.isAcknowledged());

完整代码如下

ElasticSearch(八):springboot集成ElasticSearch集群并使用第5张ElasticSearch(八):springboot集成ElasticSearch集群并使用第6张
importcom.cc.es.domain.base.ResultBean;
importio.swagger.annotations.Api;
importio.swagger.annotations.ApiImplicitParam;
importio.swagger.annotations.ApiImplicitParams;
importio.swagger.annotations.ApiOperation;
importorg.apache.commons.lang3.StringUtils;
importorg.elasticsearch.action.admin.indices.create.CreateIndexRequest;
importorg.elasticsearch.action.admin.indices.create.CreateIndexResponse;
importorg.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
importorg.elasticsearch.action.admin.indices.delete.DeleteIndexResponse;
importorg.elasticsearch.client.Requests;
importorg.elasticsearch.client.transport.TransportClient;
importorg.elasticsearch.common.xcontent.XContentBuilder;
importorg.elasticsearch.common.xcontent.XContentFactory;
importorg.slf4j.Logger;
importorg.slf4j.LoggerFactory;
importorg.springframework.web.bind.annotation.RequestMapping;
importorg.springframework.web.bind.annotation.RequestMethod;
importorg.springframework.web.bind.annotation.RequestParam;
importorg.springframework.web.bind.annotation.RestController;
importjavax.annotation.Resource;
import java.util.*;
/**
 * @Auther: Administrator
 * @Date: 2018/8/21 07
 * @Description:
 */
@Api(value = "Index", tags = "索引")
@RestController
@RequestMapping("index")
public classIndexController {
    private final String INDEX = "index";
    private final String TYPE = "type";
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    @Resource
    privateTransportClient transportClient;
    @ApiOperation(value = "结构化创建索引")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "index", value = "索引名", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "type", value = "类型", required = true, dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "fields", value = "结构化索引字段名,不定参数,传入的时候参数名为索引字段名,值为对应的数据类型")
    })
    @RequestMapping(value = "/create" , method =RequestMethod.POST)
    public ResultBean createIndex(@RequestParam Map<String,String>param){
        ResultBean resultBean = newResultBean();
        String index = null;
        String type = null;
        List<String> fieldList = new ArrayList<>();
        logger.info("接收的创建索引的参数:" +param);
        Set<Map.Entry<String, String>> set =param.entrySet();
        for (Map.Entry<String, String>entry: set) {
            String key =entry.getKey();
            if(key.trim().equals(INDEX)){
                index =entry.getValue();
            }else if(key.trim().equals(TYPE)){
                type =entry.getValue();
            }else{
                fieldList.add(key);
            }
        }
        if(StringUtils.isBlank(index) ||StringUtils.isBlank(type)){
            resultBean.setSuccess(false);
            resultBean.setMsg("参数错误!");
            returnresultBean;
        }
        try{
            XContentBuilder settings =XContentFactory.jsonBuilder()
                    .startObject()
                        .field("number_of_shards",6)
                        .field("number_of_replicas",1)
                        .startObject("analysis").startObject("analyzer").startObject("ik")
                            .field("tokenizer","ik_max_word")
                        .endObject().endObject().endObject()
                    .endObject();
            XContentBuilder mapping =XContentFactory.jsonBuilder();
            mapping.startObject().field("dynamic","strict").startObject("properties");
            for (int i = 0,j = fieldList.size(); i < j; i++) {
                String field =fieldList.get(i);
                String fieldType =param.get(field);
                mapping.startObject(field).field("type",fieldType);
                if(fieldType.trim().equals("date")){
                    mapping.field("format","yyyy-MM-dd HH:mm:ss || yyyy-MM-dd ");
                }
                mapping.endObject();
            }
            mapping.endObject().endObject();
            CreateIndexRequest createIndexRequest =Requests.createIndexRequest(index).settings(settings).mapping(type,mapping);
            CreateIndexResponse response =transportClient.admin().indices().create(createIndexRequest).get();
            logger.info("建立索引映射成功:" +response.isAcknowledged());
            resultBean.setSuccess(true);
            resultBean.setMsg("创建索引成功!");
        } catch(Exception e) {
            resultBean.setSuccess(false);
            resultBean.setMsg("创建索引失败!");
            logger.error("创建索引失败!要创建的索引为{},文档类型为{},异常为:",index,type,e.getMessage(),e);
        }
        returnresultBean;
    }
    @ApiOperation(value = "删除索引")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "index", value = "索引名", required = true, dataType = "String", paramType = "query"),
    })
    @RequestMapping(value = "/delete" , method =RequestMethod.POST)
    publicResultBean deleteIndex(String index){
        ResultBean resultBean = newResultBean();
        if(StringUtils.isBlank(index)) {
            resultBean.setMsg("参数错误,索引为空");
            resultBean.setSuccess(false);
            returnresultBean;
        }
        try{
            DeleteIndexRequest deleteIndexRequest =Requests.deleteIndexRequest(index);
            DeleteIndexResponse response =transportClient.admin().indices().delete(deleteIndexRequest).get();
            logger.info("删除索引结果:{}",response.isAcknowledged());
            resultBean.setSuccess(response.isAcknowledged());
            resultBean.setMsg(response.isAcknowledged() ? "删除索引成功!" : "删除索引失败!");
        } catch(Exception e) {
            resultBean.setSuccess(false);
            resultBean.setMsg("创建索引失败!");
            logger.error("删除索引失败!要删除的索引为{},异常为:",index,e.getMessage(),e);
        }
        returnresultBean;
    }
}
View Code

到目前为止,springboot的索引已经完成。这里都是使用的原生的一些api,以后可能还会使用一些别的方法完成。

免责声明:文章转载自《ElasticSearch(八):springboot集成ElasticSearch集群并使用》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇like 模糊查询GDB如何调试没有符号表(未加-g选项的编译)的程序下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

Java 字符串常用操作(String类)

字符串查找 String提供了两种查找字符串的方法,即indexOf与lastIndexOf方法。 1、indexOf(String s) 该方法用于返回参数字符串s在指定字符串中首次出现的索引位置,当调用字符串的indexOf()方法时,会从当前字符串的开始位置搜索s的位置;如果没有检索到字符串s,该方法返回-1 1 String str ="We a...

Java中Map用法详解

原文地址http://blog.csdn.net/guomutian911/article/details/45771621 原文地址http://blog.csdn.net/sunny243788557/article/details/52806724 Map以按键/数值对的形式存储数据,这里要特别说明(Map.Entry,是Map的内部类,它用来描述M...

C#winform解析marc显示在datagridview中以及marc卡片显示

结果显示:marc显示: 卡片显示: 程序一个类: public class MARC { #region 界面上要显示的元素 public string ztm = "";//正题名 public string ftm = "";//副题名 public string fcm = "";//分册(辑)名 public string fch = "";...

Java大文件分片上传/多线程上传

这里只写后端的代码,基本的思想就是,前端将文件分片,然后每次访问上传接口的时候,向后端传入参数:当前为第几块文件,和分片总数 下面直接贴代码吧,一些难懂的我大部分都加上注释了: 上传文件实体类: 看得出来,实体类中已经有很多我们需要的功能了,还有实用的属性。如MD5秒传的信息。 public class FileInf {      public File...

建行互联网银企被扫支付

背景 最近在对接建行的支付,我们做的是被扫支付,就是B扫C,一开始对方发了一个压缩包给我,看起来挺齐全的,文档、demo啥的都有,以为很简单,跟微信支付宝类似,调一下接口,验证一下就OK了。然而,事实证明我还是太年轻了。而且网络上你能够搜到的基本上都用不了,所以记一下博客,或许可以帮助其他人。 先说一下建行支付比较特殊的地方吧 1、官方提供的demo里面,...

ES系列二、Mac 通过docker搭建ELK日志收集系统

一、ELK简介 Elasticsearch:用于存储收集到的日志信息; Logstash:用于监控,过滤,收集日志,SpringBoot应用整合了Logstash以后会把日志发送给Logstash, Logstash再把日志转发给Elasticsearch; Kibana:通过Web端的可视化界面来查看日志。 二、解决docker拉取镜像慢的问题...