代码如下:其中,假如你想在加锁时,再加一个过期时间,就不要用opsForValue()了,改成boundValueOps即可。
@Slf4j @Component public class RedisService { @Autowired private StringRedisTemplate stringRedisTemplate; /*** * 加锁 * @param key * @param value 当前时间+超时时间 * @return 锁住返回true */ public boolean lock(String key,String value){ if(stringRedisTemplate.opsForValue().setIfAbsent(key,value)){//setNX 返回boolean return true; } //如果锁超时 *** String currentValue = stringRedisTemplate.opsForValue().get(key); if(!StringUtils.isEmpty(currentValue) && Long.parseLong(currentValue)<System.currentTimeMillis()){ //获取上一个锁的时间 String oldvalue = stringRedisTemplate.opsForValue().getAndSet(key,value); if(!StringUtils.isEmpty(oldvalue)&&oldvalue.equals(currentValue)){ return true; } } return false; } /*** * 解锁 * @param key * @param value * @return */ public void unlock(String key,String value){ try { String currentValue = stringRedisTemplate.opsForValue().get(key); if(!StringUtils.isEmpty(currentValue)&¤tValue.equals(value)){ stringRedisTemplate.opsForValue().getOperations().delete(key); } } catch (Exception e) { log.error("解锁异常"); } } }