问题:
es在7.x中默认加入elastic security组件所以java client需要使用ssl连接es server.
es 8.x 中废弃了RestHighLevelClient
,使用新版的java api client
,但是spring data elasticsearch还未更新到该版本.所以需要兼容es 8.x
RestHighLevelClient构建代码:
如下是RestHighLevelClient构建方法:
spring data elasticsearch客户端依赖(基于spring boot2.7使用最新依赖库):文章来源:https://www.toymoban.com/news/detail-549944.html
<!-- es依赖-->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-elasticsearch</artifactId>
<version>4.4.2</version>
</dependency>
@Configuration
public class EsTemplateConfiguration extends AbstractElasticsearchConfiguration {
@SneakyThrows
@Override
@Bean
public RestHighLevelClient elasticsearchClient() {
HttpHeaders compatibilityHeaders = new HttpHeaders();
// 让es 8.x使用兼容模式 兼容7.x客户端
compatibilityHeaders.add("Accept", "application/vnd.elasticsearch+json;compatible-with=7");
compatibilityHeaders.add("Content-Type", "application/vnd.elasticsearch+json;"
+ "compatible-with=7");
//添加ssl
// http_ca.crt需要从es server下的config/certs中拷贝到代码的resource目录下
ClassPathResource classPathResource = new ClassPathResource("http_ca.crt");
CertificateFactory factory =
CertificateFactory.getInstance("X.509");
Certificate trustedCa;
try (InputStream is = classPathResource.getInputStream()) {
trustedCa = factory.generateCertificate(is);
}
KeyStore trustStore = KeyStore.getInstance("pkcs12");
trustStore.load(null, null);
trustStore.setCertificateEntry("ca", trustedCa);
SSLContextBuilder sslContextBuilder = SSLContexts.custom()
.loadTrustMaterial(trustStore, null);
SSLContext sslContext = sslContextBuilder.build();
ClientConfiguration clientConfiguration = ClientConfiguration.builder()
// 你的es server地址及端口
.connectedTo("localhost:9200")
// 使用ssl连接
.usingSsl(sslContext)
.withConnectTimeout(Duration.ofSeconds(5))
.withSocketTimeout(Duration.ofSeconds(3))
.withBasicAuth("用户名", "密码")
// this variant for imperative code
// 添加兼容头
.withDefaultHeaders(compatibilityHeaders)
.build();
return RestClients.create(clientConfiguration).rest();
}
}
然后你就可以在其他bean中注入该客户端文章来源地址https://www.toymoban.com/news/detail-549944.html
@Autowired
private ElasticsearchOperations elasticsearchOperations;
到了这里,关于spring data elasticsearch使用7.x客户端兼容es 8.x和使用ssl构建RestHighLevelClient的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!