重复请求检测示例-php

<?php

checkRepeatReq(['a' => 1, 'b' => 2, 'c' => 3]);

function checkRepeatReq(array $reqParams, string $prefix = '')
{
    $url_path = Request::getPathInfo();
    if (!$url_path || $url_path == 'favicon.ico') {
        $url_path = '/';
    }
    $host = Request::domain();
    if (is_array($reqParams)) {
        $reqParams = http_build_query($reqParams);
    }
    $key = md5($host . $url_path . $reqParams);
    if ($prefix) {
        return $prefix . ':' . $key;
    }

    // 是否为重复请求
    if (duplicateReq($key)) {
        var_dump('重复请求');
        die();
    } else {
        var_dump('正常请求');
        die();
    }
}

function duplicateReq(string $id, int $expire = 0): bool
{
    $repeat = false;

    // 创建Redis实例
    $redis = new Redis();

    // 连接Redis服务器,这里假设Redis服务器运行在本地,默认端口是6379
    $redis->connect('127.0.0.1', 6379);

    // 认证(如果设置了密码)
    // $redis->auth('yourpassword');

    if ($expire <= 0) {
        $expire = rand(100, 600);
    }
    $key = 'sdkrrqq:' . $id;
    try {
        $c = $redis->exists($key);
        if (!empty($c)) {
            $repeat = true;
        } else {
            $redis->setEx($key, $expire, '1');
        }
    } catch (Exception $ex) {

    }
    return $repeat;
}

?>
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容