springboot+gradle+elasticseach安装整合window(保姆级教程)

本文详细介绍了如何在SpringBoot项目中整合Elasticsearch7.17.5,包括版本对应、本地安装、启动与配置,以及使用Kibana可视化管理和数据操作。教程覆盖了从环境设置到数据插入的完整过程。
摘要由CSDN通过智能技术生成

1、首先要清楚springboot和elasticseach版本对应关系

使用的版本如下:

springboot:2.7.15

gralde:8.2.1

elasticseach:7.17.5

2、elasticseach本地安装

官网地址:https://www.elastic.co/cn/downloads/past-releases

找到适合自己的版本,下载即可(这里默认谷歌下载可能速度有点慢,我们可以把下载地址复制出来到迅雷下载):

3、下载完成之后,解压zip包,如下:

4、在bin目录下,点击elasticsearch.bat就可以启动elasticsearch了。

4.1、启动报错记录1:not all primary shards of [.geoip_databases] index are active

解决:

修改 elasticsearch.yml

# ES启动时会去更新地图的一些数据库,这里直接禁掉即可
ingest.geoip.downloader.enabled: false

4.2、elasticsearch有自带的jdk,且7.*都是jdk11,所以得改成使用自带的jdk

解决:

在bin目录下找到elasticsearch-env.bat做以下修改,把else if 删掉即可,或者像我注释。

启动成功:

5、安装可视化管理工具Kibana(选择与elasticseach版本一致即可)

Kibana是一个针对ElasticSearch的开源分析及可视化平台,用来搜索、查看交互存储在Elasticsearch索引中的数据。使用Kibana 可以通过各种图表进行高级数据分析及展示。Kibana让海量数据更容易理解。它操作简单,基于浏览器的用户界面可以快速创建仪表板( dashboard )实时显示Elasticsearch查询动态。

下载地址:http://​https://www.elastic.co/cn/downloads/past-releases​

5.1、下载解压后修改config/kibana.yml配置文件(其实按照默认的也是指向本地不用修改配置文件也可以)

5.2、\bin\kibana.bat启动,浏览器访问:http://localhost:5601

5.3、修改中文界面:config/kibana.yml下把i18n.locale: "en"改为 i18n.locale: "zh-CN"

5.3.1 切换中文启动闪退问题

解决:前面要多一个空格,不然解析不了,所以闪退!

5.4、然后我们可以打开左侧目录的开发工具控制台,输入命令进行es的数据查询插入删除等操作了。

这里插一句(其实插入数据成功后也可以通过http://127.0.0.1:9200/索引名称/_search查询到存在ES的数据哦)

6、springboot+gradle+elasticseach搭建

6.1、在gradle引入es的依赖

// elasticseach
implementation 'org.elasticsearch.client:elasticsearch-rest-high-level-client:7.17.5'

6.2、编写连接ES的两个配置类
ElasticResource类:

package com.example.ywnbpro.elasticsearch.config;

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

@Data
@Configuration
@ConfigurationProperties(prefix = "elasticsearch")
public class ElasticResource {
    private String host;
    private String port;
    private String username;
    private String password;

}
ElasticsearchConfig类:
package com.example.ywnbpro.elasticsearch.config;

import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @program: ywNbPro
 * @description: Elasticsearch连接
 * @author: 
 * @create: 2023-10-19 10:46
 **/

@Configuration
@EnableConfigurationProperties(ElasticResource.class)
public class ElasticsearchConfig {

    public static final RequestOptions COMMON_OPTIONS;

    @Resource
    private ElasticResource elasticResource;

    static {
        RequestOptions.Builder builder = RequestOptions.DEFAULT.toBuilder();
        COMMON_OPTIONS = builder.build();
    }
    @Bean(name = "restHighLevelClient")
    public RestHighLevelClient restHighLevelClient() {
        List<HttpHost> hostLists = new ArrayList<>();
        hostLists.add(new HttpHost(elasticResource.getHost(), Integer.parseInt(elasticResource.getPort()), "http"));
        final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(elasticResource.getUsername(), elasticResource.getPassword()));
        // 转换成 HttpHost 数组
        HttpHost[] httpHost = hostLists.toArray(new HttpHost[]{});
        // 构建连接对象
        RestClientBuilder builder = RestClient.builder(httpHost);
        // 异步连接延时配置
        builder.setRequestConfigCallback(requestConfigBuilder -> {
            requestConfigBuilder.setConnectTimeout(5000);
            requestConfigBuilder.setSocketTimeout(5000);
            requestConfigBuilder.setConnectionRequestTimeout(5000);
            return requestConfigBuilder;
        });
        // 异步连接数配置
        builder.setHttpClientConfigCallback(httpClientBuilder -> {
            httpClientBuilder.setMaxConnTotal(100);
            httpClientBuilder.setMaxConnPerRoute(100);
            return httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
        });
        return new RestHighLevelClient(builder);
    }
}

6.3、编写查询和批量插入ES数据的类

ElasticsearchClientUtil:
package com.example.ywnbpro.elasticsearch.util;

import com.alibaba.fastjson2.JSON;
import com.example.ywnbpro.nbFiring.domain.NbData;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.xcontent.XContentType;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;

/**
 * @program: ywNbPro
 * @description: ClientUtil客户端
 * @author: 
 * @create: 2023-10-19 15:04
 **/

@Component
public class ElasticsearchClientUtil {

    @Resource(name = "restHighLevelClient")
    private RestHighLevelClient restHighLevelClient;

    /**
     *
     * @param indexName 索引名
     * @param tList 数据
     */
    public BulkResponse bulkAddDocument(String indexName, List<NbData> tList) {
        try {
            BulkRequest bulkRequest = new BulkRequest();
            tList.forEach(doc -> {
                bulkRequest.add(new IndexRequest(indexName)
                        .id(doc.getId().toString())
                        .source(JSON.toJSONString(doc), XContentType.JSON));
            });
            // 批量写入
            return restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public List<Map<String,Object>> search(String searchText) {
        try {
            //1.创建请求语义对象
            SearchRequest searchRequest = new SearchRequest("nbindex");
            // QueryBuilders: 构建查询类型
            searchRequest.source().query(QueryBuilders.matchQuery("name", searchText));
            SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
            SearchHit[] hits = searchResponse.getHits().getHits();
            List<Map<String,Object>> list = new ArrayList<>();
            for (SearchHit documentFields : hits) {
                Map<String, Object> sourceAsMap = documentFields.getSourceAsMap();
                list.add(sourceAsMap);
            }
            System.out.println("查询的list->>>>"+list);
            return list;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

}

6.4、最后就是调用了,可以编写以下测试类:

ElasticSearchBulkController:
package com.example.ywnbpro.nbFiring.controller;

import com.example.ywnbpro.elasticsearch.util.ElasticsearchClientUtil;
import com.example.ywnbpro.nbFiring.domain.NbData;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @program: ywNbPro
 * @description: elasticseach数据操作
 * @author: lyw
 * @create: 2023-10-19 16:17
 **/

@RestController
@RequestMapping("/elasticseach")
public class ElasticSearchBulkController {

    @Resource
    private ElasticsearchClientUtil elasticsearchClientUtil;

    @RequestMapping("/bulk")
    public void bulkData() {
        List<NbData> list = new ArrayList<>();
        NbData nbData;
        StringBuilder nameString = new StringBuilder();
        for (int i = 0; i < 10; i++) {
            nbData = new NbData();
            nameString.append("卧槽牛逼啊,竟然插入数据插入成功了,我只能说一句牛逼!");
            nbData.setId(i);
            nbData.setName(nameString.toString());
            if( i%2 == 0 ) nbData.setSex("男"); else nbData.setSex("女");
            list.add(nbData);
        }
        System.out.println(list.size());
        BulkResponse bulkItemResponses = elasticsearchClientUtil.bulkAddDocument("nbindex",list);
        System.out.println("写入结果:"+bulkItemResponses);
    }

    @GetMapping("/searchAll")
    public List<Map<String,Object>> searchAll(String searchText) throws Exception {
        return  elasticsearchClientUtil.search(searchText);
    }


}

OK,教程结束,喜欢点个关注。

以上只是ES简单操作,更多功能还须深入研究。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值