redisson分布式锁-灵析社区

英勇投弹手

### maven依赖 ```xml org.redisson redisson-spring-boot-starter 3.16.0 org.glassfish jakarta.el ``` ### redis 配置 ```yml spring: redis: host: 127.0.0.1 port: 6379 password: database: 0 lettuce: pool: # 最大活跃链接数 默认8 max-active: 100 # 最大空闲连接数 默认8 max-idle: 10 # 最小空闲连接数 默认0 min-idle: 5 timeout: 30000 ``` ### redisson 工具类 ```java package com.miya.demo.common.util; import com.miya.demo.common.exception.BusinessException; import lombok.extern.slf4j.Slf4j; import org.redisson.api.RedissonClient; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.util.concurrent.locks.Lock; /** * redisson锁工具类 * * @author Caixiaowei * @date 2022/06/21 */ @Component @Slf4j public class RedissonLockUtil { private static final long DEFAULT_WAIT_TIME = 5L; @Autowired RedissonClient redissonClient; /** * 加锁后运行 * * @param lockName 锁名称 * @param runnable Runnable */ public void runWithLock(String lockName, Runnable runnable) { Lock lock = redissonClient.getLock(lockName); runWithLock(lock, lockName, DEFAULT_WAIT_TIME, runnable, true); } /** * 加锁后运行 * * @param lockName 锁名称 * @param waitTime 等待时间,超过之后取锁失败 * @param runnable Runnable */ public void runWithLock(String lockName, Long waitTime, Runnable runnable) { Lock lock = redissonClient.getLock(lockName); runWithLock(lock, lockName, waitTime, runnable, true); } public void runWithLock(Lock lock, String lockName, Long waitTime, Runnable runnable, boolean logEnabled) { if (waitTime == null) { waitTime = DEFAULT_WAIT_TIME; } try { boolean lockOn = lock.tryLock(waitTime, java.util.concurrent.TimeUnit.SECONDS); if (lockOn) { if (logEnabled) { log.info("Try lock [{}] success.", lockName); } try { runnable.run(); } finally { lock.unlock(); } } else { throw new BusinessException(String.format("Try lock [%s] fail.", lockName)); } } catch (InterruptedException e) { if (logEnabled) { log.info("Try lock [{}] fail with exception.", lockName); } throw new BusinessException(e); } } } ``` ### 应用demo ```java public void demo() { String lockKey = "xxxx" redissonLockUtil.runWithLock(lockKey, () -> { // todo 业务逻辑 }); } ```

阅读量:179

点赞量:0

问AI