redis分布锁
配置 Redisson 连接
在 Spring Boot 项目的配置文件 application.yml 中添加 Redisson 配置:
spring:
data:
redis:
host: localhost
port: 6379
database: 0
redisson:
codec: org.redisson.codec.JsonJacksonCodec
single-server-config:
address: "redis://${spring.data.redis.host}:${spring.redis.port}"
database: "${spring.data.redis.database}"
password: "${spring.data.redis.password}"
5.3 编写分布式锁代码类
import jakarta.annotation.Resource;
import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.springframework.stereotype.Service;
import java.util.concurrent.TimeUnit;
@Service
public class RedissonLockService {
@Resource
private Redisson redisson;
/**
* 加锁
*
* @param key 分布式锁的 key
* @param timeout 超时时间
* @param unit 时间单位
* @return
*/
public boolean tryLock(String key, long timeout, TimeUnit unit) {
RLock lock = redisson.getLock(key);
try {
return lock.tryLock(timeout, unit);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return false;
}
}
/**
* 释放分布式锁
*
* @param key 分布式锁的 key
*/
public void unlock(String key) {
RLock lock = redisson.getLock(key);
lock.unlock();
}
}