我正在学习 Java Completable Future。
我决定重写这段代码来练习:
Product product = productRepository.findByUuid(UUID.fromString(productUuid)).orElse(null);
if (product == null)
// return some error
List<ProductCollection> collections = collectionRepository.findAll();
List<ProductCategory> categories = categorieyRepository.findAll();
return ResponseEntity.ok(new AdminProductDetailDTO(
product,
collections,
categories
));
然后想出了这个:
if (!productRepository.existsByUuid(UUID.fromString(productUuid)))
// return some error
CompletableFuture<Product> products = productService.findByUuid(productUuid);
CompletableFuture<List<ProductCollection>> collections = collectionService.findAll();
CompletableFuture<List<ProductCategory>> categories = categoryService.findAll();
return ResponseEntity.ok(new AdminProductDetailDTO(
products.get(),
collections.get(),
categories.get()
));
// Collection service
@Async
public CompletableFuture<List<ProductCollection>> findAll() {
return CompletableFuture.supplyAsync(collectionRepository::findAll);
}
// Category service
@Async
public CompletableFuture<List<ProductCategory>> findAll() {
return CompletableFuture.supplyAsync(categoryRepository::findAll);
}
当我在 postman 上测试我的端点时,我可以看到两个版本的执行时间非常相似。这是实现此目的的正确方法吗?