1、商城服务商品上架功能实现,使用ES做检索

2、巨坑,es的maven坐标版本需要一直,否则报错。
详情看:https://blog.csdn.net/CSDN877425287/article/details/107287531
This commit is contained in:
xjs 2022-04-06 17:03:12 +08:00
parent 02881dd139
commit bc81cc344a
33 changed files with 698 additions and 49 deletions

View File

@ -51,7 +51,7 @@
<oshi.version>5.7.1</oshi.version> <oshi.version>5.7.1</oshi.version>
<webmagic.version>0.7.5</webmagic.version> <webmagic.version>0.7.5</webmagic.version>
<spring-cloud-alicloud-oss.version>2.2.0.RELEASE</spring-cloud-alicloud-oss.version> <spring-cloud-alicloud-oss.version>2.2.0.RELEASE</spring-cloud-alicloud-oss.version>
<elasticsearch.version>7.2.0</elasticsearch.version> <elasticsearch.version>7.12.1</elasticsearch.version>
</properties> </properties>

View File

@ -0,0 +1,24 @@
package com.xjs.mall;
import com.ruoyi.common.core.constant.ServiceNameConstants;
import com.xjs.mall.other.R;
import com.xjs.mall.to.es.SkuEsModel;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import java.util.List;
/**
* 检索服务feign
* @author xiejs
* @since 2022-04-06
*/
@FeignClient(contextId = "remoteSearchFeign",
value = ServiceNameConstants.MALL_SEARCH_SERVICE)
public interface RemoteSearchFeign {
@PostMapping("/search/product")
R productStatusUp(@RequestBody List<SkuEsModel> skuEsModelList);
}

View File

@ -0,0 +1,22 @@
package com.xjs.mall;
import com.ruoyi.common.core.constant.ServiceNameConstants;
import com.xjs.mall.to.SkuHasStockVo;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import java.util.List;
/**
* 仓库服务feign
* @author xiejs
* @since 2022-04-06
*/
@FeignClient(contextId = "remoteWareFeign",
value = ServiceNameConstants.MALL_WARE_SERVICE)
public interface RemoteWareFeign {
@PostMapping("/ware/waresku/hasStock")
List<SkuHasStockVo> getSkuHasStock(@RequestBody List<Long> skuIds);
}

View File

@ -0,0 +1,21 @@
package com.xjs.mall.to;
import lombok.Data;
/**
* sku库存查询vo
* @author xiejs
* @since 2022-04-06
*/
@Data
public class SkuHasStockVo {
/**
* sku id
*/
private Long skuId;
/**
* 是否有库存
*/
private Boolean hasStock;
}

View File

@ -0,0 +1,104 @@
package com.xjs.mall.to.es;
import lombok.Data;
import java.math.BigDecimal;
import java.util.List;
/**
* spu es 模型
* @author xiejs
* @since 2022-04-06
*/
@Data
public class SkuEsModel {
/**
* 商品sku id
*/
private Long skuId;
/**
* 商品spu id
*/
private Long spuId;
/**
* sku标题
*/
private String skuTitle;
/**
* sku价格
*/
private BigDecimal skuPrice;
/**
* sku默认图片
*/
private String skuImg;
/**
* 销量
*/
private Long saleCount;
/**
* 是否拥有库存
*/
private Boolean hasStock;
/**
* 热度评分
*/
private Long hotScore;
/**
* 品牌id
*/
private Long brandId;
/**
* 分类id
*/
private Long catalogId;
/**
* 品牌名
*/
private String brandName;
/**
* 品牌logo
*/
private String brandImg;
/**
* 分类名
*/
private String catalogName;
private List<Attrs> attrs;
@Data
public static class Attrs{
/**
* 属性id
*/
private Long attrId;
/**
* 属性名
*/
private String attrName;
/**
* 属性值
*/
private String attrValue;
}
}

View File

@ -52,5 +52,17 @@ public class ServiceNameConstants {
*/ */
public static final String MALL_PRODUCT_SERVICE = "xjs-mall-product"; public static final String MALL_PRODUCT_SERVICE = "xjs-mall-product";
/**
* 仓库服务的serviceid
*/
public static final String MALL_WARE_SERVICE = "xjs-mall-ware";
/**
* 检索服务的serviceid
*/
public static final String MALL_SEARCH_SERVICE = "xjs-mall-search";
} }

View File

@ -18,3 +18,12 @@ export function getSpuList(data) {
}) })
} }
// 商品上架
export function spuUp(spuId) {
return request({
url: `/mall-product/product/spuinfo/${spuId}/up`,
method: 'post',
})
}

View File

@ -8,28 +8,38 @@
style="width: 100%;" style="width: 100%;"
> >
<el-table-column type="selection" header-align="center" align="center" width="50"></el-table-column> <el-table-column type="selection" header-align="center" align="center" width="50"></el-table-column>
<el-table-column prop="spuName" header-align="center" align="center" label="名称" :show-overflow-tooltip="true"></el-table-column> <el-table-column prop="spuName" header-align="center" align="center" label="名称"
<el-table-column prop="spuDescription" header-align="center" align="center" label="描述" :show-overflow-tooltip="true"></el-table-column> :show-overflow-tooltip="true"></el-table-column>
<el-table-column prop="catalogName" header-align="center" align="center" label="分类" :show-overflow-tooltip="true"></el-table-column> <el-table-column prop="spuDescription" header-align="center" align="center" label="描述"
<el-table-column prop="brandName" header-align="center" align="center" label="品牌" :show-overflow-tooltip="true"></el-table-column> :show-overflow-tooltip="true"></el-table-column>
<el-table-column prop="weight" header-align="center" align="center" width="80px" label="重量(kg)" :show-overflow-tooltip="true"></el-table-column> <el-table-column prop="catalogName" header-align="center" align="center" label="分类"
<el-table-column prop="publishStatus" header-align="center" width="80px" align="center" label="上架状态" :show-overflow-tooltip="true"> :show-overflow-tooltip="true"></el-table-column>
<el-table-column prop="brandName" header-align="center" align="center" label="品牌"
:show-overflow-tooltip="true"></el-table-column>
<el-table-column prop="weight" header-align="center" align="center" width="80px" label="重量(kg)"
:show-overflow-tooltip="true"></el-table-column>
<el-table-column prop="publishStatus" header-align="center" width="80px" align="center" label="上架状态"
:show-overflow-tooltip="true">
<template slot-scope="scope"> <template slot-scope="scope">
<el-tag v-if="scope.row.publishStatus === 0">新建</el-tag> <el-tag v-if="scope.row.publishStatus === 0">新建</el-tag>
<el-tag v-if="scope.row.publishStatus === 1">已上架</el-tag> <el-tag v-if="scope.row.publishStatus === 1">已上架</el-tag>
<el-tag v-if="scope.row.publishStatus === 2">已下架</el-tag> <el-tag v-if="scope.row.publishStatus === 2">已下架</el-tag>
</template> </template>
</el-table-column> </el-table-column>
<el-table-column prop="createTime" header-align="center" align="center" label="创建时间" :show-overflow-tooltip="true"></el-table-column> <el-table-column prop="createTime" header-align="center" align="center" label="创建时间"
<el-table-column prop="updateTime" header-align="center" align="center" label="修改时间" :show-overflow-tooltip="true"></el-table-column> :show-overflow-tooltip="true"></el-table-column>
<el-table-column fixed="right" header-align="center" align="center" width="150" label="操作" :show-overflow-tooltip="true"> <el-table-column prop="updateTime" header-align="center" align="center" label="修改时间"
:show-overflow-tooltip="true"></el-table-column>
<el-table-column fixed="right" header-align="center" align="center" width="150" label="操作"
:show-overflow-tooltip="true">
<template slot-scope="scope"> <template slot-scope="scope">
<el-button <el-button
v-if="scope.row.publishStatus === 0" v-if="scope.row.publishStatus === 0"
type="text" type="text"
size="small" size="small"
@click="productUp(scope.row.id)" @click="productUp(scope.row.id)"
>上架</el-button> >上架
</el-button>
<el-button type="text" size="small" @click="attrUpdateShow(scope.row)">规格</el-button> <el-button type="text" size="small" @click="attrUpdateShow(scope.row)">规格</el-button>
</template> </template>
</el-table-column> </el-table-column>
@ -48,7 +58,7 @@
</template> </template>
<script> <script>
import {getSpuList} from "@/api/mall/product/spu-info"; import {getSpuList, spuUp} from "@/api/mall/product/spu-info";
export default { export default {
data() { data() {
@ -71,34 +81,25 @@ export default {
}, },
}, },
components: {}, components: {},
created() { created() {
this.getDataList(); this.getDataList();
}, },
methods: { methods: {
//
productUp(id) { productUp(id) {
this.$http({ this.$modal.loading("商品正在上架中。。。")
url: this.$http.adornUrl("/product/spuinfo/" + id + "/up"), spuUp(id).then(res => {
method: "post" this.$modal.closeLoading()
}).then(({ data }) => { this.$modal.notifySuccess("上架成功")
if (data && data.code === 0) { this.getDataList();
this.$message({ })
message: "操作成功",
type: "success",
duration: 1500,
onClose: () => {
this.getDataList();
}
});
} else {
this.$message.error(data.msg);
}
});
}, },
attrUpdateShow(row) { attrUpdateShow(row) {
this.$router.push({ this.$router.push({
path: "/mall/product/mall-attribute/spu-attribute", path: "/mall/product/mall-attribute/spu-attribute",
query: { spuId: row.id, catalogId: row.catalogId } query: {spuId: row.id, catalogId: row.catalogId}
}); });
}, },
// //
@ -109,7 +110,7 @@ export default {
page: this.pageIndex, page: this.pageIndex,
limit: this.pageSize limit: this.pageSize
}); });
getSpuList(param).then(res =>{ getSpuList(param).then(res => {
this.dataList = res.page.list; this.dataList = res.page.list;
this.totalPage = res.page.totalCount; this.totalPage = res.page.totalCount;
this.dataListLoading = false; this.dataListLoading = false;

View File

@ -0,0 +1,13 @@
package com.xjs.consts;
/**
* ES常量
* @author xiejs
* @since 2022-04-06
*/
public class EsConst {
/**
* sku数据在ES中的索引
*/
public static final String PRODUCT_INDEX = "product";
}

View File

@ -26,4 +26,25 @@ public class ProductConstant {
return msg; return msg;
} }
} }
public enum StatusEnum{
NEW_SPU(0,"新建"),
DWON_SPU(2,"商品下架"),
UP_SPU(1,"商品上架");
private int code;
private String msg;
StatusEnum(int code,String msg){
this.code = code;
this.msg = msg;
}
public int getCode() {
return code;
}
public String getMsg() {
return msg;
}
}
} }

View File

@ -15,6 +15,7 @@ package com.xjs.exception;
*/ */
public enum BizCodeEnume { public enum BizCodeEnume {
UNKNOW_EXCEPTION(10000,"系统未知异常"), UNKNOW_EXCEPTION(10000,"系统未知异常"),
PRODUCT_UP_EXCEPTION(11000,"商品上架异常"),
VAILD_EXCEPTION(10001,"参数格式校验失败"); VAILD_EXCEPTION(10001,"参数格式校验失败");
private int code; private int code;

View File

@ -30,6 +30,13 @@ public class SpuInfoController extends MyBaseController<SpuInfoEntity> {
@Autowired @Autowired
private SpuInfoService spuInfoService; private SpuInfoService spuInfoService;
@ApiOperation("商品上架")
@PostMapping("/{spuId}/up")
public R spuUp(@PathVariable("spuId") Long spuId) {
spuInfoService.up(spuId);
return R.ok();
}
/** /**
* 列表 * 列表
*/ */

View File

@ -2,6 +2,9 @@ package com.xjs.mall.product.dao;
import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.xjs.mall.product.entity.AttrEntity; import com.xjs.mall.product.entity.AttrEntity;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/** /**
* 商品属性 * 商品属性
@ -12,4 +15,5 @@ import com.xjs.mall.product.entity.AttrEntity;
*/ */
public interface AttrDao extends BaseMapper<AttrEntity> { public interface AttrDao extends BaseMapper<AttrEntity> {
List<Long> selectSearchAttrIds(@Param("attrIds") List<Long> attrIds);
} }

View File

@ -2,14 +2,21 @@ package com.xjs.mall.product.dao;
import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.xjs.mall.product.entity.SpuInfoEntity; import com.xjs.mall.product.entity.SpuInfoEntity;
import org.apache.ibatis.annotations.Param;
/** /**
* spu信息 * spu信息
* *
* @author xiejs * @author xiejs
* @email 1294405880@qq.com * @email 1294405880@qq.com
* @date 2022-03-15 10:16:53 * @since 2022-03-15 10:16:53
*/ */
public interface SpuInfoDao extends BaseMapper<SpuInfoEntity> { public interface SpuInfoDao extends BaseMapper<SpuInfoEntity> {
/**
* 修改spu状态
* @param spuId id
* @param code 状态
*/
void updateSpuStatus(@Param("spuId") Long spuId, @Param("code") int code);
} }

View File

@ -78,5 +78,12 @@ public interface AttrService extends IService<AttrEntity> {
* @return page * @return page
*/ */
PageUtils getAttrNoRelation(Map<String, Object> params, Long attrgroupId); PageUtils getAttrNoRelation(Map<String, Object> params, Long attrgroupId);
/**
* 在指定的所有属性集合里面挑出检索属性
* @param attrIds 属性ids
* @return long
*/
List<Long> selectSearchAttrIds(List<Long> attrIds);
} }

View File

@ -4,6 +4,7 @@ import com.baomidou.mybatisplus.extension.service.IService;
import com.xjs.utils.PageUtils; import com.xjs.utils.PageUtils;
import com.xjs.mall.product.entity.SkuInfoEntity; import com.xjs.mall.product.entity.SkuInfoEntity;
import java.util.List;
import java.util.Map; import java.util.Map;
/** /**
@ -28,5 +29,12 @@ public interface SkuInfoService extends IService<SkuInfoEntity> {
* @return page * @return page
*/ */
PageUtils queryPageByCondition(Map<String, Object> params); PageUtils queryPageByCondition(Map<String, Object> params);
/**
* 根据spu获取skus
* @param spuId id
* @return list
*/
List<SkuInfoEntity> getSkusBySpuId(Long spuId);
} }

View File

@ -34,5 +34,11 @@ public interface SpuInfoService extends IService<SpuInfoEntity> {
* @return page * @return page
*/ */
PageUtils queryPageByCondition(Map<String, Object> params); PageUtils queryPageByCondition(Map<String, Object> params);
/**
* 商品上架
* @param spuId id
*/
void up(Long spuId);
} }

View File

@ -250,4 +250,9 @@ public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements
return new PageUtils(page); return new PageUtils(page);
} }
@Override
public List<Long> selectSearchAttrIds(List<Long> attrIds) {
return super.baseMapper.selectSearchAttrIds(attrIds);
}
} }

View File

@ -90,4 +90,11 @@ public class SkuInfoServiceImpl extends ServiceImpl<SkuInfoDao, SkuInfoEntity> i
return pageUtils; return pageUtils;
} }
@Override
public List<SkuInfoEntity> getSkusBySpuId(Long spuId) {
LambdaQueryWrapper<SkuInfoEntity> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(SkuInfoEntity::getSpuId,spuId);
return super.list(wrapper);
}
} }

View File

@ -5,13 +5,19 @@ import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.utils.StringUtils; import com.ruoyi.common.core.utils.StringUtils;
import com.xjs.consts.ProductConstant;
import com.xjs.mall.RemoteCouponFeign; import com.xjs.mall.RemoteCouponFeign;
import com.xjs.mall.RemoteSearchFeign;
import com.xjs.mall.RemoteWareFeign;
import com.xjs.mall.other.R;
import com.xjs.mall.product.dao.SpuInfoDao; import com.xjs.mall.product.dao.SpuInfoDao;
import com.xjs.mall.product.entity.*; import com.xjs.mall.product.entity.*;
import com.xjs.mall.product.service.*; import com.xjs.mall.product.service.*;
import com.xjs.mall.product.vo.spu.*; import com.xjs.mall.product.vo.spu.*;
import com.xjs.mall.to.SkuHasStockVo;
import com.xjs.mall.to.SkuReductionTo; import com.xjs.mall.to.SkuReductionTo;
import com.xjs.mall.to.SpuBoundTo; import com.xjs.mall.to.SpuBoundTo;
import com.xjs.mall.to.es.SkuEsModel;
import com.xjs.utils.PageUtils; import com.xjs.utils.PageUtils;
import com.xjs.utils.Query; import com.xjs.utils.Query;
import org.springframework.beans.BeanUtils; import org.springframework.beans.BeanUtils;
@ -21,9 +27,7 @@ import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource; import javax.annotation.Resource;
import java.math.BigDecimal; import java.math.BigDecimal;
import java.util.Date; import java.util.*;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors; import java.util.stream.Collectors;
@ -49,6 +53,12 @@ public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> i
private CategoryService categoryService; private CategoryService categoryService;
@Autowired @Autowired
private BrandService brandService; private BrandService brandService;
@Autowired
private AttrService attrService;
@Resource
private RemoteWareFeign remoteWareFeign;
@Resource
private RemoteSearchFeign remoteSearchFeign;
@Override @Override
@ -198,5 +208,87 @@ public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> i
return pageUtils; return pageUtils;
} }
@Override
public void up(Long spuId) {
// 1查出当前spuId对应的所有sku信息品牌名字
List<SkuInfoEntity> skus = skuInfoService.getSkusBySpuId(spuId);
// 查询当前sku的所有规格属性
List<ProductAttrValueEntity> baseAttrs = productAttrValueService.baseAtteListForSpu(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> attrList = baseAttrs.stream()
.filter(item ->
idSet.contains(item.getAttrId()))
.map(item -> {
SkuEsModel.Attrs attrs = new SkuEsModel.Attrs();
BeanUtils.copyProperties(item, attrs);
return attrs;
})
.collect(Collectors.toList());
// 发送远程调用 库存系统查询是否有库存
List<Long> skuIds = skus.stream().map(SkuInfoEntity::getSkuId).collect(Collectors.toList());
Map<Long, Boolean> stockMap = null;
try {
List<SkuHasStockVo> stockVoList = remoteWareFeign.getSkuHasStock(skuIds);
stockMap = stockVoList.stream().collect(Collectors.toMap(SkuHasStockVo::getSkuId, SkuHasStockVo::getHasStock));
} catch (Exception e) {
log.error("库存服务查询异常:原因{}", e);
}
// 2封装每个sku的信息
Map<Long, Boolean> finalStockMap = stockMap;
List<SkuEsModel> upProducts = skus.stream().map(sku -> {
//组装需要的数据
SkuEsModel skuEsModel = new SkuEsModel();
BeanUtils.copyProperties(sku, skuEsModel);
//skuPrice,skuImg,hasStock,hotScore
skuEsModel.setSkuPrice(sku.getPrice());
skuEsModel.setSkuImg(sku.getSkuDefaultImg());
//热度评分 0
skuEsModel.setHotScore(0L);
//设置库存信息
if (finalStockMap == null) {
skuEsModel.setHasStock(true);
} else {
skuEsModel.setHasStock(finalStockMap.get(sku.getSkuId()));
}
//查询品牌分类的名字信息
BrandEntity brandEntity = brandService.getById(skuEsModel.getBrandId());
skuEsModel.setBrandName(brandEntity.getName());
skuEsModel.setBrandImg(brandEntity.getLogo());
CategoryEntity categoryEntity = categoryService.getById(skuEsModel.getCatalogId());
skuEsModel.setCatalogName(categoryEntity.getName());
//设置检索属性
skuEsModel.setAttrs(attrList);
return skuEsModel;
}).collect(Collectors.toList());
// 将数据发送给es进行保存
R r = remoteSearchFeign.productStatusUp(upProducts);
if (r.getCode() == 0) {
//远程调用成功
//修改当前spu的状态
super.baseMapper.updateSpuStatus(spuId, ProductConstant.StatusEnum.UP_SPU.getCode());
} else {
//远程调用失败
// todo 重复调用,接口幂等性,重试机制
}
}
} }

View File

@ -16,6 +16,13 @@
<result property="catelogId" column="catelog_id"/> <result property="catelogId" column="catelog_id"/>
<result property="showDesc" column="show_desc"/> <result property="showDesc" column="show_desc"/>
</resultMap> </resultMap>
<select id="selectSearchAttrIds" resultType="java.lang.Long">
select attr_id from pms_attr where attr_id in
<foreach collection="attrIds" item="id" separator="," open="(" close=")">
#{id}
</foreach>
and search_type = 1
</select>
</mapper> </mapper>

View File

@ -15,6 +15,10 @@
<result property="createTime" column="create_time"/> <result property="createTime" column="create_time"/>
<result property="updateTime" column="update_time"/> <result property="updateTime" column="update_time"/>
</resultMap> </resultMap>
<update id="updateSpuStatus">
update pms_spu_info set publish_status = #{code},update_time=NOW()
where id =#{spuId}
</update>
</mapper> </mapper>

View File

@ -37,22 +37,17 @@ public class ElasticsearchConfig {
private String scheme; private String scheme;
public static final RequestOptions COMMON_OPTIONS; public static RequestOptions COMMON_OPTIONS;
static { static {
RequestOptions.Builder builder = RequestOptions.DEFAULT.toBuilder(); COMMON_OPTIONS = RequestOptions.DEFAULT.toBuilder().build();
//配置项.......
COMMON_OPTIONS = builder.build();
} }
@Bean @Bean
public RestHighLevelClient restHighLevelClient() { public RestHighLevelClient restHighLevelClient() {
RestClientBuilder builder = RestClient.builder(new HttpHost(ip, port, scheme)); RestClientBuilder builder = RestClient.builder(new HttpHost(ip, port, scheme));
RestHighLevelClient restHighLevelClient = new RestHighLevelClient(builder); return new RestHighLevelClient(builder);
return restHighLevelClient;
} }
} }

View File

@ -0,0 +1,52 @@
package com.xjs.mall.search.controller;
import com.xjs.exception.BizCodeEnume;
import com.xjs.mall.other.R;
import com.xjs.mall.search.service.ProductSaveService;
import com.xjs.mall.to.es.SkuEsModel;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.io.IOException;
import java.util.List;
/**
* es保存控制器
*
* @author xiejs
* @since 2022-04-06
*/
@RequestMapping("/search")
@RestController
@Api(tags = "商城-检索-ES保存")
@Log4j2
public class ElasticSaveController {
@Autowired
private ProductSaveService productSaveService;
@PostMapping("/product")
@ApiOperation("上架商品")
public R productStatusUp(@RequestBody List<SkuEsModel> skuEsModelList) {
boolean b = false;
try {
b = productSaveService.productStatusUp(skuEsModelList);
} catch (IOException e) {
log.error("ES商品上架错误:" + 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());
}
}
}

View File

@ -0,0 +1,21 @@
package com.xjs.mall.search.service;
import com.xjs.mall.to.es.SkuEsModel;
import java.io.IOException;
import java.util.List;
/**
* 商品保存接口
*
* @author xiejs
* @since 2022-04-06
*/
public interface ProductSaveService {
/**
* 上架商品
* @param skuEsModelList 商品es模型
*/
boolean productStatusUp(List<SkuEsModel> skuEsModelList) throws IOException;
}

View File

@ -0,0 +1,65 @@
package com.xjs.mall.search.service.impl;
import com.alibaba.fastjson.JSON;
import com.xjs.consts.EsConst;
import com.xjs.mall.search.config.ElasticsearchConfig;
import com.xjs.mall.search.service.ProductSaveService;
import com.xjs.mall.to.es.SkuEsModel;
import lombok.extern.log4j.Log4j2;
import org.elasticsearch.action.bulk.BulkItemResponse;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
/**
* 商品保存接口实现
*
* @author xiejs
* @since 2022-04-06
*/
@Service
@Log4j2
public class ProductSaveServiceImpl implements ProductSaveService {
@Autowired
private RestHighLevelClient restHighLevelClient;
@Override
public boolean productStatusUp(List<SkuEsModel> skuEsModelList) throws IOException {
//保存到es中
//1给es中建立索引-product
// product-mapping.json文件执行
//2给es中保存这些数据
BulkRequest bulkRequest = new BulkRequest();
for (SkuEsModel model : skuEsModelList) {
IndexRequest indexRequest = new IndexRequest(EsConst.PRODUCT_INDEX);
indexRequest.id(model.getSkuId().toString());
String json = JSON.toJSONString(model);
indexRequest.source(json, XContentType.JSON);
bulkRequest.add(indexRequest);
};
BulkResponse bulkResponse = restHighLevelClient.bulk(bulkRequest, ElasticsearchConfig.COMMON_OPTIONS);
// 如果批量错误
boolean b = bulkResponse.hasFailures();
List<String> collect = Arrays.stream(bulkResponse.getItems()).map(BulkItemResponse::getId).collect(Collectors.toList());
log.info("商品上架完成:{}",collect);
return b;
}
}

View File

@ -0,0 +1,69 @@
{
"mappings": {
"properties": {
"skuId": {
"type": "long"
},
"spuId": {
"type": "long"
},
"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"
},
"catalogName": {
"type": "text",
"analyzer": "ik_smart"
},
"brandName": {
"type": "keyword",
"index": false,
"doc_values": false
},
"brandImg": {
"type": "keyword",
"index": false,
"doc_values": true
},
"attrs": {
"type": "nested",
"properties": {
"attrId": {
"type": "long"
},
"attrName": {
"type": "keyword",
"index": false,
"doc_values": false
},
"attrValue": {
"type": "keyword"
}
}
}
}
}
}

View File

@ -2,10 +2,11 @@ package com.xjs.mall.ware.controller;
import com.ruoyi.common.log.annotation.Log; import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType; import com.ruoyi.common.log.enums.BusinessType;
import com.xjs.mall.other.R;
import com.xjs.mall.ware.entity.WareSkuEntity; import com.xjs.mall.ware.entity.WareSkuEntity;
import com.xjs.mall.ware.service.WareSkuService; import com.xjs.mall.ware.service.WareSkuService;
import com.xjs.mall.ware.vo.SkuHasStockVo;
import com.xjs.utils.PageUtils; import com.xjs.utils.PageUtils;
import com.xjs.mall.other.R;
import com.xjs.validation.group.AddGroup; import com.xjs.validation.group.AddGroup;
import com.xjs.validation.group.UpdateGroup; import com.xjs.validation.group.UpdateGroup;
import io.swagger.annotations.Api; import io.swagger.annotations.Api;
@ -15,6 +16,7 @@ import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import java.util.Arrays; import java.util.Arrays;
import java.util.List;
import java.util.Map; import java.util.Map;
@ -32,6 +34,14 @@ public class WareSkuController {
@Autowired @Autowired
private WareSkuService wareSkuService; private WareSkuService wareSkuService;
//查询sku是否有库存
@PostMapping("/hasStock")
public List<SkuHasStockVo> getSkuHasStock(@RequestBody List<Long> skuIds) {
return wareSkuService.getSkuHasStock(skuIds);
}
/** /**
* 列表 * 列表
*/ */

View File

@ -19,4 +19,11 @@ public interface WareSkuDao extends BaseMapper<WareSkuEntity> {
* @param skuNum 商品数量 * @param skuNum 商品数量
*/ */
void addStock(@Param("skuId") Long skuId, @Param("wareId") Long wareId, @Param("skuNum") Integer skuNum); void addStock(@Param("skuId") Long skuId, @Param("wareId") Long wareId, @Param("skuNum") Integer skuNum);
/**
* 获取库存
* @param skuId sku id
* @return 库存数
*/
Long getSkuStock(@Param("skuId") Long skuId);
} }

View File

@ -2,8 +2,10 @@ package com.xjs.mall.ware.service;
import com.baomidou.mybatisplus.extension.service.IService; import com.baomidou.mybatisplus.extension.service.IService;
import com.xjs.mall.ware.entity.WareSkuEntity; import com.xjs.mall.ware.entity.WareSkuEntity;
import com.xjs.mall.ware.vo.SkuHasStockVo;
import com.xjs.utils.PageUtils; import com.xjs.utils.PageUtils;
import java.util.List;
import java.util.Map; import java.util.Map;
/** /**
@ -24,5 +26,13 @@ public interface WareSkuService extends IService<WareSkuEntity> {
* @param skuNum 商品数量 * @param skuNum 商品数量
*/ */
void addStock(Long skuId, Long wareId, Integer skuNum); void addStock(Long skuId, Long wareId, Integer skuNum);
/**
* 根据skuIds查询是否有库存
* @since 2022-04-06
* @param skuIds skus
* @return list
*/
List<SkuHasStockVo> getSkuHasStock(List<Long> skuIds);
} }

View File

@ -13,6 +13,7 @@ import com.xjs.mall.ware.entity.WareInfoEntity;
import com.xjs.mall.ware.entity.WareSkuEntity; import com.xjs.mall.ware.entity.WareSkuEntity;
import com.xjs.mall.ware.service.WareInfoService; import com.xjs.mall.ware.service.WareInfoService;
import com.xjs.mall.ware.service.WareSkuService; import com.xjs.mall.ware.service.WareSkuService;
import com.xjs.mall.ware.vo.SkuHasStockVo;
import com.xjs.mall.ware.vo.WareSkuVo; import com.xjs.mall.ware.vo.WareSkuVo;
import com.xjs.utils.PageUtils; import com.xjs.utils.PageUtils;
import com.xjs.utils.Query; import com.xjs.utils.Query;
@ -96,4 +97,16 @@ public class WareSkuServiceImpl extends ServiceImpl<WareSkuDao, WareSkuEntity> i
} }
@Override
public List<SkuHasStockVo> getSkuHasStock(List<Long> skuIds) {
return skuIds.stream().map(skuId -> {
SkuHasStockVo vo = new SkuHasStockVo();
//查询当前sku的总库存量
Long count = super.baseMapper.getSkuStock(skuId);
vo.setSkuId(skuId);
vo.setHasStock(count != null && count > 0);
return vo;
}).collect(Collectors.toList());
}
} }

View File

@ -0,0 +1,21 @@
package com.xjs.mall.ware.vo;
import lombok.Data;
/**
* sku库存查询vo
* @author xiejs
* @since 2022-04-06
*/
@Data
public class SkuHasStockVo {
/**
* sku id
*/
private Long skuId;
/**
* 是否有库存
*/
private Boolean hasStock;
}

View File

@ -20,5 +20,9 @@
and ware_id = #{wareId} and ware_id = #{wareId}
</update> </update>
<select id="getSkuStock" resultType="java.lang.Long">
select sum(stock - stock_locked) from wms_ware_sku where sku_id=#{skuId}
</select>
</mapper> </mapper>