<?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测试工具测试