php limit限流,php+redis 限流
## 思路
### 用戶請求限限流(同接口訪問時間限制)
> redis key 接品名+ user_id 每訪問一次+1 過期時間為限制訪問時間
```php
_user_id = (int)$params['user_id'];
$this->_search_key = $params['apiName'].$this->_prefix;
$this->_key = $this->_search_key.$params['user_id'];
$this->_expireat_time = 60;##配置項
$this->_user_max_limit = 100;##配置項
$this->_max_limit = 100;##配置項
}
/**
* [userLimit 是否達(dá)到單用戶接口請求峰值]
* @Author Jerry (wx621201)
* @DateTime 2019-08-02T15:35:52+0800
* @Example eg:
* @return [type] [description]
*/
public function checkUserLimit(){
if($this->_user_max_limit==0) return true;//0不限流,不存在防刷,可以購買
##如果不存在,說明超過一分鐘,給SQL攔截
$matchNum = $this->_exists();
$matchNum = (int)$matchNum?$matchNum:0;
if($matchNum>$this->_user_max_limit) return false;##達(dá)到限流條件
$this->_set($matchNum+1);
return true;##默認(rèn)通過
}
/**
* [countLimit 是否達(dá)到用戶限流數(shù)]
* @Author Jerry (c84133883)
* @DateTime 2019-08-05T10:26:39+0800
* @Example eg:
* @return [type] [description]
*/
public function checkCountLimit(){
if($this->_max_limit==0) return true;//0不限流
if($this->_userCount>$this->_max_limit){
return false;
}else{
return true;
}
}
/**
* [_userCount 總用戶數(shù)]
* @Author Jerry (wx621201)
* @DateTime 2019-08-02T15:41:08+0800
* @Example eg:
* @return [type] [description]
*/
private function _userCount(){
$list = redis::scene($this->_scene)->keys($this->_search_key.'*');
return count($list);
}
/**
* [_set description]
* @Author Jerry (wx621201)
* @DateTime 2019-08-02T15:45:51+0800
* @Example eg:
* @param [type] $key [description]
* @param [type] $value [description]
* @param integer $time [description]
* @param string $scene [description]
*/
private function _set($value){
redis::scene($this->_scene)->set($this->_key,$value);
##處理過期時間
$expiretime = time()+(float)$this->_expireat_time;##1分鐘
redis::scene($this->_scene)->expireat($this->_key,$expiretime);
return ture;
}
/**
* [_exists 檢查是否存在]
* @Author Jerry (wx621201)
* @DateTime 2019-08-02T15:45:54+0800
* @Example eg:
* @param [type] $key [description]
* @param string $scene [description]
* @return [type] [description]
*/
private function _exists(){
if(!redis::scene($this->_scene)->exists($this->_key)||!redis::scene($this->_scene)->get($this->_key)){
return false;
}
return redis::scene($this->_scene)->get($this->_key);
}
}
```
### 總的用戶限流
#### 求合上面的key數(shù),得出當(dāng)前所在的用戶數(shù)量
### 所有請求限流
#### 思路1 通過IP限流
總結(jié)
以上是生活随笔為你收集整理的php limit限流,php+redis 限流的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 查看oracle连接数满了的记录,查看O
- 下一篇: oracle result_cache_