CompletableFuture 的这种实现实际上带来了任何好处吗?

时间:2021-08-01 11:19:12

标签: java spring-boot asynchronous completable-future

我正在学习 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 上测试我的端点时,我可以看到两个版本的执行时间非常相似。这是实现此目的的正确方法吗?

0 个答案:

没有答案
相关问题