redis 分布式锁 使用示例
分布式锁
code segment
private static final String LOCK_SUCCESS = "OK";
private static final String SET_IF_NOT_EXIST = "NX";
private static final String SET_WITH_EXPIRE_TIME = "EX";
private static final String LOCKED = "locked";
/**
* 加锁
*
* @param key redis key
* @param seconds 过期时间
* @return 如果加锁成功, 返回true, 反之, 返回false
*/
public boolean lock(String key, Integer seconds) {
final String newKey = String.format(RedisConstant.PREFIX, key);
String exist = "";
try {
exist = redisTemplate.execute(action -> action.set(newKey,
LOCKED,
SET_IF_NOT_EXIST,
SET_WITH_EXPIRE_TIME,
seconds));
} catch (Exception e) {
logger.error("lock error", e);
}
return exist != null && exist.equals(LOCK_SUCCESS);
}
设置普通缓存
code segment
redisTemplate.execute(redis -> redis.setex(redisKey, expiredTime,value));
取缓存
code segment
String value = redisTemplate.execute(action -> action.get(key));
取过期时间
code segment
Long remainSeconds = 0L;
try {
remainSeconds = redisTemplate.execute(action -> action.ttl(key));
} catch (Exception ex) {
logger.error("redis ttl error", ex);
}
if (remainSeconds <= 0L) {
//some logic
}