import org.redisson.RedissonClient;
import org.redisson.api.RLock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;
* 提供基于 Redisson 的分布式锁实现,用于在分布式环境下保护临界资源
public class DistributedLockService {
private RedissonClient redissonClient;
* @param leaseTime 持有时间(超过后自动释放,防止死锁)
* @throws RuntimeException 获取锁失败时抛出
public void executeWithLock(String lockKey, long waitTime, long leaseTime, TimeUnit timeUnit, Runnable runnable) {
RLock lock = redissonClient.getLock(lockKey);
locked = lock.tryLock(waitTime, leaseTime, timeUnit);
throw new RuntimeException("获取锁失败,当前锁被占用: " + lockKey);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException("获取锁被中断: " + lockKey, e);
if (locked && lock.isHeldByCurrentThread()) {
public void executeWithLock(String lockKey, long waitTime, long leaseTime, Runnable runnable) {
executeWithLock(lockKey, waitTime, leaseTime, TimeUnit.SECONDS, runnable);
* @param supplier 要执行的函数(带返回值)
* @throws RuntimeException 获取锁失败时抛出
public <T> T executeWithLock(String lockKey, long waitTime, long leaseTime, TimeUnit timeUnit, Supplier<T> supplier) {
RLock lock = redissonClient.getLock(lockKey);
locked = lock.tryLock(waitTime, leaseTime, timeUnit);
throw new RuntimeException("获取锁失败,当前锁被占用: " + lockKey);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException("获取锁被中断: " + lockKey, e);
if (locked && lock.isHeldByCurrentThread()) {
public <T> T executeWithLock(String lockKey, long waitTime, long leaseTime, Supplier<T> supplier) {
return executeWithLock(lockKey, waitTime, leaseTime, TimeUnit.SECONDS, supplier);