本文的示例代码参考Redis
目录
-
简单限流
Sorted Set
Practice
-
漏斗限流
Redis Cell
Practice
简单限流
Sorted Set
127.0.0.1:6379> zadd books 9.0 "think in java"
(integer) 1
127.0.0.1:6379> zadd books 8.9 "java concurrency"
(integer) 1
127.0.0.1:6379> zadd books 8.6 "java cookbook"
(integer) 1
127.0.0.1:6379> zrange books 0 -1
1) "java cookbook"
2) "java concurrency"
3) "think in java
127.0.0.1:6379> zrevrange books 0 -1
1) "think in java"
2) "java concurrency"
3) "java cookbook"
127.0.0.1:6379> zcard books
(integer) 3
127.0.0.1:6379> zrank books "java concurrency"
(integer) 1
127.0.0.1:6379> zrangebyscore books 0 8.91
1) "java cookbook"
2) "java concurrency"
127.0.0.1:6379> zremrangebyscore books 0 8.91
(integer) 2
127.0.0.1:6379> zcard books
(integer) 1
关于Sorted Set的更多介绍 可以参考Sorted Set
Practice
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import time
import redis
client = redis.StrictRedis()
def is_action_allowed(user_id, action_key, period, max_count):
key = 'rate-limit:%s:%s' % (user_id, action_key)
now_ts = int(time.time() * 1000)
with client.pipeline() as pipe:
pipe.zadd(key, {str(now_ts): now_ts})
pipe.zremrangebyscore(key, 0, now_ts - period * 1000)
pipe.zcard(key)
pipe.expire(key, period + 1)
_, _, current_count, _ = pipe.execute()
return current_count <= max_count
for i in range(10):
print(is_action_allowed("xiaoming", "post", 10, 5))
time.sleep(0.5)
True
True
True
True
True
False
False
False
False
False
Redis Client与Redis Server基于TCP通信 使用pipline可以将多个client command一次发给server即批处理 解决多次网络通信的性能问题 关于pipline更多介绍 可以参考Using pipelining to speedup Redis queries
漏斗限流
Redis Cell
CL.THROTTLE key 5 5 10 1
▲ ▲ ▲ ▲ ▲
| | | | └──── 所需令牌数
| | └──┴─────── 周期内生成令牌数
| └───────────── 初始令牌数
└─────────────────── 键
127.0.0.1:6379> CL.THROTTLE key 5 5 10 1
1) (integer) 0 # 0 means allowed; 1 means denied
2) (integer) 6 # total quota (`X-RateLimit-Limit` header)
3) (integer) 5 # remaining quota (`X-RateLimit-Remaining`)
4) (integer) -1 # if denied, time until user should retry (`Retry-After`)
5) (integer) 2 # time until limit resets to maximum capacity (`X-RateLimit-Reset`)
关于Redis Cell更多介绍 可以参考redis-cell: a Rate Limiting Redis Module
Practice
brew install redis
wget https://github.com/brandur/redis-cell/releases/download/v0.2.4/redis-cell-v0.2.4-x86_64-apple-darwin.tar.gz
tar xf redis-cell-v0.2.4-x86_64-apple-darwin.tar.gz
redis-server --loadmodule ./libredis_cell.dylib
关于Redis Modules更多介绍 可以参考Redis Modules
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import time
import redis
client = redis.StrictRedis()
def is_action_allowed(user_id, action_key, period, max_count):
key = 'funnel-limit:%s:%s' % (user_id, action_key)
ret = client.execute_command(
'CL.THROTTLE key %d %d %d 1' % (max_count, max_count, period))
print(ret)
return ret[0] == 0
for i in range(10):
print(is_action_allowed("xiaoming", "post", 10, 5))
time.sleep(0.5)
[0, 6, 5, -1, 2]
True
[0, 6, 4, -1, 3]
True
[0, 6, 3, -1, 4]
True
[0, 6, 2, -1, 6]
True
[0, 6, 2, -1, 7]
True
[0, 6, 1, -1, 9]
True
[0, 6, 0, -1, 10]
True
[1, 6, 0, 0, 10]
False
[0, 6, 0, -1, 11]
True
[1, 6, 0, 1, 11]
False
关于StrictRedis更多介绍 可以参考redis-py : What's the difference between StrictRedis() and Redis()?
参考
应用 6:断尾求生 —— 简单限流
应用 7:一毛不拔 —— 漏斗限流