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

redis> SET mykey "10"

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 控制调用频率的更多相关文章

  1. 控制ASP.NET Web API 调用频率与限流

    ASP.NET MVC 实现 https://github.com/stefanprodan/MvcThrottle ASP.NET WEBAPI 实现 https://github.com/stef ...

  2. finecms如何控制调用子栏目的数量

    finecms如何控制调用子栏目的数量?比如只要调用栏目id为23下的3个子栏目要怎么写?我们把num=3放后面不能实现,放在return前面就可以了,原来是顺序的问题,return只能放最后 {li ...

  3. Redis Java调用

    Redis Java调用 package com.stono.redis; import redis.clients.jedis.Jedis; public class RedisJava { pub ...

  4. 控制ASP.NET Web API 调用频率

    很多的api,例如GitHub’s API 都有流量控制的做法.使用速率限制,以防止在很短的时间量客户端向你的api发出太多的请求.例如,我们可以限制匿名API客户端每小时最多60个请求,而我们可以让 ...

  5. Redis实战(十五)Redis实现接口调用频率限制

    序言 登录次数 资料

  6. Redis实现访问控制频率

    为什么限制访问频率 做服务接口时通常需要用到请求频率限制 Rate limiting,例如限制一个用户1分钟内最多可以范围100次 主要用来保证服务性能和保护数据安全 因为如果不进行限制,服务调用者可 ...

  7. .Net 如何模拟会话级别的信号量,对http接口调用频率进行限制(有demo)

    现在,因为种种因素,你必须对一个请求或者方法进行频率上的访问限制. 比如, 你对外提供了一个API接口,注册用户每秒钟最多可以调用100次,非注册用户每秒钟最多可以调用10次. 比如, 有一个非常吃服 ...

  8. 主键生成器效率提升方案|基于雪花算法和Redis控制进程隔离

    背景 主键生成效率用数据库自增效率也是比较高的,为什么要用主键生成器呢?是因为需要insert主表和明细表时,明细表有个字段是主表的主键作为关联.所以就需要先生成主键填好主表明细表的信息后再一次过在一 ...

  9. 微信企业号api调用频率

    主动调用的频率限制 当你获取到AccessToken时,你的应用就可以成功调用企业号后台所提供的各种接口以管理或访问企业号后台的资源或给企业号成员发消息. 为了防止企业应用的程序错误而引发企业号服务器 ...

随机推荐

  1. word2vec生成词向量原理

    假设每个词对应一个词向量,假设: 1)两个词的相似度正比于对应词向量的乘积.即:$sim(v_1,v_2)=v_1\cdot v_2$.即点乘原则: 2)多个词$v_1\sim v_n$组成的一个上下 ...

  2. 关于——GCD

      GCD全称是Grand Central Dispatch,可译为“牛逼的中枢调度器”,纯C语言提供了强大的函数. GCD中2个核心概念 任务:执行什么操作. 队列:用来存放任务.(说白点,任务只有 ...

  3. FMDB警告Warning: there is at least one open result set around after performing的问题

    FMDB操作sqlite的时候总是报警告Warning: there is at least one open result set around after performing,后来发现是执行查询 ...

  4. Delphi-LowerCase 函数

    函数名称 LowerCase 所在单元 System.SysUtils 函数原型 function LowerCase(const S: string): string; 函数功能 将字符串中所有的大 ...

  5. APP的测试过程和重点

    APP的测试过程和重点 1.首先是测试资源确认及准备 (1)产品需求文档.产品原型图.接口说明文档以及设计说明文档等应齐全: (2)测试设备及工具的准备:IOS和andriod不同版本的真机,以及相关 ...

  6. js中typeof的用法

    一. 经常会在js里用到数组,比如 多个名字相同的input, 若是动态生成的, 提交时就需要判断其是否是数组. if(document.mylist.length != "undefine ...

  7. Pku1947 Rebuilding Roads

    题意是给一棵树,问最少删掉几条边.使得剩下的子树中有节点个数为m个的 设f[i][j]表示i号点所在的子树中选了j个点至少需要删去f[i][j]条边. code: #include<cstdio ...

  8. noi 3531 判断整除

    3531:判断整除 查看 提交 统计 提问 总时间限制:  1000ms 内存限制:  65536kB 描述 一个给定的正整数序列,在每个数之前都插入+号或-号后计算它们的和.比如序列:1.2.4共有 ...

  9. 怎样在Swift中使用CocoaPods-b

    最近关于CocoaPods有很多的议论.你可能从别的开发者那里听到过,或者在Github的目录中看到过.如果你之前从来没有用过,你可能会问,"CocoaPods到底是什么?" 它不 ...

  10. 状态机的c语言编程

    http://blog.csdn.net/shandongdaya/article/details/7282547 一 有限状态机的实现方式 有限状态机(Finite State Machine或者F ...