需求:通过查看当前商品ID,也要有展示当前商品可以使用的优惠券。用Feign组件,传产品ID,调用优惠券的Service
前提:微服务项目中数据库表设计尽量都是单表查询,商品表和优惠券表联系用第三个表来联系
商品表设计:
优惠券表:
联系表:
优惠券的业务:
@Service
public class CouponServiceImpl implements CouponService {
@Resource
CouponMapper couponMapper;
@Resource
CouponProductRelationMapper productRelationMapper;
@Override
public ResponseResult<List<CouponVo>> list(Long productId) {
List<Coupon> couponList=new ArrayList<>();
QueryWrapper<CouponProductRelation> relationQueryWrapper=new QueryWrapper<>();
relationQueryWrapper.lambda().eq(CouponProductRelation::getProductId,productId);
List<CouponProductRelation> relations = productRelationMapper.selectList(relationQueryWrapper);
if (relations!=null&&relations.size()>0){
for (CouponProductRelation c:
relations) {
QueryWrapper<Coupon>queryWrapper=new QueryWrapper<>();
queryWrapper.lambda().eq(Coupon::getId,c.getCouponId());
Coupon coupon = couponMapper.selectOne(queryWrapper);
couponList.add(coupon);
}
}
List<CouponVo> voList = CommonBeanUtils.copyListProperties(couponList, CouponVo::new);
return ResponseResult.success(voList) ;
}
}
Feign调用:
@FeignClient(value = "cloud-coupon",path = "/coupon")
public interface CouponFeignApi {
@GetMapping("/list")
ResponseResult<List<CouponVo>> list(@RequestParam Long id);
}
消费者:
商品调用
@Service
public class ProductServiceImpl implements ProductService {
@Resource
ProductMapper productMapper;
@Resource
ProductSpecsMapper productSpecsMapper;
@Resource
CouponFeignApi couponFeignApi;
@Override
public ResponseResult<ProductVo> detail(Long productId) {
Product product = productMapper.selectId(productId);
ProductVo productVo = new ProductVo();
BeanUtils.copyProperties(product, productVo);
List<ProductSpecsVo> productVos = CommonBeanUtils.copyListProperties(productSpecsMapper.selectByProductId(productId), ProductSpecsVo::new);
productVo.setProductSpecsList(productVos);
ResponseResult<List<CouponVo>> list = couponFeignApi.list(productId);
List<CouponVo> data = list.getData();
productVo.setCouponVoList(data);
return ResponseResult.success(productVo);
}
}