前言:
在分布式场景下,相信你或多或少需要使用分布式锁来访问临界资源,或者控制耗时操作的并发性。
当然,实现分布式锁的方案也比较多,比如数据库、redis、zk 等等。本文主要结合一个线上案例,讲解 redis 分布式锁的相关实现。
一、问题描述:
某天线上出现了数据重复处理问题,经排查后发现,竟然是单次处理时间较长,redis 分布式锁提前释放
导致相同请求并发处理。
其实,这是一个锁续约
的问题,对于一把分布式锁,我们需要考虑,设置锁多长时间过期、出现异常如何释放锁?
以上问题便是本文要讨论的主题。
二、原因分析:
项目采用较简单的自定义 redis 分布式锁,为避免死锁定义默认过期时间 10s,如下:
override fun lock() { while (true) { //尝试获取锁 if (trylock()) { return } try { thread.sleep(10) } catch (e: interruptedexception) { e.printstacktrace() } } } override fun trylock(): boolean { val value = getuniquesign() // 随机串 val flag = redistemplate!!.opsforvalue().setifabsent(name, value, 10000, timeunit.milliseconds) if (flag != null && flag) { value_local.set(value) into_num_local.set(if (into_num_local.get() != null) into_num_local.get() + 1 else 1) return true } return false }
缺乏对锁自动续期等实现。
三、解决方案:
1、思考:
针对这种场景,可以考虑的是如何给锁自动续期-当业务没有执行结束的情况下,当然也可以自定义实现 比如开一个后台线程定时的给这些拿到锁的线程续期。
redisson 也正是基于这种思路实现自动续期的分布式锁,各种异常情况也考虑的更加完善,综合考虑采用 redisson 的分布式锁解决方案优化。
2、redisson简单配置:
@configuration @enableconfigurationproperties(redissonproperties::class) class redissonconfig { @bean fun redissonclient(redissonproperties: redissonproperties): redissonclient { val config = config() val singleserverconfig = redissonproperties.singleserverconfig!! config.usesingleserver().setaddress(singleserverconfig.address) .setdatabase(singleserverconfig.database) .setusername(singleserverconfig.username) .setpassword(singleserverconfig.password) .setconnectionpoolsize(singleserverconfig.connectionpoolsize) .setconnectionminimumidlesize(singleserverconfig.connectionminimumidlesize) .setconnecttimeout(singleserverconfig.connecttimeout) .setidleconnectiontimeout(singleserverconfig.idleconnectiontimeout) .setretryinterval(singleserverconfig.retryinterval) .setretryattempts(singleserverconfig.retryattempts) .settimeout(singleserverconfig.timeout) return redisson.create(config) } } @configurationproperties(prefix = "xxx.redisson") class redissonproperties { var singleserverconfig: singleserverconfig? = null }
redis 服务使用的腾讯云的哨兵模式架构,此架构对外开放一个代理地址访问,因此这里配置单机模式配置即可。
如果你是自己搭建的 redis 哨兵模式架构,需要按照文档配置相关必要参数
3、使用样例:
... @autowired lateinit var redissonclient: redissonclient ... fun xxx() { ... val lock = redissonclient.getlock("mylock") lock.lock() try { ... } finally { lock.unlock() } ... }
使用方式和jdk提供的锁是不是很像?是不是很简单?
正是redisson这类优秀的开源产品的出现,才让我们将更多的时间投入到业务开发中...
四、源码分析
下面来看看 redisson 对常规分布式锁的实现,主要分析 redissonlock
1、lock加锁操作
@override public void lock() { try { lock(-1, null, false); } catch (interruptedexception e) { throw new illegalstateexception(); } } // 租约期限, 也就是expire时间, -1代表未设置 将使用系统默认的30s private void lock(long leasetime, timeunit unit, boolean interruptibly) throws interruptedexception { // 尝试拿锁, 如果能拿到就直接返回 long threadid = thread.currentthread().getid(); long ttl = tryacquire(-1, leasetime, unit, threadid); // lock acquired if (ttl == null) { return; } rfuture<redissonlockentry> future = subscribe(threadid); if (interruptibly) { commandexecutor.syncsubscriptioninterrupted(future); } else { commandexecutor.syncsubscription(future); } // 如果拿不到锁就尝试一直轮循, 直到成功获取锁或者异常终止 try { while (true) { ttl = tryacquire(-1, leasetime, unit, threadid); // lock acquired if (ttl == null) { break; } ... } } finally { unsubscribe(future, threadid); } }
1.1、tryacquire
private long tryacquire(long waittime, long leasetime, timeunit unit, long threadid) { return get(tryacquireasync(waittime, leasetime, unit, threadid)); } private <t> rfuture<long> tryacquireasync(long waittime, long leasetime, timeunit unit, long threadid) { rfuture<long> ttlremainingfuture; // 调用真正获取锁的操作 if (leasetime != -1) { ttlremainingfuture = trylockinnerasync(waittime, leasetime, unit, threadid, rediscommands.eval_long); } else { ttlremainingfuture = trylockinnerasync(waittime, internallockleasetime, timeunit.milliseconds, threadid, rediscommands.eval_long); } ttlremainingfuture.oncomplete((ttlremaining, e) -> { if (e != null) { return; } // lock acquired // 这里是成功获取了锁, 尝试给锁续约 if (ttlremaining == null) { if (leasetime != -1) { internallockleasetime = unit.tomillis(leasetime); } else { scheduleexpirationrenewal(threadid); } } }); return ttlremainingfuture; } // 通过lua脚本真正执行加锁的操作 <t> rfuture<t> trylockinnerasync(long waittime, long leasetime, timeunit unit, long threadid, redisstrictcommand<t> command) { // 如果key不存在, 那正好, 直接set并设置过期时间 // 如果key存在, 就有两种情况需要考虑 // - 同一线程获取重入锁,直接将field(也就是getlockname(threadid))对应的value值+1 // - 不同线程竞争锁, 此次加锁失败, 并直接返回此key对应的过期时间 return evalwriteasync(getrawname(), longcodec.instance, command, "if (redis.call('exists', keys[1]) == 0) then " + "redis.call('hincrby', keys[1], argv[2], 1); " + "redis.call('pexpire', keys[1], argv[1]); " + "return nil; " + "end; " + "if (redis.call('hexists', keys[1], argv[2]) == 1) then " + "redis.call('hincrby', keys[1], argv[2], 1); " + "redis.call('pexpire', keys[1], argv[1]); " + "return nil; " + "end; " + "return redis.call('pttl', keys[1]);", collections.singletonlist(getrawname()), unit.tomillis(leasetime), getlockname(threadid)); }
1.2、续约
通过 scheduleexpirationrenewal 给锁续约
protected void scheduleexpirationrenewal(long threadid) { expirationentry entry = new expirationentry(); expirationentry oldentry = expiration_renewal_map.putifabsent(getentryname(), entry); if (oldentry != null) { oldentry.addthreadid(threadid); } else { entry.addthreadid(threadid); // 续约操作 renewexpiration(); } } private void renewexpiration() { expirationentry ee = expiration_renewal_map.get(getentryname()); if (ee == null) { return; } // 设置延迟任务task, 在时长internallockleasetime/3之后执行, 定期给锁续期 timeout task = commandexecutor.getconnectionmanager().newtimeout(new timertask() { @override public void run(timeout timeout) throws exception { expirationentry ent = expiration_renewal_map.get(getentryname()); if (ent == null) { return; } long threadid = ent.getfirstthreadid(); if (threadid == null) { return; } // 真正执行续期命令操作 rfuture<boolean> future = renewexpirationasync(threadid); future.oncomplete((res, e) -> { if (e != null) { log.error("can't update lock " + getrawname() + " expiration", e); expiration_renewal_map.remove(getentryname()); return; } // 这次续期之后, 继续schedule自己, 达到持续续期的效果 if (res) { // reschedule itself renewexpiration(); } }); } }, internallockleasetime / 3, timeunit.milliseconds); ee.settimeout(task); } // 所谓续期, 就是将expire过期时间再延长 protected rfuture<boolean> renewexpirationasync(long threadid) { // 如果key以及当前线程存在, 则延长expire时间, 并返回1代表成功;否则返回0代表失败 return evalwriteasync(getrawname(), longcodec.instance, rediscommands.eval_boolean, "if (redis.call('hexists', keys[1], argv[2]) == 1) then " + "redis.call('pexpire', keys[1], argv[1]); " + "return 1; " + "end; " + "return 0;", collections.singletonlist(getrawname()), internallockleasetime, getlockname(threadid)); }
2、unlock解锁操作
public void unlock() { try { get(unlockasync(thread.currentthread().getid())); } catch (redisexception e) { ... } } public rfuture<void> unlockasync(long threadid) { rpromise<void> result = new redissonpromise<>(); // 执行解锁操作 rfuture<boolean> future = unlockinnerasync(threadid); // 操作成功之后做的事 future.oncomplete((opstatus, e) -> { // 取消续约task cancelexpirationrenewal(threadid); ... }); return result; } protected rfuture<boolean> unlockinnerasync(long threadid) { // 如果key以及当前线程对应的记录已经不存在, 直接返回空 // 否在将field(也就是getlockname(threadid))对应的value减1 // - 如果减去1之后值还大于0, 那么重新延长过期时间 // - 如果减去之后值小于等于0, 那么直接删除key, 并发布订阅消息 return evalwriteasync(getrawname(), longcodec.instance, rediscommands.eval_boolean, "if (redis.call('hexists', keys[1], argv[3]) == 0) then " + "return nil;" + "end; " + "local counter = redis.call('hincrby', keys[1], argv[3], -1); " + "if (counter > 0) then " + "redis.call('pexpire', keys[1], argv[2]); " + "return 0; " + "else " + "redis.call('del', keys[1]); " + "redis.call('publish', keys[2], argv[1]); " + "return 1; " + "end; " + "return nil;", arrays.aslist(getrawname(), getchannelname()), lockpubsub.unlock_message, internallockleasetime, getlockname(threadid)); }
以上便是 redisson 客户端工具对 redis 分布式锁的加/解锁具体实现,主要解决了以下几个问题
1、死锁问题:设置过期时间
2、可重入问题:重入+1, 释放锁-1,当值=0时代表完全释放锁
3、续约问题:可解决锁提前释放问题
4、锁释放:谁加锁就由谁来释放
总结:
本文由一个线上问题做引子,通过 redis 分布式锁的常用实现方案,最终选定 redisson 的解决方案; 并分析 redisson 的具体实现细节
相关参考:
- redisson官方文档 - 分布式锁和同步器
- redisson官方文档 - 配置方法
- csdn - 如何使用redis实现分布式锁?
到此这篇关于redisson如何解决redis分布式锁提前释放问题的文章就介绍到这了,更多相关redis分布式锁提前释放内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!