Browse Source

修改redis配置,redis参数名,site配置写入到redis,redisutil类库

lizhen_gitee 4 months ago
parent
commit
71243df6b6

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

@@ -386,11 +386,11 @@ class Api
         $redis = new Redis();
         $redisconfig = config("redis");
         $redis->connect($redisconfig["host"], $redisconfig["port"]);
-        if ($redisconfig['redis_pwd']) {
-            $redis->auth($redisconfig['redis_pwd']);
+        if ($redisconfig['password']) {
+            $redis->auth($redisconfig['password']);
         }
-        if($redisconfig['redis_selectdb'] > 0){
-            $redis->select($redisconfig['redis_selectdb']);
+        if($redisconfig['select'] > 0){
+            $redis->select($redisconfig['select']);
         }
 
         //
@@ -465,93 +465,9 @@ class Api
         }
     }
 
-    //更新用户活跃
-    protected function user_active(){
-        if($this->auth->isLogin()){
-            db('user_active')->where('user_id',$this->auth->id)->update(['requesttime'=>time()]);
-        }
-    }
 
-    //获取用户是否活跃,7200秒,2小时
-    //1活跃,0不活跃
-    protected function user_activeinfo($user_id,$requesttime = 0){
-
-        if(empty($requesttime)){
-            $requesttime = db('user_active')->where('user_id',$user_id)->value('requesttime');
-        }
 
-        $result = [
-            'is_active' => 1,
-            'active_text' => get_last_time($requesttime).'在线',
-        ];
 
-        if(time() - $requesttime > 7200){
-            $result = [
-                'is_active' => 0,
-                'active_text' => '离线',
-            ];
-        }
 
-        return $result;
-    }
-
-    //获取用户是否vip,1是,0否
-    protected function is_vip($user_id){
-        $result = 0;
-
-        $vip_endtime = db('user_wallet')->where('user_id',$user_id)->value('vip_endtime');
-        $result = $vip_endtime > time() ? 1 : 0;
-
-        return $result;
-    }
-
-    //用户是否有某项权限
-    //1有,0没有
-    protected function user_power($user_id,$power = ''){
-        $is_vip = $this->is_vip($user_id);
-        if($is_vip != 1){
-            return 0;
-        }
-        $power = db('user_power')->where('user_id',$user_id)->value($power);
-        return $power;
 
-    }
-
-    //是否关注
-    protected function is_follow($uid,$follow_uid){
-        $where = [
-            'uid' => $uid,
-            'follow_uid' => $follow_uid,
-        ];
-        $check = db('user_follow')->where($where)->find();
-        if($check){
-            return 1;
-        }else{
-            return 0;
-        }
-    }
-
-    //是否拉黑
-    protected function is_black($uid,$black_user_id){
-        $where = [
-            'user_id' => $uid,
-            'black_user_id' => $black_user_id,
-        ];
-        $check = db('user_blacklist')->where($where)->find();
-        if($check){
-            return 1;
-        }else{
-            return 0;
-        }
-    }
-
-    //是否好友
-    protected function is_friend($uid,$follow_uid){
-        $is_follow = $this->is_follow($uid,$follow_uid);
-        $be_follow = $this->is_follow($follow_uid,$uid);
-        if($is_follow && $be_follow){
-            return 1;
-        }
-        return 0;
-    }
 }

+ 2 - 2
application/common/library/token/driver/Redis.php

@@ -33,8 +33,8 @@ class Redis extends Driver
         $redis_config = config('redis');
         $this->options['host']     = $redis_config['host'];
         $this->options['port']     = $redis_config['port'];
-        $this->options['password'] = $redis_config['redis_pwd'];
-        $this->options['select']   = $redis_config['redis_selectdb'];
+        $this->options['password'] = $redis_config['password'];
+        $this->options['select']   = $redis_config['select'];
 
         if (!extension_loaded('redis')) {
             throw new \BadFunctionCallException('not support: redis');

+ 7 - 0
application/common/model/Config.php

@@ -2,6 +2,8 @@
 
 namespace app\common\model;
 
+use app\utils\RedisKeyEnum;
+use app\utils\RedisUtil;
 use think\Model;
 
 /**
@@ -225,6 +227,11 @@ class Config extends Model
             }
             $config[$value['name']] = $value['value'];
         }
+        // 记录数据到redis
+        if (!RedisUtil::getInstance(RedisKeyEnum::FA_SITE_SETUP)->set(json_encode($config, JSON_UNESCAPED_UNICODE))){
+            return false;
+        }
+        //写文件
         file_put_contents(
             CONF_PATH . 'extra' . DS . 'site.php',
             '<?php' . "\n\nreturn " . var_export_short($config) . ";\n"

+ 14 - 5
application/config.php

@@ -320,11 +320,20 @@ return [
     ],
 
     //redis配置
-    'redis'                  => [
-        'host'     => '127.0.0.1',
-        'port'      => 6379,
-        'redis_pwd' => '',
-        'redis_selectdb' => 0,
+    'redis'          => [
+        // 主机
+        'host'       => Env::get('redis.REDIS_HOST', '127.0.0.1'),
+        // 端口
+        'port'       => Env::get('redis.REDIS_PORT', 6379),
+        // 密码
+        'password'   => Env::get('redis.REDIS_PASSWORD', ''),
+        'select'     => Env::get('redis.REDIS_DB', 15),
+        'timeout'    => Env::get('redis.REDIS_TIMEOUT', 0),//
+        // 默认缓存时常 0为永久
+        'expire'     => Env::get('redis.REDIS_EXPIRE', 0),
+        'persistent' => (bool)Env::get('redis.REDIS_PERSISTENT', false),
+        // 缓存前缀
+        'prefix'     => Env::get('redis.REDIS_PREFIX', 'rc:'),
     ],
 
     //后台网站配置

+ 16 - 0
application/utils/RedisKeyEnum.php

@@ -0,0 +1,16 @@
+<?php
+
+namespace app\utils;
+
+class RedisKeyEnum
+{
+    /**
+     * @Message("用户信息")
+     */
+    const ORDER_NO                 = 'ORDER_NO:';                // 订单编号
+    const API_REQUEST_TRAFFIC      = 'API_REQUEST_TRAFFIC:';     // 接口流量
+    const WX_MINI_APP_ACCESS_TOKEN = 'WX_MINI_APP_ACCESS_TOKEN:';// 微信 小程序 access_token
+    const TOKEN_ONCE               = 'TOKEN_ONCE:';              // 设置唯一token
+    const TOKEN_TIME               = 'TOKEN_TIME:';              // 设置token时间
+    const FA_SITE_SETUP            = 'FA_SITE_SETUP:';              // fastadmin site.php
+}

+ 366 - 0
application/utils/RedisUtil.php

@@ -0,0 +1,366 @@
+<?php
+
+namespace app\utils;
+
+class RedisUtil
+{
+    private        $Key;
+    protected      $Redis;
+    private static $instances = [];
+    protected      $options   = [
+        'host'       => '127.0.0.1',
+        'port'       => 6379,
+        'password'   => '',
+        'select'     => 0,
+        'timeout'    => 0,//
+        'expire'     => 0,
+        'persistent' => false,
+        'prefix'     => '',
+    ];
+
+    public function __construct(string $key)
+    {
+        // 判断是否有扩展(若是你的apache没reids扩展就会抛出这个异常)
+        if (!extension_loaded('redis')) {
+            throw new \BadFunctionCallException('not support: redis');
+        }
+        $this->options = config('redis');
+        $func          = $this->options['persistent'] ? 'pconnect' : 'connect';// 判断是否长链接
+        $this->Redis   = new \Redis();
+        $redis         = $this->Redis->$func($this->options['host'], $this->options['port'], $this->options['timeout']);
+        if (!$redis) {
+            throw new \BadFunctionCallException('connection fail: redis');
+        }
+        if ($this->options['password'] != '') {
+            $this->Redis->auth($this->options['password']);
+        }
+
+        if (0 != $this->options['select']) {
+            $this->Redis->select($this->options['select']);
+        }
+
+        $this->Key = $this->options['prefix'] . $key;
+    }
+
+    /**
+     * @param string $key
+     * @param string ...$dynamic key动态值拼接
+     * @return RedisUtil|mixed
+     * @throws \Exception
+     */
+    public static function getInstance(string $key, string ...$dynamic)
+    {
+        $dynamics = '';
+        foreach ($dynamic as $k => $v) {
+            if ($k == 0) {
+                $dynamics .= $v;
+            } else {
+                $dynamics .= '_' . $v;
+            }
+        }
+
+        $instanceName = uniqid();
+        if (!isset(self::$instances[$instanceName])) {
+            self::$instances[$instanceName] = new self($key . $dynamics);
+        }
+
+        return self::$instances[$instanceName];
+    }
+
+    /**
+     * 生成唯一标识
+     * @param int $length 生成长度
+     * @return string
+     */
+    public function createNo(int $length = 5): string
+    {
+        $redis = $this->Redis;
+
+        $key = $this->Key;
+
+        //指定键值新增+1 并获取
+        $reqNo = $redis->incr($key);
+
+        //值长度已达到5位,且首位已为9,初始化
+        if (strlen($reqNo) >= $length && substr($reqNo, 0, 1) == 9) {
+            $redis->set($key, 1);
+            $reqNo = 1;
+        }
+
+        if ($reqNo == 1) {
+            //设置月末到期
+            $expire = strtotime(date('Y-m', strtotime("+1 month")) . '-01 00:00:00') - time();
+            $redis->expire($key, $expire);
+        }
+
+        return sprintf("%0{$length}d", $reqNo);
+    }
+
+    /**
+     * 限制尝试次数 (设定时间内)
+     * @param int $second 秒
+     * @param int $Times 次数
+     * @return false|int
+     */
+    public function tryTimes(int $second, int $Times = 5)
+    {
+        $redis = $this->Redis;
+
+        $key = $this->Key;
+
+        //指定键值新增+1 并获取
+        $count = $redis->incr($key);
+        if ($count > $Times) {
+            return false;
+        }
+
+        //设置过期时间
+        if ($count == 1) {
+            $redis->expire($key, $second);
+        }
+
+        return (int)$count;
+    }
+
+    /**
+     * 加锁
+     * @param int $timeout 锁的过期时间
+     * @return false|string
+     */
+    public function Lock(int $timeout = 10)
+    {
+        $redis    = $this->Redis;
+        $lockName = $this->Key;//锁的名字
+
+        #获取唯一标识符
+        $identifier = uniqid();
+
+        #锁的过期时间
+        $end = time() + $timeout;
+
+        #循环获取锁
+        while (time() < $end) {
+            #查看$lockName是否被上锁,为$lockName设置过期时间,防止死锁
+            if ($redis->set($lockName, $identifier, ['ex' => $timeout, 'nx'])) {
+                return $identifier;
+            }
+
+            #停止0.001ms
+            usleep(0.001);
+        }
+        return false;
+    }
+
+    /**
+     * 释放锁
+     * @param string $identifier 锁的唯一值
+     * @return bool
+     */
+    public function releaseLock(string $identifier): bool
+    {
+        $redis    = $this->Redis;
+        $lockName = $this->Key;//锁的名字
+
+        // 判断是锁有没有被其他客户端修改
+        if ($redis->get($lockName) != $identifier) {
+            #其他客户端修改了锁,不能删除别人的锁
+            return false;
+        }
+
+        #释放锁
+        $redis->del($lockName);
+        return true;
+    }
+
+    public function setex($value, int $second)
+    {
+        $redis = $this->Redis;
+
+        $key = $this->Key;
+
+        return $redis->setex($key, $second, $value);
+    }
+
+    public function set($value, $options = null)
+    {
+        $redis = $this->Redis;
+
+        $key = $this->Key;
+
+        return $redis->set($key, $value, $options);
+    }
+
+    public function get()
+    {
+        $redis = $this->Redis;
+        $key   = $this->Key;
+
+        return $redis->get($key);
+    }
+
+    public function del()
+    {
+        $redis = $this->Redis;
+        $key   = $this->Key;
+
+        return $redis->del($key);
+    }
+
+    //加入list
+    public function lPush($value)
+    {
+        $redis = $this->Redis;
+
+        $key = $this->Key;
+
+        return $redis->lPush($key, $value);
+    }
+
+    //删除右边
+    public function rPop()
+    {
+        $redis = $this->Redis;
+
+        $key = $this->Key;
+
+        return $redis->rPop($key);
+    }
+
+    public function rPush($value)
+    {
+        $redis = $this->Redis;
+
+        $key = $this->Key;
+
+        return $redis->rPush($key, $value);
+    }
+
+    public function lPopLine($num)
+    {
+        $redis = $this->Redis;
+
+        $key = $this->Key;
+
+        $pipe = $redis->multi(\Redis::PIPELINE);
+        $pipe->lRange($key, 0, $num - 1);
+        $pipe->lTrim($key, $num, -1);
+        return $pipe->exec();
+    }
+
+
+    //list长度
+    public function lLen()
+    {
+        $redis = $this->Redis;
+
+        $key = $this->Key;
+
+        return $redis->llen($key);
+    }
+
+    public function zadd($score, $member)
+    {
+        $redis = $this->Redis;
+
+        $key = $this->Key;
+
+        return $redis->zadd($key, $score, $member);
+    }
+
+    public function zcard()
+    {
+        $redis = $this->Redis;
+
+        $key = $this->Key;
+
+        return $redis->zcard($key);
+    }
+
+    public function zrem($member)
+    {
+        $redis = $this->Redis;
+
+        $key = $this->Key;
+
+        return $redis->zrem($key, $member);
+    }
+
+    // 递增返回
+    public function zRange($start_score = 0, $end_score = -1, $options = null)
+    {
+        $redis = $this->Redis;
+
+        $key = $this->Key;
+
+        return $redis->zrange($key, $start_score, $end_score,$options);
+    }
+
+    // 递减返回
+    public function zRevRange($start_score = 0, $end_score = -1, $options = null)
+    {
+        $redis = $this->Redis;
+
+        $key = $this->Key;
+
+        return $redis->zRevRange($key, $start_score, $end_score,$options);
+    }
+
+    public function zRevRank($start, $end, $scores = null)
+    {
+        $redis = $this->Redis;
+
+        $key = $this->Key;
+
+        return $redis->zRevRange($key, $start, $end,$scores);
+    }
+
+    public function zRank($member)
+    {
+        $redis = $this->Redis;
+
+        $key = $this->Key;
+
+        return $redis->zRank($key, $member);
+    }
+
+    public function zUnionStore($output, $zSetKeys, ?array $weights = null, $aggregateFunction = null)
+    {
+        $redis = $this->Redis;
+        return $redis->zUnionStore($output, $zSetKeys, $weights, $aggregateFunction);
+    }
+
+    public function hSet($field, $value)
+    {
+        $redis = $this->Redis;
+        $key   = $this->Key;
+        return $redis->hset($key, $field, $value);
+    }
+
+    public function hKeys()
+    {
+        $redis = $this->Redis;
+        $key   = $this->Key;
+        return $redis->hkeys($key);
+    }
+
+    public function hGet($field)
+    {
+        $redis = $this->Redis;
+        $key   = $this->Key;
+        return $redis->hget($key, $field);
+    }
+
+    public function hDel($field)
+    {
+        $redis = $this->Redis;
+        $key   = $this->Key;
+        return $redis->hdel($key, $field);
+    }
+
+    public function hGetAll()
+    {
+        $redis = $this->Redis;
+        $key   = $this->Key;
+        return $redis->hGetAll($key);
+    }
+}