spring data elasticsearch使用7.x客户端兼容es 8.x和使用ssl构建RestHighLevelClient

问题:

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使用最新依赖库):

	 <!-- 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中注入该客户端

    @Autowired
    private ElasticsearchOperations elasticsearchOperations;
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值