import redis.clients.jedis.Jedis;
// 优惠券秒杀
public void couponRedisLock(String userId, String couponId) {
String lockKey = "lock:coupon:" + couponId;
try (Jedis jedis = pool.getResource()) {
// 加锁
String identifier = UUID.randomUUID().toString();
if (jedis.set(lockKey, identifier, "NX", "PX", 5000).equals("OK")) {
// 业务逻辑
boolean result = seckillCoupon(userId, couponId);
if (result) {
// 处理成功
} else {
// 处理失败
}
} else {
// 已被抢完或其他情况
}
}
}
// 分布式锁的可重入
class RedisLock {
Jedis jedis;
String lockKey;
String identifier;
int expireTime;
public RedisLock(Jedis jedis, String lockKey, String identifier, int expireTime) {
this.jedis = jedis;
this.lockKey = lockKey;
this.identifier = identifier;
this.expireTime = expireTime;
}
public void lock() {
while (!jedis.set(lockKey, identifier, "NX", "PX", expireTime).equals("OK")) {
// 重试机制
try {
Thread.sleep(100);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
break;
}
}
}
public void unlock() {
if (jedis.get(lockKey).equals(identifier)) {
jedis.del(lockKey);
}
}
}
// 看门狗机制
class RedLock {
Jedis jedis;
String lockKey;
int expireTime; // 锁的过期时间
int watchdogExpireTime; // 看门狗的过期时间
public RedLock(Jedis jedis, String lockKey, int expireTime, int watchdogExpireTime) {
this.jedis = jedis;
this.lockKey = lockKey;
this.expireTime = expireTime;
this.watchdogExpireTime = watchdogExpireTime;
}
public void lock() {
long expires = System.currentTimeMillis() + expireTime + 1;
String expiresStr = String.valueOf(expires);
if (jedis.setnx(lockKey, expiresStr) == 1) {
// 开启看门狗线程
Thread watchdog = new Thread(() -> {
while (System.currentTimeMillis() < expires) {
jedis.expire(lockKey, watchdogExpireTime);
try {
Thread.sleep(watchdogExpireTime / 3);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
评论已关闭