HashOperations的用处很多,例如最常见的用redis存储用户信息。
基本用法
// 获取HashOperations
HashOperations<String, String, String> hashOperations = stringRedisTemplate.opsForHash();
//add
hashOperations.put("user_hash","zhangfei","black face");
//update put会覆盖,相当于update
hashOperations.put("user_hash","zhangfei","mangfu");
//list 这里感觉叫list不好叫all吧
Map<String, String> userMap = hashOperations.entries("user_hash"); // entries
Set<String> userKeys = hashOperations.keys("user_hash");// keys
List<String> userValues = hashOperations.values("user_hash"); // values
//delete
hashOperations.delete("user_hash","zhangfei3");
//是否存在
Boolean aBoolean = hashOperations.hasKey("user_hash", "zhangfei"); // 是否存在
为了简化,value信息用String替代,实际中会是User类等对象。
如下是完成类的代码:
@Controller
@RequestMapping("hash")
public class HashController {
@Autowired
private StringRedisTemplate stringRedisTemplate;
@ResponseBody
@RequestMapping("/add")
public Map<String,String> add(){
HashOperations<String, String, String> hashOperations = stringRedisTemplate.opsForHash();
hashOperations.put("user_hash","zhangfei","black face"); // put相当于添加
hashOperations.put("user_hash","guanyu","red face");
return getAll();
}
@ResponseBody
@RequestMapping("/update")
public Map<String,String> update(){
HashOperations<String, String, String> hashOperations = stringRedisTemplate.opsForHash();
Boolean aBoolean = hashOperations.hasKey("user_hash", "zhangfei"); // 是否存在
System.out.println(aBoolean);
hashOperations.put("user_hash","zhangfei","mangfu"); //put 会重置,相当于update
return getAll();
}
@ResponseBody
@RequestMapping("/all")
public Map<String,String> all(){
return getAll();
}
@ResponseBody
@RequestMapping("/delete")
public Map<String,String> delete(){
HashOperations<String, String, String> hashOperations = stringRedisTemplate.opsForHash();
hashOperations.delete("user_hash","zhangfei3");
return getAll();
}
public Map<String,String> getAll(){
HashOperations<String, String, String> hashOperations = stringRedisTemplate.opsForHash();
Map<String, String> userMap = hashOperations.entries("user_hash"); // entries
final Set<String> userKeys = hashOperations.keys("user_hash"); // keys
List<String> userValues = hashOperations.values("user_hash"); // values
return userMap;
}
}