java - 使用 CompleteableFuture 异步执行两个方法
问题描述
这是我必须使运行速度更快的代码片段:
fillPricedServiceForLocation(location, doc, locale, services);
fillReviewsForLocation(location, doc, services);
两种方法如下所示:
private static void fillPricedServiceForLocation(Location location, LocationDocument doc,
Language locale, List<Long> services) {
if (doc.isPriceList()) {
String locationId = doc.getLocationId();
try {
new PricesRepository().findServiceForLocation(locationId, services)
.ifPresent(foundService -> {
String serviceId = foundService.getServiceId();
final LocationServices locationServices = new LocationServices();
locationServices.setId(Integer.valueOf(serviceId));
locationServices.setPrice(BigDecimal.valueOf(foundService.getPrice()));
locationServices.setCurrency(foundService.getCurrency());
ServiceName serviceName = ServiceNameProvider.getServiceName(serviceId);
locationServices.setName(serviceName.getName(locale));
location.setServices(locationServices);
});
} catch (Exception e) {
log.error("Error when trying to retrieve last review for location {}", locationId,
e);
}
}
}
private static void fillReviewsForLocation(Location location, LocationDocument doc,
List<Long> services) {
String locationId = doc.getLocationId();
try {
LocationReviews locationReviews = new LocationReviews();
locationReviews.setCount(doc.getReviewsCount());
locationReviews.setScore(doc.getReviewsScore());
new ReviewsRepository().findReview(locationId, services).ifPresent(
foundReview -> locationReviews.setReview(reviewDocumentToJsonModel(foundReview)));
location.setReviews(locationReviews);
} catch (Exception e) {
log.error("Error when trying to retrieve last review for location {}", locationId, e);
}
}
他们调用两个不同的存储库,如果他们找到一些东西,他们会处理它并更新作为参数location传递。是否可以并行化这两个方法调用以便同时处理它们?尝试使用 CompleteableFuture 但无法使其运行 - 对异步编程没有太多经验。
解决方案
你可以在两个不同的线程中,在每个线程的 run() 方法中编写一个函数。然后使用 ExecutorService.submit(threadOne) 和 ExecutorService.submit(threadTwo) 并行执行它。
推荐阅读
- php - 将数组传递给 Laravel 视图
- c++ - 从 C++ 代码中读取 journalctl 的调试输出
- python - 在 pyspark 中创建带有时间戳和 groupby 的 KPI
- java - 在 Java 中使用 doc4J 加载 .XML 文件时出现问题
- python - 如何在熊猫 barh 图中仅堆叠选定的列
- python - pandas.to_csv 不将浮点值显示为小数点后 2 位
- python - 为什么第 7 行中的变量 url 不显示为 varibal?
- python - 如何检测数据帧列中逻辑序列中的错误?
- php - 生成二维码并合并到编辑后的 JPG 文件中
- image - ASP.NET MVC 中的图像