当前位置:网站首页>redis实现分布式锁

redis实现分布式锁

2022-06-22 00:28:00 温温top

package com.demo.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Component
public class LockUtil {

    @Autowired
    RedisTemplate<String, String> redisTemplate;

    /**
     * 获取锁的默认超时时间
     */
    private static final long timeout = 300;

    /**
     * 加锁,无阻塞
     * @param key
     * @param expireTime 加锁锁时间
     * @return
     */
    public Boolean lock(String key, long expireTime) {
        String requestId = UUID.randomUUID().toString();
        Long start = System.currentTimeMillis();
        //自旋,在一定时间内获取锁,超时则返回错误
        for (; ; ) {
            //Set命令返回OK,则证明获取锁成功
            Boolean ret = redisTemplate.opsForValue().setIfAbsent(key, requestId, expireTime,
                    TimeUnit.SECONDS);
            if (ret) {
                return true;
            }
            //否则循环等待,在timeout时间内仍未获取到锁,则获取失败
            long end = System.currentTimeMillis() - start;
            if (end >= timeout) {
                return false;
            }
        }
    }

    /**
     * 加锁,无阻塞
     * @param key
     * @param expireTime 加锁锁时间 秒
     * @param waitTime   等待时间 毫秒
     * @return
     */
    public boolean lock(String key, long expireTime, long waitTime) {
        String value = "trade_task";
        long start = System.currentTimeMillis();
        ValueOperations<String, String> opsForValue = redisTemplate.opsForValue();
        // 自旋,在一定时间内获取锁,超时则返回错误
        for (; ; ) {
            //Set命令返回OK,则证明获取锁成功
            Boolean ret = opsForValue.setIfAbsent(key, value, expireTime, TimeUnit.SECONDS);
            if (ret != null && ret) {
                return true;
            }
            //否则循环等待,在timeout时间内仍未获取到锁,则获取失败
            long end = System.currentTimeMillis() - start;
            if (end >= waitTime) {
                return false;
            }
        }
    }

    public void unlock(String key) {
        redisTemplate.delete(key);
    }
}

原网站

版权声明
本文为[温温top]所创,转载请带上原文链接,感谢
https://blog.csdn.net/wen_3370/article/details/125372309