接口访问频率限制 php,php API访问通过redis控制频率限制

解决方法:直接上代码

需要提前安装扩展

composer require predis/predis

/** * API访问频率限制简单处理 */

require_once 'vendor/autoload.php';

$redis = new PredisClient ( 'tcp://127.0.0.1:6379' );

// 测试key

$clientKey = "api_count:client_id:" . date ( 'YmdHi' ); //

限制时间为1分钟 $seconds = '60';

// 限制次数为20次

$count = 20;

//不存在key

if (! $redis--->get ( $clientKey )) {

$redis->set ( $clientKey, 0 );

$redis->expire ( $clientKey, $seconds );

}

//访问频率监控

$accessCount = $redis->incr ( $clientKey );

if ($accessCount > $count) {

echo "[WARING]:访问超过限制次数";

} else {

$remainingTime = $redis->ttl ( $clientKey );

echo "{$clientKey} 剩余时间:{$remainingTime}s 访问次数为:{$accessCount}";

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在 Django1.8 中,我们可以通过使用 Redis 来实现接口访问频率限制。具体实现步骤如下: 1. 首先,在 settings.py 文件中配置 Redis: ``` CACHES = { 'default': { 'BACKEND': 'django_redis.cache.RedisCache', 'LOCATION': 'redis://127.0.0.1:6379/1', 'OPTIONS': { 'CLIENT_CLASS': 'django_redis.client.DefaultClient', } } } ``` 2. 在 views.py 文件中定义装饰器: ``` from django.core.cache import cache from django.http import HttpResponseBadRequest def rate_limit(key_prefix, rate, block=False): def decorator(view_func): def wrapper(request, *args, **kwargs): # 计算 key key = '{0}:{1}'.format(key_prefix, request.META['REMOTE_ADDR']) # 获取当前时间 now = int(time.time()) # 获取 key 对应的数据 data = cache.get(key) if not data: # 如果 key 对应的数据不存在,说明还没有访问过,直接存储当前时间 cache.set(key, '{0}:1'.format(now), rate) else: # 否则,将数据分解成时间戳和计数器 timestamp, count = data.split(':') # 如果当前时间戳减去存储的时间戳大于限制时间,则重置计数器和时间戳 if now - int(timestamp) > rate: cache.set(key, '{0}:1'.format(now), rate) else: # 否则,将计数器加1 count = int(count) + 1 cache.set(key, '{0}:{1}'.format(timestamp, count), rate) # 如果计数器大于限制次数,则返回错误信息 if count > rate: if block: return HttpResponseBadRequest('Rate limit exceed.') else: return HttpResponseBadRequest('Rate limit exceed. Retry after {0} seconds.'.format(int(timestamp) + rate - now)) return view_func(request, *args, **kwargs) return wrapper return decorator ``` 3. 在需要进行频率限制的视图函数上使用装饰器: ``` @rate_limit('api', 10, block=True) def my_view(request): # 处理请求 pass ``` 其中,`'api'` 是 key 的前缀,`10` 是限制时间(秒),`block=True` 表示超过限制次数时阻塞请求,否则返回错误信息。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值