当前位置: 首页 > news >正文

【多线程实例】

使用场景

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

//根据机器id  获取 所有商品信息
public List<ProductResponse> productList(MachineConfigRequest.Code request) {//一次性查询数据库机器对应的商品listBoolQuery 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 productInfoMap<String, ProductSlotInfo> map = this.getSlotInfo(request.getMachine_id());//转换为 key:productId value:slotListMap<String, List<ProductSlotInfo>> productSlotMap = this.getProductSlotList(map);//不需要更新货架图 直接返回库里面存的if (request.getLabel() == 0) {searchResponse.forEach(productResponse -> {//根据商品ID获取商品对应的货道listList<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 获取所有商品idMachineService 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获取的商品信息转换为ObjProductResponse productResponse = JSON.parseObject(productStr, ProductResponse.class);//根据商品ID获取商品对应的货道listList<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() {@Overridepublic 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() {@Overridepublic 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;
}
http://www.lryc.cn/news/377470.html

相关文章:

  • 数据治理在数据提取中的角色:确保数据质量和安全
  • Nuxt快速学习开发 - Nuxt3静态资源Assets
  • 为什么企业需要数据挖掘平台?哪个比较好呢?
  • leetCode-hot100-链表专题
  • 【ai】tx2-nx:配置tritonserver2.17.0-jetpack4.6 环境并运行例子
  • Spring和Spring Boot常用注解介绍及使用
  • 【计算机毕业设计】211校园约拍微信小程序
  • 笨蛋学算法之LeetCodeHot100_1_两数之和(Java)
  • 用ip link add link命令创建vlan子设备
  • AD复用布局布线
  • 【深度学习驱动流体力学】采集OpenFOAM仿真的流体力学数据送入到强化学习DQN模型训练
  • 国内公开数据
  • QT QByteArray 的用法
  • InPixio Photo Cutter v10 解锁版安装教程 (懒人抠图工具)
  • Java17 --- SpringSecurity之OAuth2
  • 服务器上线的一些事
  • OceanBase-docker安装、连接数据库、修改mysql用户密码
  • 浪潮(Inspur)服务器硬件监控指标解读
  • 极简opencv操作xml文件
  • 更换域名流程记录
  • CSS 实现电影信息卡片
  • Skype机器人
  • 海外仓系统能解决海外仓哪些难题?海外仓标准化管理实用指南
  • 从零开始精通Onvif之录像存储
  • vue3面试题八股集合——2024
  • 第2章 Rust初体验5/8:match表达式和模式匹配:更富表达力:猜骰子冷热游戏
  • 1台UG图形工作站实现5-7人共享使用
  • Dubbo 3.x源码(22)—Dubbo服务引用源码(5)服务引用bean的获取以及懒加载原理
  • nodejs——原型链污染
  • 忘记 iPhone 密码:如果忘记密码,如何解锁 iPhone