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

	 
	 <dependency>
	     <groupId>org.springframework.datagroupId>
	     <artifactId>spring-data-elasticsearchartifactId>
	     <version>4.4.2version>
	 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;

你可能感兴趣的:(java,elasticsearch,spring,ssl)