redis-乐观锁
@Component
public class WebShopRedisLock {
@Autowired
private RedisTemplate<String, Object> redisTemplate;
private final static long LOCK_EXPIRE = 5 * 1000L;
private final static long LOCK_TRY_INTERVL = 30L;
private final static long LOCK_TRY_TIMEOUT = 20 * 1000L;
/**
* 加锁
*
* @param key productId - 商品的唯一标志
* @param value 当前时间+超时时间 也就是时间戳
* @return 成功或失败
*/
public boolean lock(String key, String value) {
try {
if (StringUtils.isEmpty(key) || StringUtils.isEmpty(value)) {
return false;
}
long startTime = System.currentTimeMillis();
do {
if (!redisTemplate.hasKey(key)) {
redisTemplate.opsForValue().set(key, value, LOCK_EXPIRE, TimeUnit.MILLISECONDS);
return true;
}
if (System.currentTimeMillis() - startTime > LOCK_TRY_TIMEOUT) {
return false;
}
Thread.sleep(LOCK_TRY_INTERVL);
} while (redisTemplate.hasKey(key));
} catch (InterruptedException e) {
e.printStackTrace();
return false;
}
return false;
}
/**
* 解锁
*
* @param key productId - 商品的唯一标志
*/
public void unlock(String key) {
// redisTemplate.delete(key);
redisTemplate.expire(key, 1, TimeUnit.MILLISECONDS);
}
}