文章目录
- 加锁
- expire
- 获取值
- 例子代码
- 附录
- 其他
- 让锁过期,如何操作
加锁
@ResponseBody
@RequestMapping("/lock")
public String lock(){
ValueOperations operations = stringRedisTemplate.opsForValue();
String wcLock = (String)operations.get(WC_LOCK);
if(!StringUtils.isEmpty(wcLock)){
logger.info("wcLock已经存在");
return "wcLock已经存在";
}else{
// key value timeout 时间单位
operations.set(WC_LOCK,"1",60, TimeUnit.SECONDS);
return "wcLock设置锁成功";
}
}
注:超期时间要 >0 否则会报错。
expire
@ResponseBody
@RequestMapping("/expire")
public String expire(){
ValueOperations operations = stringRedisTemplate.opsForValue();
operations.set(WC_LOCK,"1",1L, TimeUnit.SECONDS);
return "expire success";
}
获取值
@ResponseBody
@RequestMapping("/get")
public String get(String string){
ValueOperations operations = stringRedisTemplate.opsForValue();
String wcLock = (String)operations.get(string);
Long expire = operations.getOperations().getExpire(string); // 过期时间的获取
logger.info("key: {},timeout is: {}",expire);
return wcLock;
}
例子代码
代码:
@RestController
@RequestMapping("")
public class LoginController {
@Autowired
private StringRedisTemplate stringRedisTemplate;
@RequestMapping("/login")
public String login(HttpServletRequest request){
ValueOperations valueOperations = stringRedisTemplate.opsForValue();
valueOperations.set("shanghai","shanghai"); // 新增
valueOperations.set("hebei","shijiazhuang2"); // 存在的话就是修改
valueOperations.get("hebei");
Set<String> keys = stringRedisTemplate.keys("*"); // keys * 查看所有
for (String key:
keys) {
System.out.println(keys);
}
stringRedisTemplate.delete("one"); // 删除
return "fail";
}
}
附录
Key Type Operations:
接口 | 描述 |
GeoOperations | Redis geospatial operations like |
HashOperations | Redis hash operations |
HyperLogLogOperations | Redis HyperLogLog operations like ( |
ListOperations | Redis list operations |
SetOperations | Redis set operations |
ValueOperations | Redis string (or value) operations |
ZSetOperations | Redis zset (or sorted set) operations |
Key Bound Operations:
接口 | 描述 |
BoundGeoOperations | Redis key bound geospatial operations. |
BoundHashOperations | Redis hash key bound operations |
BoundKeyOperations | Redis key bound operations |
BoundListOperations | Redis list key bound operations |
BoundSetOperations | Redis set key bound operations |
BoundValueOperations | Redis string (or value) key bound operations |
BoundZSetOperations | Redis zset (or sorted set) key bound operations |
官网文档地址:
https://docs.spring.io/spring-data/redis/docs/2.0.3.RELEASE/reference/html/#redis:template
其他
让锁过期,如何操作
1、直接删除该redis缓存。
2、手动设置超时时间1秒,马上就过期了。