maven依赖
<dependency>
<groupId>org.redisson</groupId>
<artifactId>redisson-spring-boot-starter</artifactId>
<version>3.16.0</version>
<exclusions>
<exclusion>
<groupId>org.glassfish</groupId>
<artifactId>jakarta.el</artifactId>
</exclusion>
</exclusions>
</dependency>
redis 配置
spring:
redis:
host: 127.0.0.1
port: 6379
password:
database: 0
lettuce:
pool:
max-active: 100
max-idle: 10
min-idle: 5
timeout: 30000
redisson 工具类
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;
@Component
@Slf4j
public class RedissonLockUtil {
private static final long DEFAULT_WAIT_TIME = 5L;
@Autowired
RedissonClient redissonClient;
public void runWithLock(String lockName, Runnable runnable) {
Lock lock = redissonClient.getLock(lockName);
runWithLock(lock, lockName, DEFAULT_WAIT_TIME, runnable, true);
}
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
public void demo() {
String lockKey = "xxxx"
redissonLockUtil.runWithLock(lockKey, () -> {
});
}