queue.php 2.9 KB

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