我有一个rest api控制器,它接收大量元素,搜索DB中的每个元素,更新字段然后保存更新的objectin DB 响应非常慢,所以我想使用某种异步调用。 我的代码:
@RequestMapping(value = "qwerty/", method = RequestMethod.POST,
consumes = {"application/xml"},
produces = "application/xml")
@ResponseBody
public PriceResponceDTOCollection performTask(@RequestBody PriceDataDTOCollection priceList){
final List<PriceError> priceErrorList = new ArrayList<>();
final List<PriceError> priceErrorList = new ArrayList<>();
final List<CompletableFuture> futures = new ArrayList();
for (final PriceData price : priceList.getPriceList()) {
futures.add(CompletableFuture.supplyAsync(()->priceService.setPrice(price)).thenAccept(priceErrorList::add));
}
futures.stream().map(CompletableFuture::join).count();
}
这是priceservice的setPrice
方法
@Autowired
private FlexibleSearchService flexibleSearchService;
public PriceError setPrice(Price data){
//building query
//initialize map with params
return flexibleSearchService.search(query.toString(),params).getResult().get(0);
}
然后我在de.hybris.platform.servicelayer.session.impl.DefaultSessionService.executeInLocalView(DefaultSessionService.java:94)
BTW,如果我的控制器看起来像这样(没有Fork连接池):
@RequestMapping(value = "qwerty/", method = RequestMethod.POST,
consumes = {"application/xml"},
produces = "application/xml")
@ResponseBody
public PriceResponceDTOCollection performTask(@RequestBody PriceDataDTOCollection priceList){
final List<PriceError> priceErrorList = new ArrayList<>();
for (final PriceData price : priceList.getPriceList()) {
PriceError err = priceService.setPrice(price);
priceErrorList.add(err);
}
}
一切都很完美。是什么原因(我也试过priceList.getPriceList().parallelstream()
并获得NPE)
答案 0 :(得分:0)
我认为通过网络服务更新价格是关键操作。也许您可以将更新转换为impex并调用impex导入服务。 Impex引擎具有并行处理和其他保护功能。