queue.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  1. <?php
  2. /**
  3. * 队列处理
  4. *
  5. *
  6. * @package
  7. */
  8. class QueueClient {
  9. private static $queuedb;
  10. /**
  11. * 入列
  12. * @param string $key
  13. * @param array $value
  14. */
  15. public static function push($key, $value) {
  16. if (!C('queue.open')) {
  17. Logic('queue')->$key($value);return;
  18. }
  19. if (!is_object(self::$queuedb)) {
  20. self::$queuedb = new QueueDB();
  21. }
  22. return self::$queuedb->push(serialize(array($key=>$value)));
  23. }
  24. }
  25. class QueueServer {
  26. private $_queuedb;
  27. public function __construct() {
  28. $this->_queuedb = new QueueDB();
  29. }
  30. /**
  31. * 取出队列
  32. * @param unknown $key
  33. */
  34. public function pop($key,$time) {
  35. return unserialize($this->_queuedb->pop($key,$time));
  36. }
  37. public function scan() {
  38. return $this->_queuedb->scan();
  39. }
  40. }
  41. class QueueDB {
  42. //定义对象
  43. private $_redis;
  44. //存储前缀
  45. private $_tb_prefix = 'QUEUE_TABLE_';
  46. //存定义存储表的数量,系统会随机分配存储
  47. private $_tb_num = 2;
  48. /**
  49. * 初始化
  50. */
  51. public function __construct() {
  52. if ( !extension_loaded('redis') ) {
  53. throw_exception('redis failed to load');
  54. }
  55. $this->_redis = new Redis();
  56. $this->_redis->connect(C('queue.host'),C('queue.port'),20);
  57. }
  58. /**
  59. * 入列
  60. * @param unknown $value
  61. */
  62. public function push($value) {
  63. try {
  64. return $this->_redis->lPush($this->_tb_prefix.rand(1,$this->_tb_num),$value);
  65. }catch(Exception $e) {
  66. throw_exception($e->getMessage());
  67. }
  68. }
  69. /**
  70. * 取得所有的list key(表)
  71. */
  72. public function scan() {
  73. $list_key = array();
  74. for($i=1;$i<=$this->_tb_num;$i++) {
  75. $list_key[] = $this->_tb_prefix.$i;
  76. }
  77. return $list_key;
  78. }
  79. /**
  80. * 出列
  81. * @param unknown $key
  82. */
  83. public function pop($key, $time) {
  84. try {
  85. if ($result = $this->_redis->brPop($key,$time)) {
  86. return $result[1];
  87. }
  88. } catch (Exception $e) {
  89. exit($e->getMessage());
  90. }
  91. }
  92. /**
  93. * 清空,暂时无用
  94. */
  95. public function clear() {
  96. $this->_redis->flushAll();
  97. }
  98. }