Skip to content

背景: 仓配侧, 查库存信息分片查询

java
// 线程池
private ThreadPoolExecutor executor = new ThreadPoolExecutor(  
        1,  
        60,  
        60,  
        TimeUnit.SECONDS,  
        new LinkedBlockingQueue<Runnable>(1),  
        new ThreadPoolExecutor.CallerRunsPolicy()  
);


public Map<String, Map<Integer, Integer>> querySkuStock(String saleModel, List<BatchStockQueryVO> stockRequestList) {  
    if (stockRequestList.size() < 100) {  
        //数量小于100的时候, 不需要拆分多线程处理   
        return getSkuStock(saleModel, stockRequestList); 
    }  
    //单次请求数量超过100,批量多线程处理  
    Map<String, Map<Integer, Integer>> stockMap = Maps.newHashMap();  
    List<List<BatchStockQueryVO>> avgList = ListUtils.averageAssign(stockRequestList, 100);  
    List<Future<Map<String, Map<Integer, Integer>>>> list = new ArrayList<>();  
    for (int i = 0; i < avgList.size(); i++) {  
        StockCallable stockCallable = new StockCallable(this, saleModel, avgList.get(i));  
        Future<Map<String, Map<Integer, Integer>>> f = executor.submit(stockCallable);  
        list.add(f);  
    }  
    //多线程结果转换  
    stockMap = generateBatchResult(list);  
    return stockMap;  
}

StockCallable.Callable(){
 getSkuStock();
}

private Map<String, Map<Integer, Integer>> generateBatchResult(List<Future<Map<String, Map<Integer, Integer>>>> list) {  
    Map<String, Map<Integer, Integer>> stockMap = new HashMap<>();  
    for (Future<Map<String, Map<Integer, Integer>>> future : list) {  
        Map<String, Map<Integer, Integer>> tempMap = null;  
        try {  
            tempMap = future.get();  
        } catch (InterruptedException e) {  
            log.error("获取库存结果异常:{}",e.getMessage());  
        } catch (ExecutionException e) {  
            log.error("获取库存结果异常:{}",e.getMessage());  
        }  
        if (MapUtils.isNotEmpty(tempMap)) {  
            for (Map.Entry<String, Map<Integer, Integer>> entry : tempMap.entrySet()) {  
                String skuCode = entry.getKey();  
                Map<Integer, Integer> storageStockMap = stockMap.get(skuCode);  
                if (MapUtils.isEmpty(storageStockMap)) {  
                    storageStockMap = entry.getValue();  
                } else {  
                    storageStockMap.putAll(entry.getValue());  
                }  
                stockMap.put(skuCode, storageStockMap);  
            }  
        }  
    }  
    return stockMap;  
}

waitingresult.com