在aioredis中提供分布式锁的包装器

aioredis-lock的Python项目详细描述


CircleCI

使用基于异步的redis客户端aioredis实现分布式锁定。

这是一个独立的lib,直到并且如果,aio-libs/aioredis#573被接受。

用法

您需要已经创建了aioredis.RedisConnectionaioredis.ConnectionsPool

互斥

fromaioredis_lockimportRedisLock,LockTimeoutErrortry:asyncwithRedisLock(pool,key="foobar",# how long until the lock should expire (seconds). this can be extended# via `await lock.extend(30)`timeout=30,# you can customize how long to allow the lock acquisitions to be# attempted.wait_timeout=30,)aslock:# If you get here, you now have a lock and are the only program that# should be running this code at this moment.# do some work...# we may want it longer...awaitlock.extend(30)exceptLockTimeoutError:# The lock could not be acquired by this worker and we should give uppass

简单的领导者/追随者

假设您需要一个简单的leader/follower类型的实现,其中有许多web工作者,但只希望1执行一个重复的任务。万一领导失败了,应该由别人来接手。只需通过wait_timeout=None来重新锁定,允许工作进程在领导最终失败时继续尝试获取锁。这里的主要复杂性是扩展锁并验证领导者仍然拥有它。

fromaioredis_lockimportRedisLock# if the lock is lost, we still want to be a followerwhileTrue:# wait indefinitely to acquire a lockasyncwithRedisLock(pool,"shared_key",wait_timeout=None)aslock:# hold the lock as long as possiblewhileTrue:ifnotawaitlock.is_owner():logger.debug("We are no longer the lock owner, falling back")break# do some workifnotawaitlock.renew():logger.debug("We lost the lock, falling back to follower mode")break

这主要代表了选拔领导的工作,更重要的是提拔领导。

欢迎加入QQ群-->: 979659372 Python中文网_新手群

推荐PyPI第三方库


热门话题
ByteArrayOutputStream的java解码属性   java S3 SDK在上载时更新单个对象,而不是创建新文件   java hibernate:无法从eclipse连接到DB   java如何在强制转换JComboBox之前检查其类型?   http从Java中的GETPOST请求方法捕获URI、资源名称,如开发人员工具中所示   java在Spring@Bean方法中返回接口的局限性   Java中的Web服务和客户端(使用Eclipse Apache Axis 2自底向上服务)某些代码会引发异常   java spring安全+rest不起作用   java将LinkedList添加到包含LinkedList的LinkedList并更改添加的LinkedList   java是否临时删除对象的属性?   java使用AnimatedGifEncoder类创建的gif图像的部分帧是不透明的   java如何高效地处理maven3时间戳快照?   java向集合对象添加另一项   java如何将动态参数传递给jquery函数   java使用libGdx桌面端口作为Android GLES20的仿真器