瀏覽代碼

处理redis

panda 5 月之前
父節點
當前提交
99a5528694
共有 1 個文件被更改,包括 4 次插入22 次删除
  1. 4 22
      application/common/controller/Api.php

+ 4 - 22
application/common/controller/Api.php

@@ -3,6 +3,7 @@
 namespace app\common\controller;
 
 use app\common\library\Auth;
+use app\utils\RedisUtil;
 use think\Config;
 use think\exception\HttpResponseException;
 use think\exception\ValidateException;
@@ -369,11 +370,11 @@ class Api
     /**
      * 接口请求限制
      * @param int $apiLimit
-     * @param int $apiLimitTime
+     * @param int $apiLimitTime 单位:秒(s)
      * @param string $key
      * @return bool | true:通过 false:拒绝
      */
-    public function apiLimit($apiLimit = 1, $apiLimitTime = 1000, $key = '')
+    public function apiLimit($apiLimit = 1, $apiLimitTime = 1, $key = '')
     {
         $userId = $this->auth->id;
         $controller = request()->controller();
@@ -383,28 +384,9 @@ class Api
             $key = strtolower($controller) . '_' . strtolower($action) . '_' . $userId;
         }
 
-        $redis = new Redis();
-        $redisconfig = config("redis");
-        $redis->connect($redisconfig["host"], $redisconfig["port"]);
-        if ($redisconfig['redis_pwd']) {
-            $redis->auth($redisconfig['redis_pwd']);
-        }
-        if($redisconfig['redis_selectdb'] > 0){
-            $redis->select($redisconfig['redis_selectdb']);
-        }
-
-        //
-        //指定键值新增+1 并获取
-        $count = $redis->incr($key);
-        if ($count > $apiLimit) {
+        if (!RedisUtil::getInstance($key)->tryTimes($apiLimit,intval($apiLimitTime))){
             return false;
         }
-
-        //设置过期时间
-        if ($count == 1) {
-            $redis->pExpire($key, $apiLimitTime);
-        }
-
         return true;
     }