• php实现redis锁机制


    <?php
    
    class Redis_lock
    {
    
        public static function getRedis()
        {
            $redis = new redis();
            $redis->connect('127.0.0.1', 3838, 0);
            $redis->auth('xxx');
            return $redis;
        }
    
        public static function lock($key, $expire = 60)
        {
            if(!$key) {
                return false;
            }
            $redis = self::getRedis();
            do {
                if($acquired = ($redis->setnx("Lock:{$key}", time()))) { // 如果redis不存在,则成功
                    $redis->expire($key, $expire);
                    break;
                }
    
                usleep($expire);
    
            } while (true);
    
            return true;
        }
    
        //释放锁
        public static function release($key)
        {
            if(!$key) {
                return false;
            }
            $redis = self::getRedis();
            $redis->del("Lock:{$key}");
            $redis->close();
        }
    
    
    }
    
    
    $redis = Redis_lock::getRedis();
    Redis_lock::lock('lock');
    $re = $redis->get('Sentiger');
    $re--;
    $redis->set('Sentiger', $re);
    Redis_lock::release('lock');
    
    
    
    ?>

    测试可以 用ab测试工具测试

  • 相关阅读:
    Springmvc数据验证
    Springmvc文件上传
    BaseController
    说说NSProxy
    Objective-C的动态设计
    UITableView卡片式分组
    RunLoop应用之性能优化
    OC与JS交互之JavaScriptCore
    Core Data 迁移
    一个广告轮播视图的实现
  • 原文地址:https://www.cnblogs.com/shiwenhu/p/5303008.html
Copyright © 2020-2023  润新知