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"
}
结果
清空购物车
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
结果
修改购物车数据
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"
}
]