设计一个简单的 RedisDistributedLock
类,实现单例模式,并包含基本的锁定机制。这个类将使用 Redis 来管理锁,确保在分布式系统中资源的同步访问
java
import redis.clients.jedis.Jedis;
public class RedisDistributedLock {
private static RedisDistributedLock instance;
private Jedis jedis;
private final String redisHost;
private final int redisPort;
// 私有构造函数,防止外部实例化
private RedisDistributedLock(String host, int port) {
this.redisHost = host;
this.redisPort = port;
this.jedis = new Jedis(redisHost, redisPort);
}
// 公共静态方法,返回唯一实例
public static synchronized RedisDistributedLock getSingletonInstance(String host, int port) {
if (instance == null) {
instance = new RedisDistributedLock(host, port);
}
return instance;
}
// 尝试获取锁
public boolean lockTransaction(String transactionId) {
String key = "lock:" + transactionId;
String result = jedis.set(key, "locked", "NX", "EX", 10); // 锁超时时间为10秒
return "OK".equals(result);
}
// 释放锁
public void unlockTransaction(String transactionId) {
String key = "lock:" + transactionId;
jedis.del(key);
}
// 清理资源
public void close() {
jedis.close();
}
}