基于redis实现分布式锁——乐观锁

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);
    }
}
发布了15 篇原创文章 · 获赞 4 · 访问量 548

猜你喜欢

转载自blog.csdn.net/pyf1903047190/article/details/102535737