| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778 |
- package com.ydtech.components;
- import lombok.RequiredArgsConstructor;
- import org.redisson.api.RLock;
- import org.redisson.api.RedissonClient;
- import org.springframework.stereotype.Component;
- import java.util.concurrent.TimeUnit;
- import java.util.function.Supplier;
- /**
- * @description: 分布式锁封装
- * @author: wenks
- * @date: 2025/3/24 15:08
- **/
- @Component
- @RequiredArgsConstructor
- public class DistributedLockComponent {
- private final RedissonClient redissonClient;
- // 默认配置(单位:秒)
- private static final int DEFAULT_WAIT_TIME = 3;
- private static final int DEFAULT_LEASE_TIME = 30;
- /**
- * 带返回值的锁操作
- *
- * @param lockName 锁名称
- * @param supplier 业务逻辑
- * @param waitTime 获取锁等待时间
- * @param leaseTime 锁持有时间
- * @return 业务执行结果
- */
- public <T> T executeWithLock(String lockName, Supplier<T> supplier, long waitTime, long leaseTime) throws Exception {
- RLock lock = redissonClient.getLock(lockName);
- boolean isLocked = false;
- try {
- // 尝试获取锁
- isLocked = lock.tryLock(waitTime, leaseTime, TimeUnit.SECONDS);
- if (isLocked) {
- // 执行业务逻辑
- return supplier.get();
- }
- throw new RuntimeException("Acquire lock failed: " + lockName);
- } finally {
- if (isLocked && lock.isHeldByCurrentThread()) {
- lock.unlock();
- }
- }
- }
- /**
- * 快速失败(带默认参数)
- */
- public <T> T fastFailExecute(String lockName, Supplier<T> supplier) throws Exception {
- return executeWithLock(lockName, supplier, 0, DEFAULT_LEASE_TIME);
- }
- /**
- * 阻塞等待锁(带默认参数)
- */
- public <T> T blockingExecute(String lockName, Supplier<T> supplier) throws Exception {
- return executeWithLock(lockName, supplier, DEFAULT_WAIT_TIME, -1);
- }
- /**
- * 无返回值操作
- */
- public void executeWithLock(String lockName, Runnable runnable, long waitTime, long leaseTime) throws Exception {
- executeWithLock(lockName, () -> {
- runnable.run();
- return null;
- }, waitTime, leaseTime);
- }
- }
|