牛叔叔 的笔记

好好学习

2025-01-07 11:21

SpringBoot通过https请求ElasticSearch

牛叔叔

JavaEE

(24)

(0)

收藏


1. 添加依赖

首先,在你的Spring Boot项目的pom.xml文件中添加Elasticsearch的依赖。

xml复制代码


<dependencies>

<!-- Spring Boot Starter Data Elasticsearch -->

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-data-elasticsearch</artifactId>

</dependency>



<!-- Elasticsearch Rest High Level Client -->

<dependency>

<groupId>org.elasticsearch.client</groupId>

<artifactId>elasticsearch-rest-high-level-client</artifactId>

<version>7.10.2</version> <!-- 请根据你的Elasticsearch版本选择合适的版本 -->

</dependency>



<!-- Jackson Databind (用于JSON处理) -->

<dependency>

<groupId>com.fasterxml.jackson.core</groupId>

<artifactId>jackson-databind</artifactId>

</dependency>

</dependencies>

2. 配置Elasticsearch连接

application.propertiesapplication.yml文件中配置Elasticsearch的连接信息。

使用application.properties

properties复制代码


spring.elasticsearch.rest.uris=https://your-elasticsearch-host:9200

spring.elasticsearch.username=your-username

spring.elasticsearch.password=your-password

spring.elasticsearch.rest.connection-timeout=5s

spring.elasticsearch.rest.read-timeout=10s

使用application.yml

yaml复制代码


spring:

elasticsearch:

rest:

uris: https://your-elasticsearch-host:9200

username: your-username

password: your-password

connection-timeout: 5s

read-timeout: 10s

3. 配置SSL(如果需要自签名证书)

如果你的Elasticsearch使用自签名证书,你可能需要配置SSL信任。

创建一个配置类来加载证书

java复制代码


import org.apache.http.HttpHost;

import org.apache.http.ssl.SSLContextBuilder;

import org.apache.http.ssl.SSLContexts;

import org.elasticsearch.client.RestClient;

import org.elasticsearch.client.RestHighLevelClient;

import org.springframework.beans.factory.annotation.Value;

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.Configuration;



import javax.net.ssl.SSLContext;

import java.io.FileInputStream;

import java.io.IOException;

import java.security.KeyStore;



@Configuration

public class ElasticsearchConfig {



@Value("${spring.elasticsearch.rest.uris}")

private String elasticsearchUris;



@Value("${spring.elasticsearch.username}")

private String username;



@Value("${spring.elasticsearch.password}")

private String password;



@Bean

public RestHighLevelClient client() throws Exception {

HttpHost[] hosts = RestClient.builder(new HttpHost("your-elasticsearch-host", 9200, "https")).setHttpClientConfigCallback(httpClientBuilder -> {

try {

// Load the keystore containing the truststore

KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());

try (FileInputStream trustStoreStream = new FileInputStream("path/to/your/truststore.jks")) {

trustStore.load(trustStoreStream, "truststore-password".toCharArray());

}



// Set up the SSL context to trust the keystore

SSLContext sslContext = SSLContexts.custom()

.loadTrustMaterial(trustStore, null)

.build();



return httpClientBuilder.setSSLContext(sslContext)

.setSSLHostnameVerifier((hostname, session) -> true); // For simplicity, accept all hostnames. Use a proper verifier in production.

} catch (Exception e) {

throw new RuntimeException(e);

}

}).build().getHosts();



RestClientBuilder builder = RestClient.builder(hosts);

if (username != null && password != null) {

builder.setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder.setDefaultCredentialsProvider(

new BasicCredentialsProvider().setCredentials(AuthScope.ANY,

new UsernamePasswordCredentials(username, password))

));

}



RestHighLevelClient client = new RestHighLevelClient(builder);

return client;

}

}

4. 使用Elasticsearch客户端

现在你可以在你的Spring Boot应用中使用Elasticsearch客户端了。

java复制代码


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.QueryBuilders;

import org.elasticsearch.search.builder.SearchSourceBuilder;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;



@Service

public class ElasticsearchService {



@Autowired

private RestHighLevelClient client;



public void searchExample() throws IOException {

SearchRequest searchRequest = new SearchRequest("your-index-name");

SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

searchSourceBuilder.query(QueryBuilders.matchAllQuery());

searchRequest.source(searchSourceBuilder);



SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);

// 处理搜索结果

}

}

5. 测试连接

运行你的Spring Boot应用,并调用ElasticsearchService中的方法,确保能够成功连接到Elasticsearch并获取数据。

注意事项

  1. 证书管理:在生产环境中,请确保使用有效的SSL证书,并正确管理证书和密钥。

  2. 安全性:不要在生产代码中硬编码用户名和密码,建议使用Spring Boot的配置管理功能(如Spring Cloud Config)来管理敏感信息。

  3. 错误处理:添加适当的错误处理和日志记录,以便在连接失败或查询出错时能够及时发现并解决问题。

通过以上步骤,你应该能够成功配置并使用Spring Boot通过HTTPS连接到Elasticsearch。


0条评论

点击登录参与评论