1. 程式人生 > >CI項目設計Redis隊列

CI項目設計Redis隊列

其他 rip 因此 設計 taf range 分配 basepath ins

項目開發過程中需要設計提供可平衡的處理多個用戶請求的隊列。 需求: 當用戶登錄後,查看系統中已經登錄的管理員隊列,然後查看後臺管理員的處理能力,如果已經不能處理新的請求,則把該管理員從處理隊列中刪除,否則把 該管理員分配給該用戶,管理員的處理能力減一,系統當前所指向的管理員+1即指向下一位可以處理問題的管理員。 分析: 最簡單的設計就是維護一個循環鏈表的隊列,可以方便的刪除和修改信息,但是Redis中並不能處理這樣復制的結構信息,因此只能另辟蹊徑了,考慮使用 二重的結構來轉換循環鏈表結構。先看下原來的結構: 技術分享圖片 這樣的結構可以方便的處理問題,不過在redis中存儲這樣的結構並不能輕易的做到,於是考慮使用用戶ID建立隊列list,然後使用用戶ID建立(key,value),當然也可以把 用戶的信息建立一個以ID為KEY的list,於是經過這樣的二級結構的轉換,Redis就可以處理原本復雜的結構了,這裏處理的時候,先檢查主隊列元素,然後根據以值為 Key來獲取其他復雜的信息進行處理,這樣設計的結構: 技術分享圖片 這樣的結構,無論刪除或者添加都必須操作兩個地方....以操作的復雜性換取存儲的復雜性,未必設計的好,不過先用來實現功能再說吧。 Redis類:
  1. <?php
  2. if (!defined(‘BASEPATH‘))
  3. exit(‘No direct script access allowed‘);
  4. class Redisdb {
  5. private $size ;
  6. private $redis ;
  7. private $channel_queue;
  8. private $current_index ;
  9. public function __construct() {
  10. $this->size = 100;
  11. $this->redis = new Redis();
  12. $this->channel_queue = ‘staffs‘;
  13. $this->redis->connect(‘127.0.0.1‘, ‘6379‘);
  14. $this->set_index();
  15. }
  16. public function set_index($index=0){
  17. $this->redis->set(‘current_index‘,$index);
  18. }
  19. public function en_queue($key,$value) {
  20. return $this->redis->rpush($this->channel_queue, $key) && $this->redis->set($key,$value);;
  21. }
  22. public function is_empty(){
  23. return $this->redis->lsize(‘admins‘)<=0;
  24. }
  25. public function is_full(){
  26. return $this->redis->lsize($this->channel_queue) >= $this->size;
  27. }
  28. public function remove($value){
  29. return $this->redis->lrem($this->channel_queue,$value);
  30. }
  31. public function get_list(){
  32. return $this->redis->lrange($this->channel_queue,0,-1);
  33. }
  34. public function delete_key($key){
  35. return $this->redis->delete($key);
  36. }
  37. public function get_value($key){
  38. return $this->redis->get($key);
  39. }
  40. public function allocate_admin(){
  41. $index = $this->redis->get(‘current_index‘);
  42. $size = $this->redis->lsize(‘admins‘);
  43. if($size ==0){
  44. return false;
  45. }
  46. if($index<$size){
  47. $key = $this->redis->lindex(‘staffs‘,$index);
  48. if($this->redis->get($key)<=1){
  49. $this->remove($key);
  50. return $key;
  51. }else{
  52. $this->redis->decr($key);
  53. $this->redis->incr(‘current_index‘);
  54. return $key ;
  55. }
  56. }else{
  57. $this->redis->set(‘current_index‘,0);
  58. $this->allocate_admin();
  59. }
  60. }
  61. }

CI項目設計Redis隊列