devoralive/traffic-limit-bundle

一个基于Redis的Symfony 2最大请求限制流量处理器

dev-master / 1.0.x-dev 2016-10-28 09:09 UTC

This package is auto-updated.

Last update: 2024-08-29 04:08:50 UTC


README

根据定义的键限制应用程序的请求数量

它使用SNC\RedisBundle连接到Redis。您可以创建所需数量的流量限制服务

安装

步骤 1: 下载Bundle

打开命令行,进入您的项目目录,并执行以下命令以下载此Bundle的最新稳定版本

$ composer require devoralive/traffic-limit-bundle "dev-master"

如果您尚未安装,此命令还将安装snc\RedisBundle

此命令要求您全局安装Composer,如Composer文档的安装章节中所述。

步骤 2: 启用Bundle

然后,通过将其添加到项目app/AppKernel.php文件中注册的Bundle列表中来启用Bundle

<?php
// app/AppKernel.php

// ...
class AppKernel extends Kernel
{
    public function registerBundles()
    {
        $bundles = array(
            // ...
            new Snc\RedisBundle\SncRedisBundle(), //Mandatory of using this bundle
            new Devoralive\TrafficLimit\TrafficLimitBundle(), //Include the bundle
        );

        // ...
    }

    // ...
}

步骤 3: 配置Bundle

要使用此Bundle,您需要在app/config目录中的config.yml文件中添加配置

我们假设您已从sncRedisBundle中包含至少一个到Redis的连接。如果您需要更多信息,请查看SncRedisBundle配置

snc_redis:
    clients:
        default:
            type: phpredis
            alias: default
            dsn: redis://:6379

        traffic_limit:
            type: phpredis
            alias: default
            dsn: redis://:6379
            
traffic_limit:
    low_limit:
        enabled: true
        snc_client: traffic_limit
        amount: 600
        ttl: 60
    high_limit:
        enabled: true
        snc_client: default
        amount: 6000
        ttl: 60

如您所见,您可以定义尽可能多的流量限制服务。您可以有无限配置。所有这些都在容器中可用

<?php

use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\TooManyRequestsHttpException;

namespace AppBundle\Controller;

/**
 * Class ApiController
 *
 * @package AppBundle\Controller
 */
class ApiController
{
    /**
     * Example on how to limit requests by IP
     *     
     * @param string $ip
     *
     * @return string 
     *
     * @throws TooManyRequestsHttpException $e
     */
    public function getLocationAction(Request $request, $ip)
    {
        try {
            $this->get('traffic_limit.low_limit')->processRequest(
                $request->getClientIp()
            );
                    
            //do some stuff...
            
            return new JsonResponse('');
        } catch (TooManyRequestsHttpException $e) {
            //handle exception or throw it
        }
    }
}

您可以定义键,因此您可以根据IP、userId或任何您能识别为变量的内容来限制请求。

如果达到请求限制,则"processRequest"方法将返回异常。