import redis.clients.jedis.Jedis;
public class RedisLockDemo {
private static final String LOCK_KEY = "mylock";
private static final int LOCK_EXPIRE_TIME = 10; // 锁的过期时间,单位为秒
private static final int SLEEP_TIME = 100; // 获取锁失败后等待的时间,单位为毫秒
private Jedis jedis;
public RedisLockDemo() {
jedis = new Jedis("localhost"); // 连接本地Redis服务器
}
public boolean acquireLock() {
long startTime = System.currentTimeMillis();
while (true) {
String result = jedis.set(LOCK_KEY, "locked", "NX", "EX", LOCK_EXPIRE_TIME);
if ("OK".equals(result)) {
return true; // 获取锁成功
}
long elapsedTime = System.currentTimeMillis() - startTime;
if (elapsedTime