Redis.php 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. <?php
  2. namespace laytp\library;
  3. use think\facade\Cache;
  4. /**
  5. * Redis锁
  6. */
  7. class Redis
  8. {
  9. /**
  10. * 得到一个redis锁,循环获取锁,直到获取到锁为止
  11. * @param $name string 锁名称
  12. * @param $ttl int 锁存在的时间,单位秒,默认60秒
  13. * @return bool
  14. */
  15. public static function getLock($name, $ttl=60)
  16. {
  17. set_time_limit(0);
  18. $redis = Cache::store('redis')->handler();
  19. while(true){
  20. if($redis->set($name, 1, ['NX', 'EX'=>$ttl])){
  21. break;
  22. }
  23. }
  24. return true;
  25. }
  26. /**
  27. * 得到一个redis锁,仅尝试获取一次
  28. *
  29. * @param $name string 锁名称
  30. * @param $ttl int 锁存在的时间,单位秒,默认60秒
  31. * @return bool
  32. */
  33. public static function getOnceLock($name, $ttl=60)
  34. {
  35. set_time_limit(0);
  36. $redis = Cache::store('redis')->handler();
  37. if($redis->set($name, 1, ['NX', 'EX'=>$ttl])){
  38. return true;
  39. }
  40. return false;
  41. }
  42. /**
  43. * 删除一个redis锁
  44. * @param $name string 锁名称
  45. * @return bool
  46. */
  47. public static function delLock($name)
  48. {
  49. $redis = Cache::store('redis')->handler();
  50. $redis->del($name);
  51. return true;
  52. }
  53. }