queue.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * 队列处理
  5. *
  6. *
  7. * @package
  8. */
  9. class QueueClient
  10. {
  11. private static $queuedb;
  12. public static function push($key, $value)
  13. {
  14. if (!C('queue.open')) {
  15. Logic('queue')->$key($value); //如果队列没打开,立即执行
  16. return;
  17. }
  18. if (!is_object(self::$queuedb)) {
  19. self::$queuedb = new QueueDB();
  20. }
  21. return self::$queuedb->push(serialize([$key=>$value]));
  22. }
  23. public static function async_push($key, $value, $period_secs = 0)
  24. {
  25. if($period_secs > 0) {
  26. $model_cron = Model('cron');
  27. return $model_cron->addCron(['params' => serialize([$key=>$value]),'type' => 8,'exeid' => 0,'exetime' => time() + $period_secs]);
  28. }
  29. else {
  30. return self::push($key,$value);
  31. }
  32. }
  33. }
  34. class QueueServer
  35. {
  36. private $_queuedb;
  37. public function __construct() {
  38. $this->_queuedb = new QueueDB();
  39. }
  40. public function pop($key,$time)
  41. {
  42. $result = $this->_queuedb->pop($key,$time);
  43. if($result != null) {
  44. return unserialize($result);
  45. } else {
  46. return false;
  47. }
  48. }
  49. public function scan() {
  50. return $this->_queuedb->scan();
  51. }
  52. }
  53. class QueueDB
  54. {
  55. private $_redis;
  56. private $_tb_prefix = 'QUEUE_TABLE_';
  57. //存定义存储表的数量,系统会随机分配存储
  58. private $_tb_num = 2;
  59. public function __construct()
  60. {
  61. if ( !extension_loaded('redis') ) {
  62. throw_exception('redis failed to load');
  63. }
  64. $this->_redis = new Redis();
  65. $this->_redis->connect(C('queue.host'),C('queue.port'),20);
  66. $this->_redis->setOption(Redis::OPT_READ_TIMEOUT, 10);
  67. }
  68. public function push($value)
  69. {
  70. try {
  71. return $this->_redis->lPush($this->_tb_prefix.rand(1,$this->_tb_num),$value);
  72. } catch(Exception $e) {
  73. throw_exception($e->getMessage());
  74. }
  75. }
  76. public function scan()
  77. {
  78. $list_key = [];
  79. for($i=1;$i<=$this->_tb_num;$i++) {
  80. $list_key[] = $this->_tb_prefix.$i;
  81. }
  82. return $list_key;
  83. }
  84. public function pop($key, $time)
  85. {
  86. $result = $this->_redis->brPop($key, $time);
  87. if ($result) {
  88. return $result[1];
  89. } else {
  90. return null;
  91. }
  92. }
  93. public function clear() {
  94. $this->_redis->flushAll();
  95. }
  96. }