0


SpringBoot3整合Elasticsearch8.x之全面保姆级教程

整合ES

环境准备

  1. 安装配置EShttps://blog.csdn.net/qq_50864152/article/details/136724528
  2. 安装配置Kibanahttps://blog.csdn.net/qq_50864152/article/details/136727707
  3. 新建项目:新建名为webSpringBoot3项目

elasticsearch-java

公共配置

  1. 介绍:一个开源的高扩展的分布式全文检索引擎,可以近乎实时的存储 和检索数据
  2. 依赖:web模块引入elasticsearch-java依赖---但其版本必须与你下载的ES的版本一致
<!-- 若不存在Spring Data ES的某个版本支持你下的ES版本,则使用  --><!-- ES 官方提供的在JAVA环境使用的依赖 --><dependency><groupId>co.elastic.clients</groupId><artifactId>elasticsearch-java</artifactId><version>8.11.1</version></dependency><!-- 和第一个依赖是一起的,为了解决springboot项目的兼容性问题  --><dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-databind</artifactId></dependency>
  1. 配置:web模块dev目录application-dal添加

使用

open+@Value("${elasticsearch.open}")

的方式不能放到

Nacos

配置中心

# elasticsearch配置elasticsearch:# 自定义属性---设置是否开启ES,false表不开窍ESopen:true# es集群名称,如果下载es设置了集群名称,则使用配置的集群名称clusterName: es
  hosts: 127.0.0.1:9200# es 请求方式scheme: http
  # es 连接超时时间connectTimeOut:1000# es socket 连接超时时间socketTimeOut:30000# es 请求超时时间connectionRequestTimeOut:500# es 最大连接数maxConnectNum:100# es 每个路由的最大连接数maxConnectNumPerRoute:100
  1. 配置:web模块config包下新建ElasticSearchConfig
packagecn.bytewisehub.pai.web.config;importco.elastic.clients.elasticsearch.ElasticsearchClient;importco.elastic.clients.json.jackson.JacksonJsonpMapper;importco.elastic.clients.transport.ElasticsearchTransport;importco.elastic.clients.transport.rest_client.RestClientTransport;importlombok.Data;importlombok.extern.slf4j.Slf4j;importorg.apache.http.HttpHost;importorg.apache.http.auth.AuthScope;importorg.apache.http.auth.UsernamePasswordCredentials;importorg.apache.http.client.CredentialsProvider;importorg.apache.http.impl.client.BasicCredentialsProvider;importorg.elasticsearch.client.RestClient;importorg.elasticsearch.client.RestClientBuilder;importorg.springframework.boot.context.properties.ConfigurationProperties;importorg.springframework.context.annotation.Bean;importorg.springframework.context.annotation.Configuration;@Slf4j@Data@Configuration@ConfigurationProperties(prefix ="elasticsearch")publicclassElasticSearchConfig{// 是否开启ESprivateBooleanopen;// es 集群host ip 地址privateString hosts;// es用户名privateString userName;// es密码privateString password;// es 请求方式privateString scheme;// es集群名称privateString clusterName;// es 连接超时时间privateint connectTimeOut;// es socket 连接超时时间privateint socketTimeOut;// es 请求超时时间privateint connectionRequestTimeOut;// es 最大连接数privateint maxConnectNum;// es 每个路由的最大连接数privateint maxConnectNumPerRoute;// es api keyprivateString apiKey;publicRestClientBuildercreatBaseConfBuilder(String scheme){// 1. 单节点ES Host获取String host = hosts.split(":")[0];String port = hosts.split(":")[1];// The value of the schemes attribute used by noSafeRestClient() is http// but The value of the schemes attribute used by safeRestClient() is httpsHttpHost httpHost =newHttpHost(host,Integer.parseInt(port),scheme);// 2. 创建构建器对象//RestClientBuilder: ES客户端库的构建器接口,用于构建RestClient实例;允许你配置与Elasticsearch集群的连接,设置请求超时,设置身份验证,配置代理等RestClientBuilder builder =RestClient.builder(httpHost);// 连接延时配置
        builder.setRequestConfigCallback(requestConfigBuilder ->{
            requestConfigBuilder.setConnectTimeout(connectTimeOut);
            requestConfigBuilder.setSocketTimeout(socketTimeOut);
            requestConfigBuilder.setConnectionRequestTimeout(connectionRequestTimeOut);return requestConfigBuilder;});// 3. HttpClient 连接数配置
        builder.setHttpClientConfigCallback(httpClientBuilder ->{
            httpClientBuilder.setMaxConnTotal(maxConnectNum);
            httpClientBuilder.setMaxConnPerRoute(maxConnectNumPerRoute);return httpClientBuilder;});return builder;}}
  1. 测试:web模块test目录下新建ElasticSearchTest
@Slf4j@SpringBootTestpublicclassElasticSearchTest{@Value("${elasticsearch.open}")// 是否开启ES,默认开启Stringopen="true";}

直接连接

ES
  1. 设置:ES``````Elasticsearch.ymlxpack.security.enabled属性设置为false
xpack.security.enabled


● 默认

true

:必须使用账号连接

ES

● 若为

false

:必须使用

http://localhost:9200/

访问

ES

服务

+

启动

Kibana

服务会失败

+

不需要使用账号连接,但必须使用

HTTP

连接

  1. 添加:ElasticSearchConfig类添加下列方法
/**
* @function: 创建使用http连接来直接连接ES服务器的客户端
* 如果@Bean没有指定bean的名称,那么这个bean的名称就是方法名
*/@Bean(name ="directConnectionESClient")publicElasticsearchClientdirectConnectionESClient(){RestClientBuilder builder =creatBaseConfBuilder((scheme =="http")?"http":"http");//Create the transport with a Jackson mapperElasticsearchTransport transport =newRestClientTransport(builder.build(),newJacksonJsonpMapper());//And create the API clientElasticsearchClient esClient =newElasticsearchClient(transport);return esClient;};
  1. 添加:ElasticSearchTest类中添加下列代码---索引名必须小写
  2. 运行:设置跳过测试--->手动运行/不跳过--->直接install,但不运行测试
@Resource(name ="directConnectionESClient")ElasticsearchClient directConnectionESClient;@TestpublicvoiddirectConnectionTest()throwsIOException{if(open.equals("true")){//创建索引CreateIndexResponse response = directConnectionESClient.indices().create(c -> c.index("direct_connection_index"));
    log.info(response.toString());}else{
    log.info("es is closed");}}

账号密码连接

ES
  1. 设置:ES``````Elasticsearch.ymlxpack.security.enabled属性使用默认值+``````xpack.security.http.ssl.enabled设置为false

注意:若

xpack.security.enabled

属性为

false

,则

xpack.security.http.ssl.enabled

属性不生效,即相当于设置为

false

;所有以

xpack

开头的属性都不会生效

ES
Elasticsearch.yml

xpack.security.http.ssl.enabled


● 默认

true

:必须使用

https://localhost:9200/

访问

ES

服务

+

启动

Kibana

服务会成功

+

需要使用账号连接

+

必须使用

HTTPS

连接
● 若为

false

:必须使用

http://localhost:9200/

访问

ES

服务

+

启动

Kibana

服务会失败+需要使用账号连接,但必须使用HTTP连接

  1. 配置:dev目录application-dal中添加下列配置
# elasticsearch配置elasticsearch:userName:#自己的账号名password:#自己的密码
  1. 添加:ElasticSearchTest类中添加下列代码---索引名必须小写+不能有空格
  2. 运行:设置跳过测试--->手动运行/不跳过--->直接install,但不运行测试
@Resource(name ="accountConnectionESClient")ElasticsearchClient accountConnectionESClient;@TestpublicvoidaccountConnectionTest()throwsIOException{if(open.equals("true")){//创建索引CreateIndexResponse response = accountConnectionESClient.indices().create(c -> c.index("account_connection_index"));
    log.info(response.toString());}else{
    log.info("es is closed");}}

证书账号连接

ES
  1. 设置:ES``````Elasticsearch.ymlxpack.security.enabledxpack.security.http.ssl.enabled配置项使用默认值

设置为

true

后,

ES

就走

https

,若

scheme

http

,则报

Unrecognized

SSL

message

错误

  1. 配置:将dev目录application-dalelasticsearch.scheme配置项改成https
  2. 证书添加:终端输入keytool -importcert -alias es_https_ca -keystore "D:\computelTool\Java\JDK\JDK21\lib\security\cacerts" -file "D:\computelTool\database\elasticsearch8111\config\certs\http_ca.crt"
keytool -delete -alias es_https_ca -keystore "D:\computelTool\Java\JDK\JDK21\lib\security\cacerts"
---

与上面的命令相反

  1. 拷贝:将ESconfig目录下certs目录下的http_ca.crt文件拷贝到web模块resource目录
  2. 添加:ElasticSearchConfig类添加下列方法
/**
* @function: 创建用于安全连接(证书 + 账号)ES服务器的客户端
* 如果@Bean没有指定bean的名称,那么这个bean的名称就是方法名
*/@Bean(name ="accountAndCertificateConnectionESClient")publicElasticsearchClientaccountAndCertificateConnectionESClient(){RestClientBuilder builder =creatBaseConfBuilder((scheme =="https")?"https":"https");// 1.账号密码的配置//CredentialsProvider: 用于提供 HTTP 身份验证凭据的接口; 允许你配置用户名和密码,以便在与服务器建立连接时进行身份验证CredentialsProvider credentialsProvider =newBasicCredentialsProvider();
    credentialsProvider.setCredentials(AuthScope.ANY,newUsernamePasswordCredentials(userName, password));// 2.设置自签证书,并且还包含了账号密码
    builder.setHttpClientConfigCallback(httpAsyncClientBuilder -> httpAsyncClientBuilder
                                        .setSSLContext(buildSSLContext()).setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE).setDefaultCredentialsProvider(credentialsProvider));RestClientTransport transport =newRestClientTransport(builder.build(),newJacksonJsonpMapper());//And create the API clientElasticsearchClient esClient =newElasticsearchClient(transport);return esClient;}privatestaticSSLContextbuildSSLContext(){// 读取http_ca.crt证书ClassPathResource resource =newClassPathResource("http_ca.crt");SSLContext sslContext =null;try{// 证书工厂CertificateFactory factory =CertificateFactory.getInstance("X.509");Certificate trustedCa;try(InputStream is = resource.getInputStream()){
            trustedCa = factory.generateCertificate(is);}// 密钥库KeyStore trustStore =KeyStore.getInstance("pkcs12");
        trustStore.load(null,"liuxiansheng".toCharArray());
        trustStore.setCertificateEntry("ca", trustedCa);SSLContextBuilder sslContextBuilder =SSLContexts.custom().loadTrustMaterial(trustStore,null);
        sslContext = sslContextBuilder.build();}catch(CertificateException|IOException|KeyStoreException|NoSuchAlgorithmException|KeyManagementException e){
        log.error("ES连接认证失败", e);}return sslContext;}
  1. 测试:ElasticSearchTest类添加
@Resource(name ="accountAndCertificateConnectionESClient")ElasticsearchClient accountAndCertificateConnectionESClient;@TestpublicvoidaccountAndCertificateConnectionTest()throwsIOException{if(open.equals("true")){//创建索引CreateIndexResponse response =  accountAndCertificateConnectionESClient.indices().create(c -> c.index("account_and_certificate_connection_index"));
    log.info(response.toString());System.out.println(response.toString());}else{
    log.info("es is closed");}}

Spring Data ES

公共配置

  1. 依赖:web模块引入该依赖---但其版本必须与你下载的ES的版本一致

版本:点击

https://spring.io/projects/spring-data-elasticsearch#learn

,点击

GA

版本的

Reference Doc

,点击

version

查看

Spring Data ES

ES

版本的支持关系

参考:

https://www.yuque.com/itwanger/vn4p17/wslq2t/https://blog.csdn.net/qq_40885085/article/details/105023026
<!-- 若存在Spring Data ES的某个版本支持你下的ES版本,则使用  --><!-- Spring官方在ES官方提供的JAVA环境使用的依赖的基础上做了封装 --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-elasticsearch</artifactId></dependency><!-- ESTestEntity用到 --><dependency><groupId>jakarta.servlet</groupId><artifactId>jakarta.servlet-api</artifactId><version>6.0.0</version><scope>provided</scope></dependency><!-- ESTestEntity用到 --><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><scope>provided</scope><!--provided:指定该依赖项在编译时是必需的,才会生效, 但在运行时不需要,也不会生效--><!--这样 Lombok 会在编译期静悄悄地将带 Lombok 注解的源码文件正确编译为完整的 class 文件 --></dependency>
  1. 新建:web模块TestEntity目录新建ESTestEntity
@Data@EqualsAndHashCode(callSuper =false)@Document(indexName ="test")publicclassESTestEntityimplementsSerializable{privatestaticfinallong serialVersionUID =1L;@IdprivateLong id;@Field(type =FieldType.Text, analyzer ="ik_max_word")privateString content;privateString title;privateString excerpt;}
  1. 新建:web模块TestRepository包下新建ESTestRepository 接口
importcn.bytewisehub.pai.web.TestEntity.ESTestEntity;importorg.springframework.data.domain.Page;importorg.springframework.data.domain.Pageable;importorg.springframework.data.elasticsearch.repository.ElasticsearchRepository;publicinterfaceESTestRepositoryextendsElasticsearchRepository<ESTestEntity,Long>{}

直接连接

ES
  1. 配置:ES``````Elasticsearch.ymlxpack.security.enabled属性设置为false
xpack.security.enabled


● 默认

true

:必须使用账号连接

ES

● 若为

false

:必须使用

http://localhost:9200/

访问

ES

服务

+

启动

Kibana

服务会失败

+

不需要使用账号连接,但必须使用

HTTP

连接

  1. 配置:web模块dev目录application-dal添加
spring:elasticsearch:uris:- http://127.0.0.1:9200
  1. 新建:web模块test目录新建ElasticsearchTemplateTest
importcn.bytewisehub.pai.web.TestEntity.ESTestEntity;importcn.bytewisehub.pai.web.TestRepository.ESTestRepository;importorg.junit.jupiter.api.Test;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.boot.test.context.SpringBootTest;importorg.springframework.data.elasticsearch.client.elc.ElasticsearchTemplate;@SpringBootTestpublicclassElasticsearchTemplateTest{@AutowiredESTestRepository esTestRepository;@AutowiredElasticsearchTemplate elasticsearchTemplate;@Testvoidsave(){ESTestEntity esTestEntity =newESTestEntity();
        esTestEntity.setId(1L);
        esTestEntity.setContent("不安全连接");
        esTestEntity.setTitle("world");
        esTestEntity.setExcerpt("test");System.out.println(elasticsearchTemplate.save(esTestEntity));}@Testvoidinsert(){ESTestEntity esTestEntity =newESTestEntity();
        esTestEntity.setId(2L);
        esTestEntity.setContent("不安全连接");
        esTestEntity.setTitle("world");
        esTestEntity.setExcerpt("test");System.out.println(esTestRepository.save(esTestEntity));}}
  1. 访问:点击http://localhost:9200/test/_search``````---查询索引库test请添加图片描述

HTTP

连接

ES
  1. 配置:ES``````Elasticsearch.ymlxpack.security.enabled属性使用默认值+``````xpack.security.http.ssl.enabled设置为false
ES
Elasticsearch.yml

xpack.security.http.ssl.enabled


● 默认

true

:必须使用

https://localhost:9200/

访问

ES

服务

+

启动

Kibana

服务会成功

+

需要使用账号连接

+

必须使用

HTTPS

连接
● 若为

false

:必须使用

http://localhost:9200/

访问

ES

服务

+

启动

Kibana

服务会失败

+

需要使用账号连接,但必须使用

HTTP

连接

  1. 配置:web模块dev目录application-dal添加
spring:elasticsearch:uris:- http://127.0.0.1:9200username:# 账号用户名password:#账号密码
  1. 修改:web模块test目录下ElasticsearchTemplateTest修改成这样,其他参见直接连接
importcn.bytewisehub.pai.web.TestEntity.ESTestEntity;importcn.bytewisehub.pai.web.TestRepository.ESTestRepository;importorg.junit.jupiter.api.Test;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.boot.test.context.SpringBootTest;importorg.springframework.data.elasticsearch.client.elc.ElasticsearchTemplate;@SpringBootTestpublicclassElasticsearchTemplateTest{@AutowiredESTestRepository esTestRepository;@AutowiredElasticsearchTemplate elasticsearchTemplate;@Testvoidsave(){ESTestEntity esTestEntity =newESTestEntity();
        esTestEntity.setId(1L);
        esTestEntity.setContent("不安全连接");
        esTestEntity.setTitle("world");
        esTestEntity.setExcerpt("test");System.out.println(elasticsearchTemplate.save(esTestEntity));}@Testvoidinsert(){ESTestEntity esTestEntity =newESTestEntity();
        esTestEntity.setId(2L);
        esTestEntity.setContent("不安全连接");
        esTestEntity.setTitle("world");
        esTestEntity.setExcerpt("test");System.out.println(esTestRepository.save(esTestEntity));}}
  1. 访问:点击http://localhost:9200/test/_search``````---查询索引库test

HTTPS

连接

ES 
  1. 配置:ES``````Elasticsearch.ymlxpack.security.enabledxpack.security.http.ssl.enabled属性使用默认值
  2. 配置:web模块dev目录application-dal添加
spring:elasticsearch:uris:- https://127.0.0.1:9200username:# 账号用户名password:#账号密码
  1. 修改:web模块test目录下ElasticsearchTemplateTest修改成这样,其他参见直接连接
importcn.bytewisehub.pai.web.TestEntity.ESTestEntity;importcn.bytewisehub.pai.web.TestRepository.ESTestRepository;importorg.junit.jupiter.api.Test;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.boot.test.context.SpringBootTest;importorg.springframework.data.elasticsearch.client.elc.ElasticsearchTemplate;@SpringBootTestpublicclassElasticsearchTemplateTest{@AutowiredESTestRepository esTestRepository;@AutowiredElasticsearchTemplate elasticsearchTemplate;@Testvoidsave(){ESTestEntity esTestEntity =newESTestEntity();
        esTestEntity.setId(1L);
        esTestEntity.setContent("不安全连接");
        esTestEntity.setTitle("world");
        esTestEntity.setExcerpt("test");System.out.println(elasticsearchTemplate.save(esTestEntity));}@Testvoidinsert(){ESTestEntity esTestEntity =newESTestEntity();
        esTestEntity.setId(2L);
        esTestEntity.setContent("不安全连接");
        esTestEntity.setTitle("world");
        esTestEntity.setExcerpt("test");System.out.println(esTestRepository.save(esTestEntity));}}
  1. 访问:点击http://localhost:9200/test/_search``````---查询索引库test
标签: java spring spring boot

本文转载自: https://blog.csdn.net/qq_50864152/article/details/136736296
版权归原作者 柳衣白卿 所有, 如有侵权,请联系我们删除。

“SpringBoot3整合Elasticsearch8.x之全面保姆级教程”的评论:

还没有评论