当前位置:   article > 正文

谷粒商城【成神路】-【8】——商品上架

谷粒商城【成神路】-【8】——商品上架

目录

1.数据模型封装

1.es数据模型

2.将es数据模型封装为JAVA bean

3.根据前端发送请求,编写controller

2.模型实现

2.1服务controller

2.2服务service

2.3服务远程调用接口

2.4检索服务controller

2.5检索服务保存到es 

 2.6库存查询服务


1.数据模型封装

1.es数据模型

注意自己的es内存设置,不然后面出错

  1. PUT product
  2. {
  3. "mappings": {
  4. "properties": {
  5. "skuId": {
  6. "type": "long"
  7. },
  8. "spuId": {
  9. "type": "keyword"
  10. },
  11. "skuTitle": {
  12. "type": "text",
  13. "analyzer": "ik_smart"
  14. },
  15. "skuPrice": {
  16. "type": "keyword"
  17. },
  18. "skuImg": {
  19. "type": "keyword",
  20. "index": false,
  21. "doc_values": false
  22. },
  23. "saleCount": {
  24. "type": "long"
  25. },
  26. "hasStock": {
  27. "type": "boolean"
  28. },
  29. "hotScore": {
  30. "type": "long"
  31. },
  32. "brandId": {
  33. "type": "long"
  34. },
  35. "catalogId": {
  36. "type": "long"
  37. },
  38. "brandName": {
  39. "type": "keyword",
  40. "index": false,
  41. "doc_values": false
  42. },
  43. "brandImg": {
  44. "type": "keyword",
  45. "index": false,
  46. "doc_values": false
  47. },
  48. "catalogName": {
  49. "type": "keyword",
  50. "index": false,
  51. "doc_values": false
  52. },
  53. "attrs": {
  54. "type": "nested",
  55. "properties": {
  56. "attrId": {
  57. "type": "long"
  58. },
  59. "attrName": {
  60. "type": "keyword",
  61. "index": false,
  62. "doc_values": false
  63. },
  64. "attrValue": {
  65. "type": "keyword"
  66. }
  67. }
  68. }
  69. }
  70. }
  71. }

2.将es数据模型封装为JAVA bean

根据数据模型进行转换,转换为java实体类

  1. @Data
  2. public class SkuEsMode {
  3. private Long skuId;
  4. private Long spuId;
  5. private String skuTitle;
  6. private BigDecimal skuPrice;
  7. private String skuImg;
  8. private Long saleCount;
  9. private Boolean hasStock;
  10. private Long hotScore;
  11. private Long brandId;
  12. private Long catalogId;
  13. private String brandName;
  14. private String brandImg;
  15. private String catalogName;
  16. private List<Attrs> attrs;
  17. @Data
  18. public static class Attrs {
  19. private Long attrId;
  20. private String attrName;
  21. private String attrValue;
  22. }
  23. }

3.根据前端发送请求,编写controller

2.模型实现

2.1服务controller

  1. @PostMapping("/{spuId}/up")
  2. public R spuUp(@PathVariable("spuId") Long spuId){
  3. spuInfoService.up(spuId);
  4. return R.ok();
  5. }

2.2服务service

业务逻辑实现,使用openfeign远程调用检索服务和库存服务

  1. /**
  2. * 商品上架
  3. *
  4. * @param spuId
  5. */
  6. @Override
  7. public void up(Long spuId) {
  8. //1.查出当前spuId对应的所有sku信息、品牌的名字
  9. List<SkuInfoEntity> skus = skuInfoService.getSkusBySpuId(spuId);
  10. List<Long> skuIdList = skus.stream().map(SkuInfoEntity::getSkuId).collect(Collectors.toList());
  11. //TODO 查询当前sku的所有规格属性
  12. List<ProductAttrValueEntity> baseAttrs = attrValueService.baseAttrListForSpu(spuId);
  13. List<Long> attrIds = baseAttrs.stream().map(attr -> {
  14. return attr.getAttrId();
  15. }).collect(Collectors.toList());
  16. List<Long> searchAttrIds = attrService.selectSearchAttrs(attrIds);
  17. Set<Long> idSet = new HashSet<>(searchAttrIds);
  18. List<SkuEsMode.Attrs> attrsList = baseAttrs.stream().filter(item -> {
  19. return idSet.contains(item.getAttrId());
  20. }).map(item -> {
  21. SkuEsMode.Attrs attrs1 = new SkuEsMode.Attrs();
  22. BeanUtils.copyProperties(item, attrs1);
  23. return attrs1;
  24. }).collect(Collectors.toList());
  25. //TODO 发送远程调用,查询是否有库存
  26. Map<Long, Boolean> stockMap = null;
  27. try {
  28. R r = wareFeignService.getSkuHasStock(skuIdList);
  29. TypeReference<List<SkuHasStockVo>> typeReference = new TypeReference<List<SkuHasStockVo>>() {};
  30. stockMap = r.getData(typeReference).stream().collect(Collectors.toMap(SkuHasStockVo::getSkuId, item -> item.getHasStock()));
  31. } catch (Exception e) {
  32. log.error("库存服务查询异常:原因{}", e);
  33. }
  34. //2.封装每个sku的信息
  35. Map<Long, Boolean> finalStockMap = stockMap;
  36. List<SkuEsMode> uoProducts = skus.stream().map(sku -> {
  37. //组装需要的数据
  38. SkuEsMode esMode = new SkuEsMode();
  39. //属性对拷
  40. BeanUtils.copyProperties(sku, esMode);
  41. esMode.setSkuPrice(sku.getPrice());
  42. esMode.setSkuImg(sku.getSkuDefaultImg());
  43. //设置库存信息
  44. if (finalStockMap == null) {
  45. esMode.setHasStock(true);
  46. }else {
  47. esMode.setHasStock(finalStockMap.get(sku.getSkuId()));
  48. }
  49. //TODO 热度评分
  50. esMode.setHotScore(0L);
  51. //TODO 查询品牌和分类的名字的信息
  52. BrandEntity brand = brandService.getById(esMode.getBrandId());
  53. esMode.setBrandName(brand.getName());
  54. esMode.setBrandImg(brand.getLogo());
  55. CategoryEntity category = categoryService.getById(esMode.getCatalogId());
  56. esMode.setCatalogName(category.getName());
  57. //设置检索属性
  58. esMode.setAttrs(attrsList);
  59. return esMode;
  60. }).collect(Collectors.toList());
  61. //TODO 发送es进行保存:gulimall-search
  62. R r = searchFeignService.productStatusUp(uoProducts);
  63. if (r.getCode()==0){
  64. //调用成功
  65. //TODO 修改spu状态
  66. baseMapper.updateSpuStatus(spuId, ProductConstant.StatusEnum.SPU_UP.getCode());
  67. }else {
  68. //调用失败
  69. //TODO 重复调用
  70. }
  71. }

2.3服务远程调用接口

在商品服务中,创建feign接口,一定要使用@FeignClient指定nacos上的服务名称

  1. @FeignClient("gulimall-ware")
  2. public interface WareFeignService {
  3. @PostMapping("/ware/waresku/hasStock")
  4. R getSkuHasStock(@RequestBody List<Long> skuIds);
  5. }
  6. @FeignClient("gulimall-search")
  7. public interface SearchFeignService {
  8. @PostMapping("/search/save/product")
  9. public R productStatusUp(@RequestBody List<SkuEsMode> skuEsModes);
  10. }

2.4检索服务controller

  1. @Slf4j
  2. @RequestMapping("/search/save")
  3. @RestController
  4. public class ElasticSaveController {
  5. @Autowired
  6. ProductSaveService productSaveService;
  7. //上架商品
  8. @PostMapping("/product")
  9. public R productStatusUp(@RequestBody List<SkuEsMode> skuEsModes) {
  10. Boolean b = false;
  11. try {
  12. b = productSaveService.productStatusUp(skuEsModes);
  13. } catch (IOException e) {
  14. log.error("商品上架错误:{}", e);
  15. return R.error(BizCodeEnume.PRODUCT_UP_EXCEPTION.getCode(), BizCodeEnume.PRODUCT_UP_EXCEPTION.getMsg());
  16. }
  17. if (!b) {
  18. return R.ok();
  19. } else {
  20. return R.error(BizCodeEnume.PRODUCT_UP_EXCEPTION.getCode(), BizCodeEnume.PRODUCT_UP_EXCEPTION.getMsg());
  21. }
  22. }
  23. }

2.5检索服务保存到es 

  1. @Slf4j
  2. @Service
  3. public class ProductSaveServiceImpl implements ProductSaveService {
  4. @Autowired
  5. RestHighLevelClient restHighLevelClient;
  6. @Override
  7. public Boolean productStatusUp(List<SkuEsMode> skuEsModes) throws IOException {
  8. //保存到es
  9. //给es建立索引
  10. //1.给es建立映射关系
  11. //2.给es中保存这些数据
  12. BulkRequest bulkRequest = new BulkRequest();
  13. for (SkuEsMode model : skuEsModes) {
  14. //构造保存请求
  15. IndexRequest indexRequest = new IndexRequest(EsConstant.PRODUCT_INDEX);
  16. indexRequest.id(model.getSkuId().toString());
  17. String jsonString = JSON.toJSONString(model);
  18. indexRequest.source(jsonString, XContentType.JSON);
  19. bulkRequest.add(indexRequest);
  20. }
  21. BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, ElasticSearchConfig.COMMON_OPTIONS);
  22. //TODO 错误处理
  23. boolean b = bulk.hasFailures();
  24. List<String> collect = Arrays.stream(bulk.getItems()).map(item -> {
  25. return item.getId();
  26. }).collect(Collectors.toList());
  27. log.info("商品上架完成:{},返回数据:{}", collect,bulk.toString());
  28. return b;
  29. }
  30. }

 2.6库存查询服务

  1. @Override
  2. public void addStock(Long skuId, Long wareId, Integer skuNum) {
  3. //1.判断如果还没有库存记录。那就是新增操作,如果有,才更新
  4. List<WareSkuEntity> entities = wareSkuDao.selectList(new QueryWrapper<WareSkuEntity>().eq("sku_id", skuId).eq("ware_id", wareId));
  5. if (entities == null || entities.size() == 0) {
  6. WareSkuEntity skuEntity = new WareSkuEntity();
  7. skuEntity.setSkuId(skuId);
  8. skuEntity.setStock(skuNum);
  9. skuEntity.setWareId(wareId);
  10. skuEntity.setStockLocked(0);
  11. // TODO 远程查询sku的名字,如果失败整个事务无需回滚
  12. //1.自己catch调异常
  13. // TODO 还可以异常出现以后不会回滚
  14. try {
  15. R info = productFeignService.info(skuId);
  16. if (info.getCode() == 0) {
  17. Map<String, Object> data = (Map<String, Object>) info.get("skuInfo");
  18. skuEntity.setSkuName((String) data.get("skuName"));
  19. }
  20. } catch (Exception e) {
  21. }
  22. wareSkuDao.insert(skuEntity);
  23. } else {
  24. wareSkuDao.addStock(skuId, wareId, skuNum);
  25. }
  26. }

 

注意事项:启动nacos服务注册中心,并且启动elasticsearch,保证容量

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/羊村懒王/article/detail/191205
推荐阅读
相关标签
  

闽ICP备14008679号