Redis实现分布式锁

import java.util.concurrent.TimeUnit;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundValueOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;


/**
 * 分布式锁
 *@Title:  
 *@Version:1.0
 */
@Component
public class DistributeLock {
    @Autowired
    private StringRedisTemplate redis;

    public boolean tryLock(String key, String uuid, long expireMillis) {
        BoundValueOperations<String, String> oper = redis.boundValueOps(key);
        if (oper.setIfAbsent(uuid)) {
            oper.expire(expireMillis, TimeUnit.MILLISECONDS);
            return true;
        } else if (oper.getExpire() == null || oper.getExpire() == -1  ) {
            oper.expire(expireMillis, TimeUnit.MILLISECONDS);
        }
        return false;
    }


    public boolean unlock(final String key, final String uuid) {
        BoundValueOperations<String, String> oper = redis.boundValueOps(key);
        String value = oper.get();
        if (StringUtils.equals(value, uuid)) {
            redis.delete(key);
            return true;
        }
        return false;
    }


    /**
     *
     * @param key
     * @param uuid
     * @param expireMillis 锁的超时时间
     * @param timeout 获得锁的超时时间
     * @return
     */
    public boolean lock(String key, String uuid, long expireMillis,long timeout) {
        BoundValueOperations<String, String> oper = redis.boundValueOps(key);
        long beginTime = System.currentTimeMillis();
        try {
            // 在timeout的时间范围内不断轮询锁
            while (System.currentTimeMillis() - beginTime < timeout) {
                // 锁不存在的话,设置锁并设置锁过期时间,即加锁
                if (oper.setIfAbsent(uuid)) {
                    oper.expire(expireMillis, TimeUnit.MILLISECONDS);
                    return true;
                } else if (oper.getExpire() == null || oper.getExpire() == -1) {
                    oper.expire(expireMillis, TimeUnit.MILLISECONDS);
                }
                // 短暂休眠后轮询,避免可能的活锁
                Thread.sleep(30);
            }
        } catch (Exception e) {
            throw new RuntimeException("locking error", e);
        }
        return false;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值