queue.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  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. }
  23. class QueueServer
  24. {
  25. private $_queuedb;
  26. public function __construct() {
  27. $this->_queuedb = new QueueDB();
  28. }
  29. public function pop($key,$time)
  30. {
  31. $result = $this->_queuedb->pop($key,$time);
  32. if($result != null) {
  33. return unserialize($result);
  34. } else {
  35. return false;
  36. }
  37. }
  38. public function scan() {
  39. return $this->_queuedb->scan();
  40. }
  41. }
  42. class QueueDB
  43. {
  44. private $_redis;
  45. private $_tb_prefix = 'QUEUE_TABLE_';
  46. //存定义存储表的数量,系统会随机分配存储
  47. private $_tb_num = 2;
  48. public function __construct()
  49. {
  50. if ( !extension_loaded('redis') ) {
  51. throw_exception('redis failed to load');
  52. }
  53. $this->_redis = new Redis();
  54. $this->_redis->connect(C('queue.host'),C('queue.port'),20);
  55. $this->_redis->setOption(Redis::OPT_READ_TIMEOUT, 10);
  56. }
  57. public function push($value)
  58. {
  59. try {
  60. return $this->_redis->lPush($this->_tb_prefix.rand(1,$this->_tb_num),$value);
  61. } catch(Exception $e) {
  62. throw_exception($e->getMessage());
  63. }
  64. }
  65. public function scan()
  66. {
  67. $list_key = array();
  68. for($i=1;$i<=$this->_tb_num;$i++) {
  69. $list_key[] = $this->_tb_prefix.$i;
  70. }
  71. return $list_key;
  72. }
  73. public function pop($key, $time)
  74. {
  75. try
  76. {
  77. if ($result = $this->_redis->brPop($key,$time)) {
  78. return $result[1];
  79. } else {
  80. return null;
  81. }
  82. }
  83. catch (Exception $e) {
  84. $err = $e->getMessage();
  85. $code = $e->getCode();
  86. Log::record("QueueDB pop err: code={$code} err={$err}",Log::ERR);
  87. return null;
  88. }
  89. }
  90. public function clear() {
  91. $this->_redis->flushAll();
  92. }
  93. }