【发布时间】:2020-10-30 17:13:53
【问题描述】:
我正在学习 webflux 和 reactor。得到以下三种测试方法。 “documentOperations.findById”和“documentOperations.delete”是两个数据库操作。我知道 test1 不好,因为两个数据库操作放在一个异步方法中。我的问题是:
test2 和 test3 对系统性能的影响是否相同?或者换句话说,哪个更好?
private Mono<ServerResponse> test1(ServerRequest request, Contexts contexts) {
return request.body(bodyDocumentExtractor)
.flatMap(doc -> {
Document document = documentOperations.findById(doc.getId());
documentOperations.delete(document.getId());
return ServerResponse.noContent().build();
});
}
private Mono<ServerResponse> test2(ServerRequest request, Contexts contexts) {
return request.body(bodyDocumentExtractor)
.flatMap(doc -> {
return Mono.just(documentOperations.findById(doc.getId()))
.flatMap(document -> {
documentOperations.delete(document.getId());
return ServerResponse.noContent().build();
});
});
}
private Mono<ServerResponse> test3(ServerRequest request, Contexts contexts) {
return request.body(bodyDocumentExtractor)
.flatMap(doc -> {
return Mono.just(documentOperations.findById(doc.getId()));
}).flatMap(document -> {
documentOperations.delete(document.getId());
return ServerResponse.noContent().build();
});
}
【问题讨论】:
-
我假设
documentOperations上的操作与一些外部数据源交互。因此,这两种方法都应返回包装在Mono中的结果。 -
@Michael Xin 在使用 Webflux 时最好使用响应式数据库客户端。每当您需要连接到外部详细信息(例如 dbs、http 资源)时,请始终使用响应式客户端。对于 dbs checkout ReactiveMongoRepository,对于 http 调用 checkout WebClient。如果您找不到这样的响应式客户端,请查看用于处理阻塞行为的 spring 准则。 docs.spring.io/spring-framework/docs/current/reference/html/…
-
您的数据库返回的具体值直接告诉我它们正在阻塞。所以以上都不好,都是坏的。
标签: java mono spring-webflux reactor