redis 控制调用频率
redis提供了rate limit demo 如下所示:
INCR key
Available since 1.0.0.
Time complexity: O(1)
Increments the number stored at key
by one. If the key does not exist, it is set to 0
before performing the operation. An error is returned if the key contains a value of the wrong type or contains a string that can not be represented as integer. This operation is limited to 64 bit signed integers.
Note: this is a string operation because Redis does not have a dedicated integer type. The string stored at the key is interpreted as a base-10 64 bit signed integer to execute the operation.
Redis stores integers in their integer representation, so for string values that actually hold an integer, there is no overhead for storing the string representation of the integer.
Return value
Integer reply: the value of key
after the increment
Examples
OK
redis> INCR mykey
(integer) 11
redis> GET mykey
"11"
redis>
Pattern: Counter
The counter pattern is the most obvious thing you can do with Redis atomic increment operations. The idea is simply send an INCR command to Redis every time an operation occurs. For instance in a web application we may want to know how many page views this user did every day of the year.
To do so the web application may simply increment a key every time the user performs a page view, creating the key name concatenating the User ID and a string representing the current date.
This simple pattern can be extended in many ways:
- It is possible to use INCR and EXPIRE together at every page view to have a counter counting only the latest N page views separated by less than the specified amount of seconds.
- A client may use GETSET in order to atomically get the current counter value and reset it to zero.
- Using other atomic increment/decrement commands like DECR or INCRBY it is possible to handle values that may get bigger or smaller depending on the operations performed by the user. Imagine for instance the score of different users in an online game.
Pattern: Rate limiter
The rate limiter pattern is a special counter that is used to limit the rate at which an operation can be performed. The classical materialization of this pattern involves limiting the number of requests that can be performed against a public API.
We provide two implementations of this pattern using INCR, where we assume that the problem to solve is limiting the number of API calls to a maximum of ten requests per second per IP address.
Pattern: Rate limiter 1
The more simple and direct implementation of this pattern is the following:
FUNCTION LIMIT_API_CALL(ip)
ts = CURRENT_UNIX_TIME()
keyname = ip+":"+ts
current = GET(keyname)
IF current != NULL AND current > 10 THEN
ERROR "too many requests per second"
ELSE
MULTI
INCR(keyname,1)
EXPIRE(keyname,10)
EXEC
PERFORM_API_CALL()
END
Basically we have a counter for every IP, for every different second. But this counters are always incremented setting an expire of 10 seconds so that they'll be removed by Redis automatically when the current second is a different one.
Note the used of MULTI and EXEC in order to make sure that we'll both increment and set the expire at every API call.
Pattern: Rate limiter 2
An alternative implementation uses a single counter, but is a bit more complex to get it right without race conditions. We'll examine different variants.
FUNCTION LIMIT_API_CALL(ip):
current = GET(ip)
IF current != NULL AND current > 10 THEN
ERROR "too many requests per second"
ELSE
value = INCR(ip)
IF value == 1 THEN
EXPIRE(value,1)
END
PERFORM_API_CALL()
END
The counter is created in a way that it only will survive one second, starting from the first request performed in the current second. If there are more than 10 requests in the same second the counter will reach a value greater than 10, otherwise it will expire and start again from 0.
In the above code there is a race condition. If for some reason the client performs the INCR command but does not perform the EXPIRE the key will be leaked until we'll see the same IP address again.
This can be fixed easily turning the INCR with optional EXPIRE into a Lua script that is send using the EVAL command (only available since Redis version 2.6).
local current
current = redis.call("incr",KEYS[1])
if tonumber(current) == 1 then
redis.call("expire",KEYS[1],1)
end
There is a different way to fix this issue without using scripting, but using Redis lists instead of counters. The implementation is more complex and uses more advanced features but has the advantage of remembering the IP addresses of the clients currently performing an API call, that may be useful or not depending on the application.
FUNCTION LIMIT_API_CALL(ip)
current = LLEN(ip)
IF current > 10 THEN
ERROR "too many requests per second"
ELSE
IF EXISTS(ip) == FALSE
MULTI
RPUSH(ip,ip)
EXPIRE(ip,1)
EXEC
ELSE
RPUSHX(ip,ip)
END
PERFORM_API_CALL()
END
The RPUSHX command only pushes the element if the key already exists.
Note that we have a race here, but it is not a problem: EXISTS may return false but the key may be created by another client before we create it inside the MULTI / EXEC block. However this race will just miss an API call under rare conditions, so the rate limiting will still work correctly.
redis 控制调用频率的更多相关文章
- 控制ASP.NET Web API 调用频率与限流
ASP.NET MVC 实现 https://github.com/stefanprodan/MvcThrottle ASP.NET WEBAPI 实现 https://github.com/stef ...
- finecms如何控制调用子栏目的数量
finecms如何控制调用子栏目的数量?比如只要调用栏目id为23下的3个子栏目要怎么写?我们把num=3放后面不能实现,放在return前面就可以了,原来是顺序的问题,return只能放最后 {li ...
- Redis Java调用
Redis Java调用 package com.stono.redis; import redis.clients.jedis.Jedis; public class RedisJava { pub ...
- 控制ASP.NET Web API 调用频率
很多的api,例如GitHub’s API 都有流量控制的做法.使用速率限制,以防止在很短的时间量客户端向你的api发出太多的请求.例如,我们可以限制匿名API客户端每小时最多60个请求,而我们可以让 ...
- Redis实战(十五)Redis实现接口调用频率限制
序言 登录次数 资料
- Redis实现访问控制频率
为什么限制访问频率 做服务接口时通常需要用到请求频率限制 Rate limiting,例如限制一个用户1分钟内最多可以范围100次 主要用来保证服务性能和保护数据安全 因为如果不进行限制,服务调用者可 ...
- .Net 如何模拟会话级别的信号量,对http接口调用频率进行限制(有demo)
现在,因为种种因素,你必须对一个请求或者方法进行频率上的访问限制. 比如, 你对外提供了一个API接口,注册用户每秒钟最多可以调用100次,非注册用户每秒钟最多可以调用10次. 比如, 有一个非常吃服 ...
- 主键生成器效率提升方案|基于雪花算法和Redis控制进程隔离
背景 主键生成效率用数据库自增效率也是比较高的,为什么要用主键生成器呢?是因为需要insert主表和明细表时,明细表有个字段是主表的主键作为关联.所以就需要先生成主键填好主表明细表的信息后再一次过在一 ...
- 微信企业号api调用频率
主动调用的频率限制 当你获取到AccessToken时,你的应用就可以成功调用企业号后台所提供的各种接口以管理或访问企业号后台的资源或给企业号成员发消息. 为了防止企业应用的程序错误而引发企业号服务器 ...
随机推荐
- WPF Binding
winform有binding, WPF也有binding,区别在哪呢?这里暂时不提.以前也检查接触WPF binding, 但为什么过段时间就忘记了呢? 可能主要原因自己的知识体系不够完善吧,下面我 ...
- How to check a not defined variable in javascript
javascript里怎么检查一个未定义的变量? in JavaScript null is an object. There's another value for things that don' ...
- jQuery 的ready事件和 JavaScript 的load事件对比
为了理解2个事件的异同,先了解一下HTML文档加载顺序 HTML DOM文档加载步骤 HTML DOM文档加载是按顺序执行的,这与浏览器的渲染方式有关,一般浏览器渲染操作的顺序大致按如下几个步骤 1, ...
- Jquery的外部链接和编写样式
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></ ...
- jQuery MVC 科室异步联动
//科室改变,级联医生 js $("#DepartmentId").change(function () { if (isNaN($(this).val())) { $(" ...
- APP的测试过程和重点
APP的测试过程和重点 1.首先是测试资源确认及准备 (1)产品需求文档.产品原型图.接口说明文档以及设计说明文档等应齐全: (2)测试设备及工具的准备:IOS和andriod不同版本的真机,以及相关 ...
- Python学习笔记:05类
类 Python是面向对象的语言,面向对象最重要的三个优点有: 多态:多态使对象具备不同的行为方式.(可以认为声明了接口,但是实现方式可能多样) 封装:封装是对全局作用域中隐藏多余信息的原则(创建对象 ...
- lua curl动态链接库编译安装(二)
下面再介绍一下lua-curl中的lua-curl-0.2.tar.gz版本的安装方法,可能对于一般的人来说这个很简单,但是对于我们这些菜鸟来说就不一样了: # wget http://files.l ...
- IIS 10 安装URLRewrite组件 方式
1.Open Regedit > HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\InetStp 2.Edit "MajorVersion" an ...
- js渲染引擎 tempo.js
1.引入tempo.js <script src="js/tempo.js" type="text/javascript"></script& ...