123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657 |
- <?php
- namespace laytp\library;
- use think\facade\Cache;
- /**
- * Redis锁
- */
- class Redis
- {
- /**
- * 得到一个redis锁,循环获取锁,直到获取到锁为止
- * @param $name string 锁名称
- * @param $ttl int 锁存在的时间,单位秒,默认60秒
- * @return bool
- */
- public static function getLock($name, $ttl=60)
- {
- set_time_limit(0);
- $redis = Cache::store('redis')->handler();
- while(true){
- if($redis->set($name, 1, ['NX', 'EX'=>$ttl])){
- break;
- }
- }
- return true;
- }
- /**
- * 得到一个redis锁,仅尝试获取一次
- *
- * @param $name string 锁名称
- * @param $ttl int 锁存在的时间,单位秒,默认60秒
- * @return bool
- */
- public static function getOnceLock($name, $ttl=60)
- {
- set_time_limit(0);
- $redis = Cache::store('redis')->handler();
- if($redis->set($name, 1, ['NX', 'EX'=>$ttl])){
- return true;
- }
- return false;
- }
- /**
- * 删除一个redis锁
- * @param $name string 锁名称
- * @return bool
- */
- public static function delLock($name)
- {
- $redis = Cache::store('redis')->handler();
- $redis->del($name);
- return true;
- }
- }
|