ElasticSearch Client
ElasticSearch 客户端的配置和用法。
使用 Spring Data ElasticSearch 的应用通常使用 ElasticSearch Operations
和 ElasticSearch Repositories
的高级别抽象。
一、Transport Client
从 ES7 开始不推荐使用,并将在 ES8 中删除。这里就不多赘述了。
推荐使用 Rest Client 。
二、REST Client
REST 客户端是 ES 的默认客户端,与 Transport Client
接受和返回完全相同的请求/响应对象,因此可以完全替换。
配置:
@Configuration
public class RestClientConfig extends AbstractElasticsearchConfiguration {
@Bean
@Override
public RestHighLevelClient elasticsearchClient() {
// 使用构造器来提供集群地址,设置默认的 HttpHeaders 或启用 SSL
ClientConfiguration build = ClientConfiguration.builder()
.connectedTo("localhost:9200")
.build();
return RestClients.create(build).rest();
}
}
// ... 获取Client
@Autowired
RestHighLevelClient highLevelClient;
RestClient lowLevelClient = highLevelClient.lowLevelClient();
// ... 使用
IndexRequest request = new IndexRequest("spring-data", "elasticsearch", randomID())
.source(singletonMap("feature", "high-level-rest-client"))
.setRefreshPolicy(IMMEDIATE);
IndexResponse response = highLevelClient.index(request);
三、客户端配置
HttpHeaders headers = new HttpHeaders();
headers.add("some-header", "on every request");
ClientConfiguration config = ClientCofiguration.builder()
// 连接的ES集群地址
.connectedTo("localhost:9200", "localhost:9300")
// 启用SSL
.useSsl()
// 设置代理
.withProxy("localhost:8888")
// 设置路径前缀,通常在不同的集群反代时使用
.withPathPrefix("ela")
// 连接超时时间,默认10s
.withConnectTimeout(Duration.ofSeconds(5))
// 套接字超时时间,默认5s
.withSocketTimeout(Duration.ofSeconds(3))
// 设置请求头
.withDefaultHeaders(headers)
// 身份验证
.withBasicAuth(username, password)
// 请求头
.withHeaders(() -> {
HttpHeaders h = new HttpHeaders();
h.add("currentTime", LocalDateTime.now().format(DateTimeFormatter.ISO_LOCAL_DATE_TIME));
return h;
})
.build();
四、日志
查看服务器的接收与响应,需要打开如下配置:
<logger name="org.springframework.data.elasticsearch.client.WIRE" level="trace" />