CI項目設計Redis隊列
阿新 • • 發佈:2018-05-18
其他 rip 因此 設計 taf range 分配 basepath ins 項目開發過程中需要設計提供可平衡的處理多個用戶請求的隊列。
需求:
當用戶登錄後,查看系統中已經登錄的管理員隊列,然後查看後臺管理員的處理能力,如果已經不能處理新的請求,則把該管理員從處理隊列中刪除,否則把
該管理員分配給該用戶,管理員的處理能力減一,系統當前所指向的管理員+1即指向下一位可以處理問題的管理員。
分析:
最簡單的設計就是維護一個循環鏈表的隊列,可以方便的刪除和修改信息,但是Redis中並不能處理這樣復制的結構信息,因此只能另辟蹊徑了,考慮使用
二重的結構來轉換循環鏈表結構。先看下原來的結構:
這樣的結構可以方便的處理問題,不過在redis中存儲這樣的結構並不能輕易的做到,於是考慮使用用戶ID建立隊列list,然後使用用戶ID建立(key,value),當然也可以把
用戶的信息建立一個以ID為KEY的list,於是經過這樣的二級結構的轉換,Redis就可以處理原本復雜的結構了,這裏處理的時候,先檢查主隊列元素,然後根據以值為
Key來獲取其他復雜的信息進行處理,這樣設計的結構:
這樣的結構,無論刪除或者添加都必須操作兩個地方....以操作的復雜性換取存儲的復雜性,未必設計的好,不過先用來實現功能再說吧。
Redis類:
- <?php
- if (!defined(‘BASEPATH‘))
- exit(‘No direct script access allowed‘);
- class Redisdb {
- private $size ;
- private $redis ;
- private $channel_queue;
- private $current_index ;
- public function __construct() {
- $this->size = 100;
- $this->redis = new Redis();
- $this->channel_queue = ‘staffs‘;
- $this->redis->connect(‘127.0.0.1‘, ‘6379‘);
- $this->set_index();
- }
- public function set_index($index=0){
- $this->redis->set(‘current_index‘,$index);
- }
- public function en_queue($key,$value) {
- return $this->redis->rpush($this->channel_queue, $key) && $this->redis->set($key,$value);;
- }
- public function is_empty(){
- return $this->redis->lsize(‘admins‘)<=0;
- }
- public function is_full(){
- return $this->redis->lsize($this->channel_queue) >= $this->size;
- }
- public function remove($value){
- return $this->redis->lrem($this->channel_queue,$value);
- }
- public function get_list(){
- return $this->redis->lrange($this->channel_queue,0,-1);
- }
- public function delete_key($key){
- return $this->redis->delete($key);
- }
- public function get_value($key){
- return $this->redis->get($key);
- }
- public function allocate_admin(){
- $index = $this->redis->get(‘current_index‘);
- $size = $this->redis->lsize(‘admins‘);
- if($size ==0){
- return false;
- }
- if($index<$size){
- $key = $this->redis->lindex(‘staffs‘,$index);
- if($this->redis->get($key)<=1){
- $this->remove($key);
- return $key;
- }else{
- $this->redis->decr($key);
- $this->redis->incr(‘current_index‘);
- return $key ;
- }
- }else{
- $this->redis->set(‘current_index‘,0);
- $this->allocate_admin();
- }
- }
- }
CI項目設計Redis隊列