内容涉及购物车的双重map 以及Redis的缓存购物车操作
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson 引入阿里巴巴cloud后自带,TODO 可以删除这个包 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.75</version>
</dependency> import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import net.xdclass.constant.CacheKey;
import net.xdclass.enums.BizCodeEnum;
import net.xdclass.exception.BizException;
import net.xdclass.interceptor.LoginInterceptor;
import net.xdclass.model.LoginUser;
import net.xdclass.request.CartItemRequest;
import net.xdclass.service.CartService;
import net.xdclass.service.ProductService;
import net.xdclass.vo.CartItemVO;
import net.xdclass.vo.ProductVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
@Service
@Slf4j
public class CartServiceImpl implements CartService {
@Autowired
private ProductService productService;
@Autowired
private RedisTemplate redisTemplate;
@Override
public void addToCart(CartItemRequest cartItemRequest) {
//商品id
long productId = cartItemRequest.getProductId();
//购买数量
int buyNum = cartItemRequest.getBuyNum();
//获取购物车
BoundHashOperations<String, Object, Object> myCart = getMyCartOps();
//获取Redis缓存中的商品id
Object cacheObj = myCart.get(productId);
String result = "";
//看看有没有
if (cacheObj != null) {
result = (String) cacheObj;
}
if (StringUtils.isBlank(result)) {
//不存在则新建一个商品
CartItemVO cartItemVO = new CartItemVO();
ProductVO productVO = productService.findDetailById(productId);
if (productVO == null) {
throw new BizException(BizCodeEnum.CART_FAIL);
}
cartItemVO.setAmount(productVO.getAmount());
cartItemVO.setBuyNum(buyNum);
cartItemVO.setProductId(productId);
cartItemVO.setProductImg(productVO.getCoverImg());
cartItemVO.setProductTitle(productVO.getTitle());
//将对象转换为json
myCart.put(productId, JSON.toJSONString(cartItemVO));
} else {
//存在商品,修改数量
//将json转换为对象
CartItemVO cartItem = JSON.parseObject(result, CartItemVO.class);
cartItem.setBuyNum(cartItem.getBuyNum() + buyNum);
myCart.put(productId, JSON.toJSONString(cartItem));
}
}
/**
* 抽取我的购物车,通用方法
* 这个就是双重map结构
*
* @return
*/
private BoundHashOperations<String, Object, Object> getMyCartOps() {
String cartKey = getCartKey();
return redisTemplate.boundHashOps(cartKey);
}
/**
* 购物车缓存 key
*
* @return
*/
private String getCartKey() {
LoginUser loginUser = LoginInterceptor.threadLocal.get();
String cartKey = String.format(CacheKey.CART_KEY, loginUser.getId());
return cartKey;
}
} 本文作者为DBC,转载请注明。