zoukankan      html  css  js  c++  java
  • 使用redis实现分布式锁

    class RedisDistributedLock(object):
    def __init__(self):
    self.redis_cli = distributed_lock_redis_client(timeout=1)
    self.lock_timeout = 10
    self.lock_key = "random_lock_key"
    self.now = long(time.time())
    self.timestamp = self.now + self.lock_timeout

    def getLock(self):
    try:
    lock = self.redis_cli.setnx(self.lock_key, self.timestamp)
    if lock == True:
    return True

    last_timestamp = self.redis_cli.get(self.lock_key)
    if last_timestamp and long(last_timestamp) <= self.now:
    self.redis_cli.getset(self.lock_key, self.timestamp)
    return True
    return False
    except Exception, ex:
    logger.exception("[RedisDistributedLock] getLock fail error=%s" % ex)


    def releaseLock(self):
    try:
    last_timestamp = self.redis_cli.get(self.lock_key)
    if last_timestamp and long(last_timestamp) == self.timestamp:
    self.redis_cli.delete(self.lock_key)
    except Exception, ex:
    logger.exception("[RedisDistributedLock] releaseLock fail error=%s" % ex)
  • 相关阅读:
    第九周学习进度
    用户场景描述
    第九天
    第10天
    求两个有序数组的中值
    计算字符串中最长子字符串的长度
    计算两个数之和
    将string 转int
    判断一个int 型整数 是否为回文数
    php 对象的一些特性
  • 原文地址:https://www.cnblogs.com/acvc/p/5926468.html
Copyright © 2011-2022 走看看