redis缓存实例html,Redis缓存实例:缓存购物车数据

该博客介绍了如何利用@Autowired的RedisTemplate在Spring Boot中实现购物车功能。具体步骤包括查询Redis中的商品数据,如果已有商品则更新数量和金额,没有则从远程服务获取商品信息并存入Redis。涉及的操作包括boundHashOps的使用、商品信息的转换及Redis的增删操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

思路:

0c900935459c5a21f34f0058b46faee8.png

代码:

@Autowired

private RedisTemplate redisTemplate;

@Override

public void addCart(String skuId, Integer num, String username) {

/**

* 1)查询redis中的数据

* 2)如果redis中已经有了,则追加数量,重新计算金额

* 3)如果没有,将商品添加到缓存

*/

//redisTemplate.boundHashOps新增元素到指定键中

OrderItem orderItem = (OrderItem) redisTemplate.boundHashOps(CART + username).get(skuId);

if (orderItem != null) {

//存在,刷新购物车

orderItem.setNum(orderItem.getNum() + num);

//如果数量<=0,应该移除该商品

if (orderItem.getNum()<= 0){

redisTemplate.boundHashOps(CART + username).delete(skuId);

return;

}

orderItem.setMoney(orderItem.getNum() * orderItem.getPayMoney());

orderItem.setPayMoney(orderItem.getNum() * orderItem.getPayMoney());

} else {

//不存在,新增购物车

Result skuResult = skuFeign.findById(skuId);

Sku sku = skuResult.getData();

//getData()

Spu spu = spuFeign.findSpuById(sku.getSpuId()).getData();

//将SKU转换成OrderItem

orderItem = this.sku2OrderItem(sku, spu, num);

}

//存入redis

redisTemplate.boundHashOps(CART + username).put(skuId, orderItem);

}

标签:boundHashOps,skuId,缓存,orderItem,Redis,购物车,num,sku,redisTemplate

来源: https://www.cnblogs.com/aaaazzzz/p/13160833.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值