栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 前沿技术 > 大数据 > 大数据系统

Redis实现分布式锁

Redis实现分布式锁

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包

    org.redisson
    redisson
    3.6.5

初始化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();
}
redisson加锁逻辑

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-0sZtn67b-1639709433758)(C:Users鲁川AppDataRoamingTyporatypora-user-imagesimage-20211126163854801.png)]

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

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

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

分布式锁优化 1. 采用分段思想,将共享资源分段加锁
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/671263.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号