SpringBoot3整合Elasticsearch8(1)

文章详细介绍了如何在SpringBoot应用中配置Elasticsearch,包括使用不同方式(HTTP、账号密码、证书)连接,设置连接超时,最大连接数等,并展示了如何使用SpringDataElasticsearch。
摘要由CSDN通过智能技术生成

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


4. 配置:`web`模块`config`包下新建`ElasticSearchConfig`类



package cn.bytewisehub.pai.web.config;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.json.jackson.JacksonJsonpMapper;
import co.elastic.clients.transport.ElasticsearchTransport;
import co.elastic.clients.transport.rest_client.RestClientTransport;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
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.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Slf4j
@Data
@Configuration
@ConfigurationProperties(prefix = “elasticsearch”)
public class ElasticSearchConfig {

// 是否开启ES
private Boolean open;

// es 集群host ip 地址
private String hosts;

// es用户名
private String userName;

// es密码
private String password;

// es 请求方式
private String scheme;

// es集群名称
private String clusterName;

// es 连接超时时间
private int connectTimeOut;

// es socket 连接超时时间
private int socketTimeOut;

// es 请求超时时间
private int connectionRequestTimeOut;

// es 最大连接数
private int maxConnectNum;

// es 每个路由的最大连接数
private int maxConnectNumPerRoute;

// es api key
private String apiKey;


public RestClientBuilder creatBaseConfBuilder(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 https
    HttpHost httpHost = new HttpHost(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;
}

}


5. 测试:`web`模块`test`目录下新建`ElasticSearchTest`类



@Slf4j
@SpringBootTest
public class ElasticSearchTest {

@Value("${elasticsearch.open}")
// 是否开启ES,默认开启
String open = "true";

}


#### 直接连接`ES`


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



> 
> `xpack.security.enabled`:  
>  ● 默认`true`:必须使用账号连接`ES`  
>  ● 若为`false`:必须使用`http://localhost:9200/`访问`ES`服务`+`启动`Kibana`服务会失败`+`不需要使用账号连接,但必须使用`HTTP`连接
> 
> 
> 


3. 添加:`ElasticSearchConfig`类添加下列方法



/**
* @function: 创建使用http连接来直接连接ES服务器的客户端
* 如果@Bean没有指定bean的名称,那么这个bean的名称就是方法名
*/
@Bean(name = “directConnectionESClient”)
public ElasticsearchClient directConnectionESClient(){

RestClientBuilder builder = creatBaseConfBuilder((scheme == "http")?"http":"http");

//Create the transport with a Jackson mapper
ElasticsearchTransport transport = new RestClientTransport(builder.build(), new JacksonJsonpMapper());

//And create the API client
ElasticsearchClient esClient = new ElasticsearchClient(transport);

return esClient;

};


3. 添加:`ElasticSearchTest`类中添加下列代码`---`索引名必须小写
4. 运行:设置跳过测试`--->`手动运行/不跳过`--->`直接`install`,但不运行测试



@Resource(name = “directConnectionESClient”)
ElasticsearchClient directConnectionESClient;

@Test
public void directConnectionTest() throws IOException {

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.yml`的`xpack.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连接
> 
> 
> 


2. 配置:`dev`目录`application-dal`中添加下列配置



elasticsearch配置

elasticsearch:
userName: #自己的账号名
password: #自己的密码


3. 添加:`ElasticSearchTest`类中添加下列代码`---`索引名必须小写`+`不能有空格
4. 运行:设置跳过测试`--->`手动运行/不跳过`--->`直接`install`,但不运行测试



@Resource(name = “accountConnectionESClient”)
ElasticsearchClient accountConnectionESClient;

@Test
public void accountConnectionTest() throws IOException {

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.yml`的`xpack.security.enabled`和`xpack.security.http.ssl.enabled`配置项使用默认值



> 
> 设置为`true`后,`ES`就走`https`,若`scheme`为`http`,则报`Unrecognized` SSL `message`错误
> 
> 
> 


2. 配置:将`dev`目录`application-dal`中`elasticsearch.scheme`配置项改成`https`
3. 证书添加:终端输入`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"` `---`与上面的命令相反
> 
> 
> 


4. 拷贝:将`ESconfig`目录下`certs`目录下的`http_ca.crt`文件拷贝到`web`模块`resource`目录
5. 添加:`ElasticSearchConfig`类添加下列方法



/**
* @function: 创建用于安全连接(证书 + 账号)ES服务器的客户端
* 如果@Bean没有指定bean的名称,那么这个bean的名称就是方法名
*/
@Bean(name = “accountAndCertificateConnectionESClient”)
public ElasticsearchClient accountAndCertificateConnectionESClient() {

RestClientBuilder builder = creatBaseConfBuilder( (scheme == "https")?"https":"https");

// 1.账号密码的配置
//CredentialsProvider: 用于提供 HTTP 身份验证凭据的接口; 允许你配置用户名和密码,以便在与服务器建立连接时进行身份验证
CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(userName, password));

// 2.设置自签证书,并且还包含了账号密码
builder.setHttpClientConfigCallback(httpAsyncClientBuilder -> httpAsyncClientBuilder
                                    .setSSLContext(buildSSLContext())
                                    .setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
                                    .setDefaultCredentialsProvider(credentialsProvider));

RestClientTransport transport = new RestClientTransport(builder.build(), new JacksonJsonpMapper());

//And create the API client
ElasticsearchClient esClient = new ElasticsearchClient(transport);

return esClient;

}

private static SSLContext buildSSLContext() {

// 读取http\_ca.crt证书
ClassPathResource resource = new ClassPathResource("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;

}


7. 测试:`ElasticSearchTest`类添加



@Resource(name = “accountAndCertificateConnectionESClient”)
ElasticsearchClient accountAndCertificateConnectionESClient;

@Test
public void accountAndCertificateConnectionTest() throws IOException {

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`
> 
> 
> 



org.springframework.boot spring-boot-starter-data-elasticsearch jakarta.servlet jakarta.servlet-api 6.0.0 provided org.projectlombok lombok provided

2. 新建:`we`b模块`TestEntity`目录新建`ESTestEntity`



@Data
@EqualsAndHashCode(callSuper = false)
@Document(indexName = “test”)
public class ESTestEntity implements Serializable {

private static final long serialVersionUID = 1L;

@Id
private Long id;

@Field(type = FieldType.Text, analyzer = "ik\_max\_word")
private String content;

private String title;

private String excerpt;

}



# 最后

![腾讯T3大牛总结的500页MySQL实战笔记意外爆火,P8看了直呼内行](https://img-blog.csdnimg.cn/img_convert/5501a26ee36c4a90625cbd8d745510c7.webp?x-oss-process=image/format,png)

![腾讯T3大牛总结的500页MySQL实战笔记意外爆火,P8看了直呼内行](https://img-blog.csdnimg.cn/img_convert/7b5f957a0efd1969ece4a7b422857186.webp?x-oss-process=image/format,png)

Code(callSuper = false)
@Document(indexName = "test")
public class ESTestEntity implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    private Long id;

    @Field(type = FieldType.Text, analyzer = "ik\_max\_word")
    private String content;

    private String title;

    private String excerpt;
}

最后

[外链图片转存中…(img-FSWtp9lf-1714149363884)]

[外链图片转存中…(img-ymMtzu9Y-1714149363884)]

本文已被CODING开源项目:【一线大厂Java面试题解析+核心总结学习笔记+最新讲解视频+实战项目源码】收录

  • 25
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值