queue.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118
  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. private $_tb_tmp = 'TMP_TABLE';
  50. /**
  51. * 初始化
  52. */
  53. public function __construct() {
  54. if ( !extension_loaded('redis') ) {
  55. throw_exception('redis failed to load');
  56. }
  57. $this->_redis = new Redis();
  58. $this->_redis->connect(C('queue.host'),C('queue.port'));
  59. }
  60. /**
  61. * 入列
  62. * @param unknown $value
  63. */
  64. public function push($value) {
  65. try {
  66. return $this->_redis->lPush($this->_tb_prefix.rand(1,$this->_tb_num),$value);
  67. }catch(Exception $e) {
  68. throw_exception($e->getMessage());
  69. }
  70. }
  71. /**
  72. * 取得所有的list key(表)
  73. */
  74. public function scan() {
  75. $list_key = array();
  76. for($i=1;$i<=$this->_tb_num;$i++) {
  77. $list_key[] = $this->_tb_prefix.$i;
  78. }
  79. return $list_key;
  80. }
  81. /**
  82. * 出列
  83. * @param unknown $key
  84. */
  85. public function pop($key, $time) {
  86. try {
  87. if ($result = $this->_redis->brPop($key,$time)) {
  88. return $result[1];
  89. }
  90. } catch (Exception $e) {
  91. exit($e->getMessage());
  92. }
  93. }
  94. /**
  95. * 清空,暂时无用
  96. */
  97. public function clear() {
  98. $this->_redis->flushAll();
  99. }
  100. }