目录
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内存设置,不然后面出错
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"
},
"hotScore": {
"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"
}
}
}
}
}
}
2.将es数据模型封装为JAVA bean
根据数据模型进行转换,转换为java实体类
@Data
public class SkuEsMode {
private Long skuId;
private Long spuId;
private String skuTitle;
private BigDecimal skuPrice;
private String skuImg;
private Long saleCount;
private Boolean hasStock;
private Long hotScore;
private Long brandId;
private Long catalogId;
private String brandName;
private String brandImg;
private String catalogName;
private List<Attrs> attrs;
@Data
public static class Attrs {
private Long attrId;
private String attrName;
private String attrValue;
}
}
3.根据前端发送请求,编写controller
2.模型实现
2.1服务controller
@PostMapping("/{spuId}/up")
public R spuUp(@PathVariable("spuId") Long spuId){
spuInfoService.up(spuId);
return R.ok();
}
2.2服务service
业务逻辑实现,使用openfeign远程调用检索服务和库存服务
/**
* 商品上架
*
* @param spuId
*/
@Override
public void up(Long spuId) {
//1.查出当前spuId对应的所有sku信息、品牌的名字
List<SkuInfoEntity> skus = skuInfoService.getSkusBySpuId(spuId);
List<Long> skuIdList = skus.stream().map(SkuInfoEntity::getSkuId).collect(Collectors.toList());
//TODO 查询当前sku的所有规格属性
List<ProductAttrValueEntity> baseAttrs = attrValueService.baseAttrListForSpu(spuId);
List<Long> attrIds = baseAttrs.stream().map(attr -> {
return attr.getAttrId();
}).collect(Collectors.toList());
List<Long> searchAttrIds = attrService.selectSearchAttrs(attrIds);
Set<Long> idSet = new HashSet<>(searchAttrIds);
List<SkuEsMode.Attrs> attrsList = baseAttrs.stream().filter(item -> {
return idSet.contains(item.getAttrId());
}).map(item -> {
SkuEsMode.Attrs attrs1 = new SkuEsMode.Attrs();
BeanUtils.copyProperties(item, attrs1);
return attrs1;
}).collect(Collectors.toList());
//TODO 发送远程调用,查询是否有库存
Map<Long, Boolean> stockMap = null;
try {
R r = wareFeignService.getSkuHasStock(skuIdList);
TypeReference<List<SkuHasStockVo>> typeReference = new TypeReference<List<SkuHasStockVo>>() {};
stockMap = r.getData(typeReference).stream().collect(Collectors.toMap(SkuHasStockVo::getSkuId, item -> item.getHasStock()));
} catch (Exception e) {
log.error("库存服务查询异常:原因{}", e);
}
//2.封装每个sku的信息
Map<Long, Boolean> finalStockMap = stockMap;
List<SkuEsMode> uoProducts = skus.stream().map(sku -> {
//组装需要的数据
SkuEsMode esMode = new SkuEsMode();
//属性对拷
BeanUtils.copyProperties(sku, esMode);
esMode.setSkuPrice(sku.getPrice());
esMode.setSkuImg(sku.getSkuDefaultImg());
//设置库存信息
if (finalStockMap == null) {
esMode.setHasStock(true);
}else {
esMode.setHasStock(finalStockMap.get(sku.getSkuId()));
}
//TODO 热度评分
esMode.setHotScore(0L);
//TODO 查询品牌和分类的名字的信息
BrandEntity brand = brandService.getById(esMode.getBrandId());
esMode.setBrandName(brand.getName());
esMode.setBrandImg(brand.getLogo());
CategoryEntity category = categoryService.getById(esMode.getCatalogId());
esMode.setCatalogName(category.getName());
//设置检索属性
esMode.setAttrs(attrsList);
return esMode;
}).collect(Collectors.toList());
//TODO 发送es进行保存:gulimall-search
R r = searchFeignService.productStatusUp(uoProducts);
if (r.getCode()==0){
//调用成功
//TODO 修改spu状态
baseMapper.updateSpuStatus(spuId, ProductConstant.StatusEnum.SPU_UP.getCode());
}else {
//调用失败
//TODO 重复调用
}
}
2.3服务远程调用接口
在商品服务中,创建feign接口,一定要使用@FeignClient指定nacos上的服务名称
@FeignClient("gulimall-ware")
public interface WareFeignService {
@PostMapping("/ware/waresku/hasStock")
R getSkuHasStock(@RequestBody List<Long> skuIds);
}
@FeignClient("gulimall-search")
public interface SearchFeignService {
@PostMapping("/search/save/product")
public R productStatusUp(@RequestBody List<SkuEsMode> skuEsModes);
}
2.4检索服务controller
@Slf4j
@RequestMapping("/search/save")
@RestController
public class ElasticSaveController {
@Autowired
ProductSaveService productSaveService;
//上架商品
@PostMapping("/product")
public R productStatusUp(@RequestBody List<SkuEsMode> skuEsModes) {
Boolean b = false;
try {
b = productSaveService.productStatusUp(skuEsModes);
} catch (IOException e) {
log.error("商品上架错误:{}", e);
return R.error(BizCodeEnume.PRODUCT_UP_EXCEPTION.getCode(), BizCodeEnume.PRODUCT_UP_EXCEPTION.getMsg());
}
if (!b) {
return R.ok();
} else {
return R.error(BizCodeEnume.PRODUCT_UP_EXCEPTION.getCode(), BizCodeEnume.PRODUCT_UP_EXCEPTION.getMsg());
}
}
}
2.5检索服务保存到es
@Slf4j
@Service
public class ProductSaveServiceImpl implements ProductSaveService {
@Autowired
RestHighLevelClient restHighLevelClient;
@Override
public Boolean productStatusUp(List<SkuEsMode> skuEsModes) throws IOException {
//保存到es
//给es建立索引
//1.给es建立映射关系
//2.给es中保存这些数据
BulkRequest bulkRequest = new BulkRequest();
for (SkuEsMode model : skuEsModes) {
//构造保存请求
IndexRequest indexRequest = new IndexRequest(EsConstant.PRODUCT_INDEX);
indexRequest.id(model.getSkuId().toString());
String jsonString = JSON.toJSONString(model);
indexRequest.source(jsonString, XContentType.JSON);
bulkRequest.add(indexRequest);
}
BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, ElasticSearchConfig.COMMON_OPTIONS);
//TODO 错误处理
boolean b = bulk.hasFailures();
List<String> collect = Arrays.stream(bulk.getItems()).map(item -> {
return item.getId();
}).collect(Collectors.toList());
log.info("商品上架完成:{},返回数据:{}", collect,bulk.toString());
return b;
}
}
2.6库存查询服务
@Override
public void addStock(Long skuId, Long wareId, Integer skuNum) {
//1.判断如果还没有库存记录。那就是新增操作,如果有,才更新
List<WareSkuEntity> entities = wareSkuDao.selectList(new QueryWrapper<WareSkuEntity>().eq("sku_id", skuId).eq("ware_id", wareId));
if (entities == null || entities.size() == 0) {
WareSkuEntity skuEntity = new WareSkuEntity();
skuEntity.setSkuId(skuId);
skuEntity.setStock(skuNum);
skuEntity.setWareId(wareId);
skuEntity.setStockLocked(0);
// TODO 远程查询sku的名字,如果失败整个事务无需回滚
//1.自己catch调异常
// TODO 还可以异常出现以后不会回滚
try {
R info = productFeignService.info(skuId);
if (info.getCode() == 0) {
Map<String, Object> data = (Map<String, Object>) info.get("skuInfo");
skuEntity.setSkuName((String) data.get("skuName"));
}
} catch (Exception e) {
}
wareSkuDao.insert(skuEntity);
} else {
wareSkuDao.addStock(skuId, wareId, skuNum);
}
}
注意事项:启动nacos服务注册中心,并且启动elasticsearch,保证容量