谷粒商城商品上架(二十)
128 商城业务-商品上架-sku在es中存储模型分析-135 商城业务-商品上架-抽取响应结果&上架测试完成
主要踩的坑就是上一篇的博客,当数据放到R中,由于是HashMap结构,数据根本拿不到,具体可以看上一篇博客
https://www.cnblogs.com/dalianpai/p/13155540.html
下面就贴一些主要的代码,后面项目跑起来,在提交到码云上。
GET /product/_search PUT product { "mappings":{ "properties": { "skuId":{ "type":"long" }, "spuId":{ "type":"keyword" }, "skuTitle":{ "type":"text", "analyzer": "ik_smart" }, "skuPrice":{ "type":"keyword" }, "skuImg":{ "type":"keyword", "index":false, "doc_values":false }, "saleCount":{ "type":"long" }, "hasStock":{ "type":"boolean" }, "hasScore":{ "type":"long" }, "brandId":{ "type":"long" }, "catalogId":{ "type":"long" }, "brandName":{ "type":"keyword", "index":false, "doc_values":false }, "brandImg":{ "type":"keyword", "index":false, "doc_values":false }, "catalogName":{ "type":"keyword", "index":false, "doc_values":false }, "attrs":{ "type":"nested", "properties": { "attrId":{ "type":"long" }, "attrName":{ "type":"keyword", "index":false, "doc_values":false }, "attrValue":{ "type":"keyword" } } } } } }
上传的主方法
@Override public void up(Long spuId) { List<SkuInfoEntity> skuInfoEntities =skuInfoService.getSkusBySpuId(spuId); // List<SkuEsModel> uoProducts = new ArrayList<>(); List<Long> skuIdList = skuInfoEntities.stream().map(SkuInfoEntity::getSkuId).collect(Collectors.toList()); List<ProductAttrValueEntity> baseAttrs = attrValueService.baseAttrlistforspu(spuId); List<Long> attrIds = baseAttrs.stream().map(ProductAttrValueEntity::getAttrId).collect(Collectors.toList()); List<Long> searchAttrIds = attrService.selectSearchAttrIds(attrIds); Set<Long> idSet = new HashSet<>(searchAttrIds); List<SkuEsModel.Attrs> attrsList = baseAttrs.stream().filter(item -> idSet.contains(item.getAttrId())) .map(item -> { SkuEsModel.Attrs attrs1 = new SkuEsModel.Attrs(); BeanUtils.copyProperties(item, attrs1); return attrs1; }).collect(Collectors.toList()); //Feign的远程调用 Map<Long, Boolean> stockMap = null; try { R r = wareFeignService.getSkusHasStock(skuIdList); TypeReference<List<SkuHasStockVo>> typeReference = new TypeReference<List<SkuHasStockVo>>() {}; stockMap = r.getData(typeReference).stream().collect(Collectors.toMap(SkuHasStockVo::getSkuId, SkuHasStockVo::getHasStock)); System.out.println(stockMap); }catch (Exception e){ log.error("库存远程调用异常,原因:{}",e); } Map<Long, Boolean> finalStockMap = stockMap; List<SkuEsModel> upProducts = skuInfoEntities.stream().map(sku -> { SkuEsModel esModel = new SkuEsModel(); BeanUtils.copyProperties(sku, esModel); esModel.setSkuPrice(sku.getPrice()); esModel.setSkuImg(sku.getSkuDefaultImg()); //查询品牌和信息的名字 BrandEntity brandEntity = brandService.getById(esModel.getBrandId()); esModel.setBrandName(brandEntity.getName()); esModel.setBrandImg(brandEntity.getLogo()); CategoryEntity categoryEntity = categoryService.getById(esModel.getCatalogId()); esModel.setCatalogName(categoryEntity.getName()); esModel.setAttrs(attrsList); esModel.setHotScore(0L); if(finalStockMap !=null){ esModel.setHasStock(finalStockMap.get(sku.getSkuId())); }else{ esModel.setHasStock(true); } return esModel; }).collect(Collectors.toList()); //将数据存到es中 R r = searchFeignService.productStatusUp(upProducts); if(r.getCode() ==0){ //修改上架的状态 baseMapper.updateSpuStatus(spuId, ProductConstant.StatusEnum.SPU_UP.getCode()); }else{ } } }
最好把每个服务的超时时间设置一下,不然第一次调用或者断点,很容易超时
feign: client: config: service-product: readTimeout: 6000 connectTimeout: 6000 loggerLevel: FULL
下面的代码就是ES插入的代码
@RequestMapping("/search/save") @RestController @Slf4j public class ElasticSaveController { @Autowired ProductSaveService productSaveService; @PostMapping("/product") public R productStatusUp(@RequestBody List<SkuEsModel> skuEsModels) { Boolean b = null; try { b = productSaveService.productStatusUp(skuEsModels); } catch (IOException e) { log.error("ElasticSaveController商品上架异常;{}",e); return R.error(BizCodeEnume.PRODUCT_UP_EXCEPTION.getCode(),BizCodeEnume.PRODUCT_UP_EXCEPTION.getMessage()); } if(!b){ return R.ok(); }else{ return R.error(BizCodeEnume.PRODUCT_UP_EXCEPTION.getCode(),BizCodeEnume.PRODUCT_UP_EXCEPTION.getMessage()); } } }
@Slf4j @Service public class ProductSaveServiceImpl implements ProductSaveService { @Autowired RestHighLevelClient restHighLevelClient; @Override public Boolean productStatusUp(List<SkuEsModel> skuEsModels) throws IOException { //1.先给es创建索引 //BulkRequest bulkRequest, RequestOptions options BulkRequest bulkRequest = new BulkRequest(); for (SkuEsModel model:skuEsModels){ IndexRequest indexRequest = new IndexRequest(EsConstant.PRODUCT_INDEX); indexRequest.id(model.getSkuId().toString()); String s = JSON.toJSONString(model); indexRequest.source(s, XContentType.JSON); bulkRequest.add(indexRequest); } BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, GulimallElasticSearchConfig.COMMON_OPTIONS); // boolean b = bulk.hasFailures(); List<String> collect = Arrays.stream(bulk.getItems()).map(item -> { return item.getId(); }).collect(Collectors.toList()); log.info("商品上架成功:{}",collect); return b; } }
配置类
/** * @author WGR * @create 2020/6/16 -- 17:16 */ @Configuration public class GulimallElasticSearchConfig { public static final RequestOptions COMMON_OPTIONS; static { RequestOptions.Builder builder = RequestOptions.DEFAULT.toBuilder(); // builder.addHeader("Authorization", "Bearer " + TOKEN); // builder.setHttpAsyncResponseConsumerFactory( // new HttpAsyncResponseConsumerFactory // .HeapBufferedResponseConsumerFactory(30 * 1024 * 1024 * 1024)); COMMON_OPTIONS = builder.build(); } @Bean public RestHighLevelClient esRestClient(){ RestHighLevelClient client = new RestHighLevelClient( RestClient.builder( new HttpHost("192.168.1.119", 9200, "http"))); return client; } }
仓库的服务类
@Override public List<SkuHasStockVo> getSkusHasStock(List<Long> skuIds) { List<SkuHasStockVo> hasStockVoList = skuIds.stream().map(id -> { SkuHasStockVo vo = new SkuHasStockVo(); Long count = baseMapper.getSkuStock(id); vo.setSkuId(id); vo.setHasStock(count ==null ?false:count > 0); return vo; }).collect(Collectors.toList()); return hasStockVoList; }
修改后的R类
public class R extends HashMap<String, Object> { private static final long serialVersionUID = 1L; public R setData(Object data) { put("data", data); return this; } ///利用fastjson进行逆转 public <T> T getData(TypeReference<T> typeReference){ Object data = get("data");//默认是map String s = JSON.toJSONString(data); T t = JSON.parseObject(s, typeReference); return t; }
部分截图