Browse Source

首页匹配,加防重复

lizhen_gitee 1 year ago
parent
commit
abf72cec4d
1 changed files with 53 additions and 5 deletions
  1. 53 5
      application/api/controller/Index.php

+ 53 - 5
application/api/controller/Index.php

@@ -4,6 +4,7 @@ namespace app\api\controller;
 
 use app\common\controller\Api;
 use think\Db;
+use think\Cache;
 /**
  * 首页接口
  */
@@ -220,7 +221,12 @@ class Index extends Api
 
         //检查剩余次数
 
+        //缓存,防重复
+        $user_id = $this->auth->id;
+        $user_id_redis = 'u_'.$user_id;
+        $redis_ids = json_decode(Cache::get($user_id_redis),true);
 
+        //where
         $where = [
             'user.id' => ['neq',$this->auth->id],
             'user.status' => 1,
@@ -238,15 +244,57 @@ class Index extends Api
             $where['user.id'] = ['NOTIN',$black_ids];
         }
 
+        //匹配一个
+        $result = $this->pipei_action($redis_ids,$where);
 
-        $list = Db::name('user')->alias('user')
-            ->join('user_active active' ,'user.id = active.user_id','LEFT')
-            ->where($where)
-            ->column('user.id');
+        //匹配不到,移除防重复
+        if(!$result) {
+            Cache::rm($user_id_redis);
+            $redis_ids = [];
+            $result = $this->pipei_action($redis_ids,$where);
+        }
+        // 追加一个防重复
+        if($result){
+            if($redis_ids) {
+                $redis_ids[] = $result;
+            } else {
+                $redis_ids = [$result];
+            }
+            Cache::set($user_id_redis,json_encode($redis_ids));
+        }else{
+            Cache::rm($user_id_redis);
+        }
 
-        $this->success(1,$list);
+        $this->success(1,$result);
+    }
 
+    private function pipei_action($redis_ids,$where){
+        $where_op = [];
+        if(!empty($redis_ids)){
+            $where_op['user.id'] = ['NOTIN',$redis_ids];
+        }
+
+        $result = Db::name('user')->alias('user')
+            ->join('user_active active' ,'user.id = active.user_id','LEFT')
+            ->where($where)
+            ->where($where_op)
+            ->orderRaw('rand()')
+            ->value('user.id');
 
+        return $result;
+    }
+///////////////////////////////////
+    public function test(){
+        //缓存,防重复
+        $user_id = $this->auth->id;
+        $user_id_redis = 'u_'.$user_id;
+        $redis_ids = json_decode(Cache::get($user_id_redis),true);
+        dump($redis_ids);
+    }
+    public function testrm(){
+        $user_id = $this->auth->id;
+        $user_id_redis = 'u_'.$user_id;
+        Cache::rm($user_id_redis);
     }