java - Reactive Spring Boot API 包装了 Elasticsearch 的异步批量索引
问题描述
我正在为一个新项目开发原型。这个想法是为 Elasticsearch 中的批量索引文档提供响应式 Spring Boot 微服务。Elasticsearch 提供了一个高级 Rest 客户端,它提供了一种异步方法来批量处理索引请求。此处提到了使用侦听器的异步传递回调。回调分批接收索引响应(每个请求)。我正在尝试将此响应作为 Flux 发送回客户端。我根据这篇博文提出了一些建议。
控制器
@RestController
public class AppController {
@SuppressWarnings("unchecked")
@RequestMapping(value = "/test3", method = RequestMethod.GET)
public Flux<String> index3() {
ElasticAdapter es = new ElasticAdapter();
JSONObject json = new JSONObject();
json.put("TestDoc", "Stack123");
Flux<String> fluxResponse = es.bulkIndex(json);
return fluxResponse;
}
弹性适配器
@Component
class ElasticAdapter {
String indexName = "test2";
private final RestHighLevelClient client;
private final ObjectMapper mapper;
private int processed = 1;
Flux<String> bulkIndex(JSONObject doc) {
return bulkIndexDoc(doc)
.doOnError(e -> System.out.print("Unable to index {}" + doc+ e));
}
private Flux<String> bulkIndexDoc(JSONObject doc) {
return Flux.create(sink -> {
try {
doBulkIndex(doc, bulkListenerToSink(sink));
} catch (JsonProcessingException e) {
sink.error(e);
}
});
}
private void doBulkIndex(JSONObject doc, BulkProcessor.Listener listener) throws JsonProcessingException {
System.out.println("Going to submit index request");
BiConsumer<BulkRequest, ActionListener<BulkResponse>> bulkConsumer =
(request, bulkListener) ->
client.bulkAsync(request, RequestOptions.DEFAULT, bulkListener);
BulkProcessor.Builder builder =
BulkProcessor.builder(bulkConsumer, listener);
builder.setBulkActions(10);
BulkProcessor bulkProcessor = builder.build();
// Submitting 5,000 index requests ( repeating same JSON)
for (int i = 0; i < 5000; i++) {
IndexRequest indexRequest = new IndexRequest(indexName, "person", i+1+"");
String json = doc.toJSONString();
indexRequest.source(json, XContentType.JSON);
bulkProcessor.add(indexRequest);
}
System.out.println("Submitted all docs
}
private BulkProcessor.Listener bulkListenerToSink(FluxSink<String> sink) {
return new BulkProcessor.Listener() {
@Override
public void beforeBulk(long executionId, BulkRequest request) {
}
@SuppressWarnings("unchecked")
@Override
public void afterBulk(long executionId, BulkRequest request, BulkResponse response) {
for (BulkItemResponse bulkItemResponse : response) {
JSONObject json = new JSONObject();
json.put("id", bulkItemResponse.getResponse().getId());
json.put("status", bulkItemResponse.getResponse().getResult
sink.next(json.toJSONString());
processed++;
}
if(processed >= 5000) {
sink.complete();
}
}
@Override
public void afterBulk(long executionId, BulkRequest request, Throwable failure) {
failure.printStackTrace();
sink.error(failure);
}
};
}
public ElasticAdapter() {
// Logic to initialize Elasticsearch Rest Client
}
}
我使用 FluxSink 创建响应的 Flux 以发送回客户端。在这一点上,我不知道这是否正确。
我的期望是调用客户端应该以 10 个批次接收响应(因为批量处理器以 10 个批次处理它 - builder.setBulkActions(10);
)。我尝试使用 Spring Webflix Client 使用端点。但无法解决。这是我尝试过的
网络客户端
public class FluxClient {
public static void main(String[] args) {
WebClient client = WebClient.create("http://localhost:8080");
Flux<String> responseFlux = client.get()
.uri("/test3")
.retrieve()
.bodyToFlux(String.class);
responseFlux.subscribe(System.out::println);
}
}
正如我所料,控制台上没有打印任何内容。我尝试使用System.out.println(responseFlux.blockFirst());
. 它在最后将所有响应打印为一个批次,而不是在 .
如果我的方法是正确的,那么正确的消费方法是什么?对于我心目中的解决方案,这个客户端将驻留在另一个 Web 应用程序中。
注:我对 Reactor API 的理解有限。使用的 elasticsearch 版本是 6.8。
解决方案
因此,对您的代码进行了以下更改。
在 ElasticAdapter 中,
public Flux<Object> bulkIndex(JSONObject doc) {
return bulkIndexDoc(doc)
.subscribeOn(Schedulers.elastic(), true)
.doOnError(e -> System.out.print("Unable to index {}" + doc+ e));
}
在 Flux 上调用 subscribeOn(Scheduler, requestOnSeparateThread),从https://github.com/spring-projects/spring-framework/issues/21507了解它
在 FluxClient 中,
Flux<String> responseFlux = client.get()
.uri("/test3")
.headers(httpHeaders -> {
httpHeaders.set("Accept", "text/event-stream");
})
.retrieve()
.bodyToFlux(String.class);
responseFlux.delayElements(Duration.ofSeconds(1)).subscribe(System.out::println);
添加了“Accept”标头作为“text/event-stream”并延迟了 Flux 元素。
通过上述更改,能够从服务器获得实时响应。
推荐阅读
- c++ - 无法在多通道中将 fcgi 库与 g++ 链接
- arrays - 如何在角度 9 的对象模型中设置数组属性
- javascript - Nerlify:lambda 响应未定义。再次检查您的功能代码在 583 毫秒内以状态 500 响应
- sql - how to transform a number in binary representation to a Snowflake number
- typescript - 如何使用 AWS CDK 在 typescript 中获取路由表 ID
- google-sheets - 具有多个结果的 Google 表格索引/匹配
- django - 创建一个“post”对象并使用 post id 和 author id 初始化一个 m2m 属性
- flutter - 将侦听器添加到列表
- javascript - EPERM 阻止的文件写入权限 - 删除然后写入新文件。节点.js
- flutter - 如何在浏览列表时使用速度