All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.iohao.game.widget.light.redis.lock.DefaultRedissonDistributedLock Maven / Gradle / Ivy

package com.iohao.game.widget.light.redis.lock;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;

import java.util.concurrent.TimeUnit;

/**
 * 简单的基于Redisson分布式锁接口实现类
 * 
 *     使用Redisson实现
 * 
* * @author shen * @date 2022-03-28 * @Slogan 慢慢变好,是给自己最好的礼物 */ @Slf4j @RequiredArgsConstructor public class DefaultRedissonDistributedLock implements DistributedLock { private final RedissonClient redissonClient; @Override public T tryLockAndExecute(String key, long waitTime, long leaseTime, TimeUnit unit, ReturnHandle action) throws InterruptedException { RLock lock = redissonClient.getLock(key); try { boolean tryLock = lock.tryLock(waitTime, leaseTime, unit); if (tryLock) { log.debug("{} 获取锁成功", key); return action.execute(); } } finally { if (lock.isHeldByCurrentThread()) { lock.unlock(); } } return null; } @Override public void tryLockAndExecute(String key, long waitTime, long leaseTime, TimeUnit unit, VoidHandle action) throws InterruptedException { RLock lock = redissonClient.getLock(key); try { boolean tryLock = lock.tryLock(waitTime, leaseTime, unit); if (tryLock) { action.execute(); } } finally { if (lock.isHeldByCurrentThread()) { lock.unlock(); } } } @Override public T lockAndExecute(String key, long leaseTime, TimeUnit unit, ReturnHandle action) { RLock lock = redissonClient.getLock(key); try { lock.lock(leaseTime, unit); return action.execute(); } finally { if (lock.isHeldByCurrentThread()) { lock.unlock(); } } } @Override public void lockAndExecute(String key, long leaseTime, TimeUnit unit, VoidHandle action) { RLock lock = redissonClient.getLock(key); try { lock.lock(leaseTime, unit); action.execute(); } finally { if (lock.isHeldByCurrentThread()) { lock.unlock(); } } } @Override public boolean unlock(String key) { RLock lock = redissonClient.getLock(key); lock.unlock(); return true; } }




© 2015 - 2024 Weber Informatics LLC | Privacy Policy