RedisQueue.Class.php 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. <?php
  2. namespace Mall\Framework\Core;
  3. use Mall\Framework\Cache\Redis;
  4. class RedisQueue
  5. {
  6. public static $prefix = 'queue::';
  7. public static $queueName = 'public_queue';
  8. protected static $_instance;
  9. /** @var Redis $redis */
  10. protected static $redis;
  11. /**
  12. * @param Redis $redis redis实例
  13. * @param string $queueName 队列名称
  14. *
  15. * @return mixed
  16. *
  17. * @throws \Exception
  18. */
  19. public static function getInstance(Redis $redis ,$queueName = 'public_queue')
  20. {
  21. if ($redis instanceof \Redis) {
  22. throw new \Exception('Redis driver not null');
  23. }
  24. self::$redis = $redis;
  25. self::setQueueName($queueName);
  26. $key = md5(self::$queueName);
  27. if (!isset(self::$_instance[$key])) {
  28. self::$_instance[$key] = new self();
  29. }
  30. return self::$_instance[$key];
  31. }
  32. public static function setQueueName($queueName)
  33. {
  34. if ($queueName) {
  35. self::$queueName = self::$prefix . $queueName;
  36. }
  37. }
  38. /**
  39. * 添加队列
  40. *
  41. * @param string $value 存储的队列
  42. *
  43. * @return bool
  44. */
  45. public static function push($value)
  46. {
  47. return self::$redis->push(self::$queueName, $value, 'start');
  48. }
  49. /**
  50. * 从队列取出数据
  51. *
  52. * @param int $number 数量
  53. *
  54. * @return array
  55. */
  56. public static function pop($number = 1)
  57. {
  58. $result = [];
  59. for ($i = 0; $i < $number; $i++) {
  60. if ($value = self::$redis->pop(self::$queueName, 'end')) {
  61. $result[] = $value;
  62. }
  63. }
  64. return $result;
  65. }
  66. /**
  67. * 删除队列
  68. */
  69. public static function flushQueue()
  70. {
  71. return self::$redis->delete(self::$queueName);
  72. }
  73. /**
  74. * 返回队列的长度
  75. */
  76. public function llen()
  77. {
  78. return self::$redis->llen(self::$queueName);
  79. }
  80. /**
  81. * 查看队列的 key 是否存在
  82. */
  83. public function has()
  84. {
  85. return self::$redis->has(self::$queueName);
  86. }
  87. }