美文网首页
thinkphp接口节流限制、redis节流,tp5节流、tp6

thinkphp接口节流限制、redis节流,tp5节流、tp6

作者: 可乐_加冰_ | 来源:发表于2023-11-14 00:51 被阅读0次

    php接口节流限制

    • 自定义节流控制器
    <?php
    declare(strict_types=1);
    
    namespace app\common\controller;
    
    
    use app\exceptions\SystemException;
    use think\Controller;
    
    class AhThrottle extends Controller
    {
        /**
         * 初始化
         * @return bool|void
         * @throws SystemException
         */
        public function _initialize()
        {
            $this->throttleApi();
        }
    
        /**
         * redis简单节流案列
         * @return bool
         * @throws SystemException
         */
        protected function throttleApi()
        {
            $redis = new \Redis();  //实例化这个类
            $redis->connect('127.0.0.1', 6379, 10000);  //指定主机和端口进行连接
    //        $redis->auth('');//密码
            //接口频繁请求防御措施
            //取出本机的客户端ip
            $ip = $_SERVER['REMOTE_ADDR'];
    
            //从缓存中取出ip访问次数
            $ipData = $redis->get($ip);
    
            //取出redis的key的过期时间
            $ipExpireTime = $redis->ttl($ip);
            if ($ipExpireTime <= 0) $ipExpireTime = 60;
            //如果非空判断是否恶意请求
            if (!empty($ipData) && $ipData >= 10) {
                throw new SystemException('请求太多,请稍后再试。' . $ipExpireTime . '秒');
            }
            //存id请求次数
            $i = 1;
            $redis->set($ip, $ipData + $i, $ipExpireTime);
            return true;
        }
    
    }
    
    
    • 接口文件继承
    <?php
    declare(strict_types=1);
    namespace app\apiv1\controller;
    
    use app\common\controller\AhThrottle;//继承节流类
    use app\utils\AppRespUtil;
    use think\Request;
    
    class TestDemo extends AhThrottle
    {
    
      public function index()
      {
           echo phpinfo();
      }
    
    }
    

    相关文章

      网友评论

          本文标题:thinkphp接口节流限制、redis节流,tp5节流、tp6

          本文链接:https://www.haomeiwen.com/subject/vvtjwdtx.html