es的自签证书,这是SpringBoot
时间: 2025-05-23 22:09:32 浏览: 15
### Spring Boot 中使用 Elasticsearch 的自签证书配置
在 Spring Boot 和 Elasticsearch 结合使用的场景下,如果启用了 HTTPS 并使用了自签名证书,则需要额外的配置来支持客户端验证服务器的身份。以下是详细的配置方法:
#### 1. 准备自签证书
确保已经生成了一个有效的自签名证书,并将其导出为 `.crt` 文件(例如 `http_ca.crt`)。此文件将在后续步骤中用于信任 Elasticsearch 服务端。
#### 2. 配置 application.yml 或 application.properties
在项目的 `application.yml` 文件中添加如下配置项[^2]:
```yaml
spring:
elasticsearch:
rest:
enable: true
uris: https://localhost:9200
host: localhost
port: 9200
username: elastic
password: your_password_here
crtName: http_ca.crt
```
注意:这里的 `uris` 使用的是 `https` 协议,因为启用了 SSL/TLS 加密通信。
#### 3. 添加证书到项目资源目录
将自签名证书文件(如 `http_ca.crt`)放置于项目的 `src/main/resources/` 目录下,以便应用程序能够加载它。
#### 4. 创建自定义 RestHighLevelClient Bean
由于默认的 Spring Boot 自动配置不支持自签名证书,因此需要手动创建一个定制化的 `RestHighLevelClient` 实现。通过以下方式实现对自签名证书的信任:
```java
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.apache.http.ssl.SSLContextBuilder;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.io.FileInputStream;
import java.security.KeyStore;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
@Configuration
public class ElasticConfig {
@Bean
public RestHighLevelClient client() throws Exception {
String crtPath = "classpath:http_ca.crt"; // 路径指向 resources 下的 crt 文件
X509Certificate caCert = loadCaCert(crtPath);
CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("elastic", "your_password_here"));
RestClient restClient = RestClient.builder(new HttpHost("localhost", 9200, "https"))
.setHttpClientConfigCallback(httpAsyncClientBuilder -> {
try {
KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
trustStore.load(null); // 初始化为空 Truststore
trustStore.setCertificateEntry("ca-cert", caCert);
return httpAsyncClientBuilder.setDefaultCredentialsProvider(credentialsProvider)
.setSSLContext(SSLContextBuilder.create()
.loadTrustMaterial(trustStore, null).build())
.setSSLHostnameVerifier((hostname, session) -> true); // 禁用主机名验证
} catch (Exception e) {
throw new RuntimeException(e);
}
})
.build();
return new RestHighLevelClient(restClient);
}
private static X509Certificate loadCaCert(String certPath) throws Exception {
CertificateFactory cf = CertificateFactory.getInstance("X.509");
try (FileInputStream fis = new FileInputStream(certPath)) {
return (X509Certificate) cf.generateCertificate(fis);
}
}
}
```
上述代码实现了以下几个功能:
- **加载 CA 证书**:从指定路径读取并解析自签名证书。
- **禁用主机名验证**:对于开发环境中的测试用途,可以忽略主机名匹配问题。
- **集成用户名密码认证**:提供基本身份验证所需的凭证。
#### 5. 测试连接
完成以上配置后,可以通过简单的 REST 请求测试与 Elasticsearch 的连通性。例如,在控制器中注入 `RestHighLevelClient` 并执行索引操作:
```java
@RestController
@RequestMapping("/test-es")
public class EsController {
@Autowired
private RestHighLevelClient client;
@GetMapping("/ping")
public ResponseEntity<String> pingEs() throws IOException {
Request request = new Request("GET", "/");
Response response = client.getLowLevelClient().performRequest(request);
return ResponseEntity.ok(EntityUtils.toString(response.getEntity()));
}
}
```
访问 `/test-es/ping` 接口即可确认是否成功连接至 Elasticsearch。
---
阅读全文
相关推荐







