queue.php 2.5 KB

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