Redis常用的数据类型之哈希(Hash)

Redis 哈希(Hash)

Redis hash 是一个 string 类型的 field(字段) 和 value(值) 的映射表,hash 特别适合用于存储对象。

Redis 中每个 hash 可以存储 232 - 1 键值对(40多亿)。

场景描述

购物车案例

以用户id为key,商品id为field,商品数量为value,恰好构成了购物车的3个要素。

代码实现
添加购物车
service层
/**
 * 添加商品
 * @param shopCartDto
 * @return
 */
public Result addCart(ShopCartDto shopCartDto){
    //判断用户手机号是否为空
    if(StringUtils.isEmpty(shopCartDto.getIphone())){
        return Result.error("用户手机号为空");
    }
    if(StringUtils.isEmpty(shopCartDto.getId())){
        return Result.error("商品为空");
    }
    //添加商品
    cacheService.hPut(ShopCartKey(shopCartDto.getIphone())
                      ,shopCartDto.getId(),
                      shopCartDto.getCartNums().toString());
    return Result.success();
}
测试用例
POST http://localhost:18888/api/v1/ShopCart/addCart
Content-Type:application/json

{
  "iphone": "13666667878",
  "id":"1",
  "CartNums": "10"
}
结果

image-20240826162122520

清空购物车
service层
	/**
     * 清空购物车
     * @param iphone
     * @return
     */
    public Result cleanCart(String iphone){
        //TODO:这里应该先清空数据库,在进行同步
        try{
            String shopCartKey = ShopCartKey(iphone);
            Map<Object, Object> objectObjectMap = cacheService.hGetAll(shopCartKey);
            for (Map.Entry<Object,Object> entry:objectObjectMap.entrySet()){
                cacheService.hDelete(shopCartKey, entry.getKey());
            }
        }catch (Exception e){
            return Result.error("清空购物车失败");
        }
        return Result.success();
    }
测试用例
POST http://localhost:18888/api/v1/ShopCart/clean
Content-Type:application/json

13666667844
结果

image-20240827103710035

修改购物车数据
service层
/**
 * 批量更新购物车数据
 * @param shopCartDtolist
 * @return
 */
public Result UpdateCart(List<ShopCartDto> shopCartDtolist){
   try{
       for (ShopCartDto shopCartDto : shopCartDtolist) {
           cacheService.hPut(ShopCartKey(shopCartDto.getIphone()),shopCartDto.getId(),shopCartDto.getCartNums());
       }
       return Result.success();
   }catch (Exception e){
       return  Result.error("更新失败");
   }
}
测试用例
POST http://localhost:18888/api/v1/ShopCart/update
Content-Type:application/json

[
  {
    "iphone": "13666667866",
    "id" : "1",
    "cartNums":"10.00"
  },
  {
    "iphone": "13666667866",
    "id" : "2",
    "cartNums":"20.00"
  }
]
结果

image-20240827110657665

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值