RedisTemplate分布式锁-加锁/解锁的实现

加锁实现

实现逻辑

通过for循环自旋的方式,判断redis中是否存在锁的缓存,存在则放回true,否则判断获取锁的时间是否超时,超时则返回false。
自旋的判断时间是很快的,设置的超时时间如果太长会占用cpu的时间片处理。

加锁的实现方法

/**
* 获取锁的超时时间
*/
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 可以传一个值 或多个
 */
public void del(String... key) {
    if (key != null && key.length > 0) {
        if (key.length == 1) {
            redisTemplate.delete(key[0]);
        } else {
            redisTemplate.delete(CollectionUtils.arrayToList(key));
        }
    }
}

业务代码的实现

实现逻辑

先判断是否获得锁,是则处理业务代码,并且在最后进行解锁操作,否则循环5次,继续获取锁,能获取到则实现业务方法,不能获取到则返回错误信息

实现方法

/**
 * 锁的key前缀
 */
private static final String lockStr = "r_lock_";

/**
 * 获取锁最大失败次数
 */
private static final int maxFailCount = 5;

@RequestMapping("/t1")
public void testRedis(){

    String key = "test";
    // 锁的过期时间,避免死锁,根据业务调整,毫秒
    long expireTime = 1000;
    //判断是否获得锁
    boolean lock = redisService.tryLock(lockStr + key,expireTime);
    if(lock){
        try {

            String result = redisService.get(key);
            //处理业务的方法
            //TODO
            redisService.set(key,result);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //解锁
            redisService.del(lockStr + key);
        }
    }else{
        int failCount = 1;
        while (failCount <= maxFailCount){
            //判断是否获得锁
            if (redisService.tryLock(lockStr + key,expireTime)){
                //处理业务的方法
                //TODO

                //解锁
                redisService.del(lockStr + key);
            }else{
                failCount ++;
            }
        }
        throw new RuntimeException("当前创建的数量太多了,请稍后再试。");
    }
}
好的,请稍等,以下是分布式锁实现代码,基于Redis实现: ``` public class RedisDistributedLock { private static final Logger logger = LoggerFactory.getLogger(RedisDistributedLock.class); private static final String LOCK_PREFIX = "lock:"; private static final String LOCK_SUCCESS = "OK"; private static final long LOCK_TIMEOUT = 30000; private static final int RETRY_TIMES = 3; private static final long SLEEP_TIME = 1000; private JedisPool jedisPool; public RedisDistributedLock(JedisPool jedisPool) { this.jedisPool = jedisPool; } public boolean lock(String lockKey) { try (Jedis jedis = jedisPool.getResource()) { String lock = LOCK_PREFIX + lockKey; String threadId = Long.toString(Thread.currentThread().getId()); int retryTimes = 0; while (retryTimes < RETRY_TIMES) { String result = jedis.set(lock, threadId, "NX", "PX", LOCK_TIMEOUT); if (LOCK_SUCCESS.equals(result)) { logger.info("Lock acquired for key {}", lockKey); return true; } retryTimes++; Thread.sleep(SLEEP_TIME); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); } catch (Exception e) { logger.error("Failed to acquire lock for key {}", lockKey, e); } logger.warn("Failed to acquire lock for key {}", lockKey); return false; } public void unlock(String lockKey) { String lock = LOCK_PREFIX + lockKey; try (Jedis jedis = jedisPool.getResource()) { String curThreadId = Long.toString(Thread.currentThread().getId()); String lockValue = jedis.get(lock); if (curThreadId.equals(lockValue)) { jedis.del(lock); logger.info("Lock released for key {}", lockKey); } else { logger.warn("Trying to release lock for key {} with wrong thread id", lockKey); } } catch (Exception e) { logger.error("Failed to release lock for key {}", lockKey, e); } } } ``` 以下是分布式锁加锁解锁的测试类: ``` public class RedisDistributedLockTest { private static final JedisPool JEDIS_POOL = new JedisPool("localhost", 6379); @BeforeAll public static void setUp() throws Exception { Jedis jedis = JEDIS_POOL.getResource(); jedis.flushAll(); } @Test public void testLockUnlock() throws InterruptedException { RedisDistributedLock lock = new RedisDistributedLock(JEDIS_POOL); CountDownLatch latch = new CountDownLatch(1); AtomicBoolean locked = new AtomicBoolean(false); Thread t1 = new Thread(() -> { locked.set(lock.lock("test-key")); latch.countDown(); try { Thread.sleep(1000); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } lock.unlock("test-key"); }); Thread t2 = new Thread(() -> { try { latch.await(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } boolean success = lock.lock("test-key"); assertFalse(success); }); t1.start(); t2.start(); t1.join(); t2.join(); assertTrue(locked.get()); } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值