redis实现分布式锁代码
时间: 2023-08-24 19:07:04 浏览: 52
以下是一个简单的 Redis 分布式锁实现代码示例,使用 Python 编写:
```
import redis
class RedisLock:
def __init__(self, host='localhost', port=6379, db=0, password=None):
self.redis = redis.Redis(host=host, port=port, db=db, password=password)
self.lock_key = 'redis_lock'
def acquire(self):
while True:
if self.redis.set(self.lock_key, '1', nx=True, ex=10):
return True
else:
time.sleep(0.1)
def release(self):
self.redis.delete(self.lock_key)
```
上述代码中,我们使用 Redis 的 setnx() 方法实现了加锁操作,如果设置成功则表示获取到锁,返回 True,否则等待一段时间重新尝试获取锁。在释放锁的时候,我们使用 Redis 的 delete() 方法删除锁的键值对。
注意:上述代码仅为示例,实际使用时需要考虑更多情况,如重试次数、锁超时等。
相关问题
Redis实现分布式锁代码
以下是使用Redis实现分布式锁的示例代码,使用了setnx和expire命令:
```
import redis
class RedisLock:
def __init__(self, redis_client, key, expire=60, wait_timeout=10):
self.redis_client = redis_client
self.key = key
self.expire = expire
self.wait_timeout = wait_timeout
self.locked = False
def acquire(self):
while not self.locked:
self.locked = self.redis_client.setnx(self.key, 1)
if self.locked:
self.redis_client.expire(self.key, self.expire)
return True
else:
time.sleep(0.1)
self.wait_timeout -= 0.1
if self.wait_timeout <= 0:
return False
def release(self):
if self.locked:
self.redis_client.delete(self.key)
self.locked = False
```
使用示例:
```
import redis
redis_client = redis.Redis(host='localhost', port=6379, db=0)
lock = RedisLock(redis_client, 'my_lock_key', expire=60, wait_timeout=10)
if lock.acquire():
try:
# 临界区代码
pass
finally:
lock.release()
else:
# 获取锁失败,处理逻辑
pass
```
springboot加Redis实现分布式锁代码
好的,下面是使用Spring Boot和Redis实现分布式锁的示例代码:
```java
@Component
public class RedisLockUtil {
@Autowired
private RedisTemplate<String, Object> redisTemplate;
private static final String LOCK_PREFIX = "lock_";
private static final long LOCK_EXPIRE = 30 * 1000L; // 锁过期时间30秒
/**
* 获取锁
*
* @param key 锁的key
* @return 是否获取成功
*/
public boolean lock(String key) {
String lockKey = LOCK_PREFIX + key;
long now = System.currentTimeMillis();
long expireTime = now + LOCK_EXPIRE + 1; // 锁过期时间
boolean acquired = redisTemplate.opsForValue().setIfAbsent(lockKey, expireTime);
if (acquired) {
return true;
} else {
Long expire = redisTemplate.opsForValue().getOperations().getExpire(lockKey);
if (expire == -1) { // 如果key没有设置过期时间,直接设置过期时间
redisTemplate.expire(lockKey, LOCK_EXPIRE, TimeUnit.MILLISECONDS);
}
return false;
}
}
/**
* 释放锁
*
* @param key 锁的key
* @return 是否释放成功
*/
public boolean release(String key) {
String lockKey = LOCK_PREFIX + key;
Long expireTime = (Long) redisTemplate.opsForValue().get(lockKey);
if (expireTime == null) {
return true;
}
if (expireTime > System.currentTimeMillis()) {
redisTemplate.delete(lockKey);
return true;
} else {
return false;
}
}
}
```
在需要使用分布式锁的地方,注入RedisLockUtil,使用lock方法获取锁,使用release方法释放锁。
```java
@Autowired
private RedisLockUtil redisLockUtil;
public void doSomethingWithLock(String key) {
if (redisLockUtil.lock(key)) {
try {
// 执行业务逻辑
} finally {
redisLockUtil.release(key);
}
} else {
// 获取锁失败,处理逻辑
}
}
```
以上代码仅供参考,实际使用时需要根据实际情况进行修改和优化。