【多线程实例】

使用场景

拿到了一个商品的list,然后要循环list去获取每个商品的明细,由于调用api很依赖于网络,一个个执行速度慢,所以考虑使用线程去解决。

//根据机器id  获取 所有商品信息
public List<ProductResponse> productList(MachineConfigRequest.Code request) {
    //一次性查询数据库机器对应的商品list
    BoolQuery boolQuery = new BoolQuery();
    List<Query> queryList = new ArrayList<>();
    TermQuery termQuery1 = new TermQuery();
    termQuery1.setFieldName(ProductListConfigEnum.MACHINE_ID.getValue());
    termQuery1.setTerm(ColumnValue.fromString(request.getMachine_id()));
    queryList.add(termQuery1);


    boolQuery.setMustQueries(queryList);
    MachineCommonTableStore tableStore = new MachineCommonTableStore();
    SearchQuery searchQuery = new SearchQuery();
    searchQuery.setQuery(boolQuery);
    List<ProductResponse> searchResponse = tableStore.getRowList(searchQuery, ProductResponse.class, ModelEnum.PRODUCT_LIST.getModel(), ModelEnum.PRODUCT_LIST_INDEX.getModel());


    //根据机器id 和 获取所有的货道信息  key:slot value productInfo
    Map<String, ProductSlotInfo> map = this.getSlotInfo(request.getMachine_id());
    //转换为 key:productId value:slotList
    Map<String, List<ProductSlotInfo>> productSlotMap = this.getProductSlotList(map);


    //不需要更新货架图 直接返回库里面存的
    if (request.getLabel() == 0) {
        searchResponse.forEach(productResponse -> {
            //根据商品ID获取商品对应的货道list
            List<ProductSlotInfo> productSlotInfos = productSlotMap.get(productResponse.getProduct_id());
            //塞货道信息和库存
            this.setSlotAndQuantity(productResponse, productSlotInfos);
        });
        return searchResponse.parallelStream()
                .sorted(Comparator.comparing(ProductResponse::getSlot_info))
                .collect(Collectors.toList());
    }


    //根据机器id 调用API 获取所有商品id
    MachineService service = new MachineService();
    List<ProductResponse> list = service.getProductInventory(request.getMachine_id(), ProductResponse.class);


    //循环对比 把之前已经配置过赏级的商品的id和赏级塞进去
    list.forEach(response -> searchResponse.stream().filter(row -> response.getProduct_id().equals(row.getProduct_id())).forEach(row -> {
        response.setId(row.getId());
        response.setMarket(row.getMarket());
    }));


    List<ProductResponse> responseList = Lists.newArrayList();
    if (CollectionUtils.isNotEmpty(list)) {
        ThreadPoolExecutor pool = new ThreadPoolExecutor(50, 50
                , 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(100), (r, executor) -> {
            try {
                executor.getQueue().put(r);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });


        list.forEach(response -> pool.submit(() -> {
            //调用API 获取商品信息
            JSONObject object = new JSONObject();
            object.put(CeresonApiEnum.product_id.getValue(), response.getProduct_id());
            String json = RobotShopClient.callApiGet(CallMachineShopApiConstants.GET_PRODUCT_BY_ID, object.toJSONString());
            JSONObject jsonObject = JSON.parseObject(json);
            String data = jsonObject.getString(CeresonApiEnum.data.getValue());
            JSONObject js = JSON.parseObject(data);
            String productStr = js.getString(CeresonApiEnum.product.getValue());


            //把API获取的商品信息转换为Obj
            ProductResponse productResponse = JSON.parseObject(productStr, ProductResponse.class);
            //根据商品ID获取商品对应的货道list
            List<ProductSlotInfo> productSlotInfos = productSlotMap.get(response.getProduct_id());
            //塞货道信息和库存
            this.setSlotAndQuantity(productResponse, productSlotInfos);


            responseList.add(productResponse);
        }));
        boolean allThreadsIsDone = pool.getTaskCount() == pool.getCompletedTaskCount();
        while (!allThreadsIsDone) {
            allThreadsIsDone = pool.getTaskCount() == pool.getCompletedTaskCount();
        }
        pool.shutdown();
    }


    return responseList.parallelStream()
            .sorted(Comparator.comparing(ProductResponse::getSlot_info))
            .collect(Collectors.toList());
}
public PageResponse<AuctionListByUserIdResponse> getAuctionListByUserId(AuctionRequest.GetAuctionByUserId request) {


    AuctionTableStore auctionTableStore = new AuctionTableStore();


    List<Query> list = new ArrayList<>();
    BoolQuery boolQuery = new BoolQuery();
    BoolQuery shouldQuery = new BoolQuery();


    List<Sort.Sorter> sorter = TableStoreTemplate.getSorter(request.getSort());
    PageResponse<AuctionListByUserIdResponse> pageResponse = new PageResponse<>();
    try {
        pageResponse = auctionTableStore.queryAll(request.getNextToken(), sorter, boolQuery, request.getLimit(),
                AuctionListByUserIdResponse.class);
    } catch (Exception e) {
        log.error("getAuctionList failed exception = {}", e);
        throw new BaseException(ResponseCode.Bad_Request.getCode(), "查询失败!");
    }
    List<AuctionListByUserIdResponse> auctionListByUserIdResponses = pageResponse.getData();


    if (null != auctionListByUserIdResponses && auctionListByUserIdResponses.size() > 0) {
        ThreadPoolExecutor pool = new ThreadPoolExecutor(auctionListByUserIdResponses.size(), auctionListByUserIdResponses.size()
                , 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(), new RejectedExecutionHandler() {
            @Override
            public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
                try {
                    executor.getQueue().put(r);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        String robotSign = "##robot";
        auctionListByUserIdResponses.forEach(response -> {
            pool.submit(new Runnable() {
                @Override
                public void run() {
                    String sellerId = response.getSellerId();
                    String buyerId = response.getBuyerId();
                    String auctionId = response.getId();
                    String twr = "";
                    /* 处理是否为机器人 robotSign */
                    if (buyerId.endsWith(robotSign) || sellerId.endsWith(robotSign)) {
                        twr = "是";
                    } else {
                        twr = "否";
                    }
                    response.setWhetherRobot(twr);
                    response.setAuctionGoodsList(getGoodsRangeByAuctionId(sellerId, auctionId, DeleteFlagEnum.DELETE));
                    response.setAuctionBidGoodsList(getGoodsRangeByAuctionId(buyerId, auctionId, DeleteFlagEnum.DELETE));
                    response.setCostPrice(getTotalCostPrice(response.getAuctionGoodsList()));
                }
            });
        });
        boolean allThreadsIsDone = pool.getTaskCount() == pool.getCompletedTaskCount();
        while (!allThreadsIsDone) {
            allThreadsIsDone = pool.getTaskCount() == pool.getCompletedTaskCount();
        }
        pool.shutdown();
    }
    for (AuctionListByUserIdResponse info : pageResponse.getData()){
        System.out.println(info.getTransactionPrice() + "," + info.getCostPrice());
    }
    return pageResponse;
}

相关推荐

  1. 线实例

    2024-06-17 05:32:02       6 阅读
  2. c语言线队列实现

    2024-06-17 05:32:02       40 阅读
  3. Python的线使用实践

    2024-06-17 05:32:02       34 阅读
  4. Android中线实现

    2024-06-17 05:32:02       18 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-06-17 05:32:02       16 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-06-17 05:32:02       16 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-06-17 05:32:02       15 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-06-17 05:32:02       18 阅读

热门阅读

  1. Jupyter Notebook 入门教程

    2024-06-17 05:32:02       8 阅读
  2. 字符串数组——传递文本的不同方法实例

    2024-06-17 05:32:02       6 阅读
  3. Linux更改默认python版本

    2024-06-17 05:32:02       5 阅读
  4. 力扣上的经典问题:接雨水

    2024-06-17 05:32:02       6 阅读
  5. C++文本文件的读与写

    2024-06-17 05:32:02       6 阅读
  6. C++回溯算法

    2024-06-17 05:32:02       6 阅读
  7. 杂谈-Android和Ios的对比

    2024-06-17 05:32:02       10 阅读
  8. MySQL 保姆级教程(六):用通配符进行过滤

    2024-06-17 05:32:02       7 阅读
  9. 人工智能和印度大选

    2024-06-17 05:32:02       6 阅读