PHP code example of bud / rate-limit

1. Go to this page and download the library: Download bud/rate-limit library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

bud / rate-limit example snippets



declare(strict_types=1);

namespace App\Controller;

use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\HttpServer\Annotation\AutoController;
use Bud\RateLimit\Annotation\RateLimitAnnotation;

#[AutoController(prefix: "test")]
class TestController
{
    /**
     * 20秒内仅允许请求一次
     */
    #[RequestMapping(path: "", methods: "get"),RateLimitAnnotation('test', 20, 1)]
    public function index()
    {
        return [
            'key' => 'rate_limit:App\Controller\IndexController:index:test'
        ];
    }

    /**
     * 相同路径参数一分钟仅允许访问一次
     */
    #[RequestMapping(path: "{id}", methods: "get"),RateLimitAnnotation('test:{id}', 60, 1)]
    public function info(int $id)
    {
        return [
            'key' => "rate_limit:App\Controller\IndexController:info:test:$id"
        ];
    }
}

    /**
     * @param string $key 限流键
     * @param int $unit_time 单位时间(秒)默认(60)秒
     * @param int $max_number 最大访问次数 默认60次,即一秒一次
    */
    \Zeno\RateLimit\RateLimit::checkLimit(string $key, int $unit_time = 60, int $max_number = 60)