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

2023-11-14  本文已影响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();
  }

}
上一篇下一篇

猜你喜欢

热点阅读