Redis实现分布式锁

2 篇文章 0 订阅

Redis实现分布式锁

方式1:

问题 : 如果具体业务代码抛出异常,redis锁无法释放,产生死锁

String lockKey = "product_stock";
// 等于setnx
Boolean result = stringRedisTemplate.opsForValue().setIfAbsent(lockKey,"value");
if(!result){
    return "error_code";
}
// 具体业务
stringRedisTemplate.delete(lockKey);

方式2:

问题 : 如果系统宕机无法释放锁

String lockKey = "product_stock";
// 等于setnx
Boolean result = stringRedisTemplate.opsForValue().setIfAbsent(lockKey,"value");
if(!result){
    return "error_code";
}
try{
    // 具体业务
}catch (Exception e){
    ...
}finally{
    stringRedisTemplate.delete(lockKey);
}

方式3:

问题 : 超时时间可能设置失败,系统宕机无法释放锁

String lockKey = "product_stock";
// 等于setnx
Boolean result = stringRedisTemplate.opsForValue().setIfAbsent(lockKey,"value");
// 设置超时时间
stringRedisTemplate.expire(lockKey,10,TimeUnit.SECONDS);
if(!result){
    return "error_code";
}
try{
    // 具体业务
}catch (Exception e){
    ...
}finally{
    stringRedisTemplate.delete(lockKey);
}

方式4:

问题 : 指定的过期时间不足,可能会释放其他线程的锁

String lockKey = "product_stock";
// 等于setnx
Boolean result = stringRedisTemplate.opsForValue().setIfAbsent(lockKey,"value",10,TimeUnit.SECONDS);
if(!result){
    return "error_code";
}
try{
    // 具体业务
}catch (Exception e){
    ...
}finally{
    stringRedisTemplate.delete(lockKey);
}

方式5:

问题 : 判断当前线程和删锁不是原子的,还是可能会删除其他线程的锁

String lockKey = "product_stock";
String clientId = UUID.randomUUID().toString();
// 等于setnx
Boolean result = stringRedisTemplate.opsForValue().setIfAbsent(lockKey,"value",10,TimeUnit.SECONDS);
if(!result){
    return "error_code";
}
try{
    // 具体业务
}catch (Exception e){
    ...
}finally{
    if (clientId.equals(stringRedisTemplate.opsForValue().get(lockKey))){
        stringRedisTemplate.delete(lockKey);
    }
}

Redisson实现分布式锁

1. 引入jar包

<dependence>
    <groupId>org.redisson</groupId>
    <artifactId>redisson</artifactId>
    <version>3.6.5</version>
</dependence>

初始化redis客户端

@Bean
public Redisson redisson(){
    // 此处为单机模式
    Config config  = new Config();
    config.useSingleServer().setAddress("redis://localhost:6379").setDarabase(0);
    return *(Redission) Redisson.create(config);
}

redisson分布式锁操作

String lockKey = "product_stock";
RLock redissonLock = redisso.getLock(lockKey);
try{
    redissonLock.lock();
    // 具体业务
}catch (Exception e){
    ...
}finally{
    redissonLock.unlock();
}

Zookeeper实现分布式锁与Redis实现分布式锁比较

zookeeper性能不如redis,因为zookeeper需要同步

zookeeper不会丢key,因为zookeeper保证了数据一致性

分布式锁优化

1. 采用分段思想,将共享资源分段加锁

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值