Redis的三种限流方法以及代码详解

Redis 提供了几种不同的方法来实现限流,以下是三种常见的限流方法及其代码示例:

  1. 使用 Redis 的 INCR 和 EXPIRE 命令



import redis
 
def is_rate_limited(redis_conn, user_id, max_requests, duration):
    key = f"user:{user_id}:rate_limit"
    requests = redis_conn.incr(key)
    if requests == 1:
        redis_conn.expire(key, duration)
    if requests > max_requests:
        return True
    else:
        return False
 
r = redis.Redis(host='localhost', port=6379, db=0)
user_id = "user123"
max_requests = 10
duration = 60  # 60 seconds
 
if is_rate_limited(r, user_id, max_requests, duration):
    print("User has exceeded the rate limit.")
else:
    print("User is within the rate limit.")
  1. 使用 Redis 的 LUA 脚本



import redis
 
rate_limit_script = """
    local key = KEYS[1]
    local limit = tonumber(ARGV[1])
    local current = redis.call('get', key)
    if current and tonumber(current) > limit then
        return true
    else
        if current then
            redis.call('incr', key)
        else
            redis.call('set', key, 1)
            redis.call('expire', key, ARGV[2])
        end
        return false
    end
"""
 
def is_rate_limited(redis_conn, user_id, max_requests, duration):
    key = f"user:{user_id}:rate_limit"
    script = redis_conn.register_script(rate_limit_script)
    return script(keys=[key], args=[max_requests, duration])
 
r = redis.Redis(host='localhost', port=6379, db=0)
user_id = "user123"
max_requests = 10
duration = 60  # 60 seconds
 
if is_rate_limited(r, user_id, max_requests, duration):
    print("User has exceeded the rate limit.")
else:
    print("User is within the rate limit.")
  1. 使用 Redis 的 Token Bucket 算法



import redis
import time
 
def token_bucket(redis_conn, user_id, rate, tokens, duration):
    key = f"user:{user_id}:rate_limit"
    now = time.time()
    timestamp = redis_conn.get(key)
    if timestamp:
        timestamp = float(timestamp)
        if now < timestamp:
            return False
        if now > timestamp + duration:
            redis_conn.set(key, now, ex=duration)
            redis_conn.set(f"{key}:tokens", max(tokens - (now - timestamp) * rate, 0))
    else:
        redis_conn.set(key, now, ex=duration)
        redis_conn.set(f"{key}:tokens", tokens)
    if redis_conn.exists(f"{key}:tokens"):
        current_tokens = redis_conn.get(f"{key}:tokens")
        if current_tokens and int(current_tokens) > 0:
            redis_conn.decr(f"{ke
最后修改于:2024年09月02日 10:17

评论已关闭

推荐阅读

Vue中使用mind-map实现在线思维导图
2024年08月04日
VUE
Web前端最全Vue实现免密登录跳转的方式_vue怎么样不登录返回首页,最强技术实现
2024年08月04日
VUE
vue3 项目搭建教程(基于create-vue,vite,Vite + Vue)
2024年08月04日
VUE
Vue-颜色选择器实现方案——>Vue-Color( 实战*1+ Demo*7)
2024年08月04日
VUE
Vue项目卡顿慢加载?这些优化技巧告诉你!_vue数据多渲染卡顿
2024年08月04日
VUE
vue中的keep-alive详解与应用场景
2024年08月04日
VUE
Vue、React实现excel导出功能(三种实现方式保姆级讲解)
2024年08月04日
vue-office/docx插件实现docx文件预览
2024年08月04日
VUE
java调用js文件的两种方法(支持V8引擎)
2024年08月04日
JavaScript:解决计算精度问题/mathjs/bignumber.js/big.js/decimal.js
2024年08月04日
两周从爬虫小白变大神 _yjs_js_security_passport
2024年08月04日
JS笔记(对象、函数、数组)
2024年08月04日
Markdown.js:强大的纯JavaScript Markdown解析器
2024年08月04日
Vue项目:js模拟点击a标签下载文件并重命名,URL文件地址下载方法、请求接口下载文件方法总结。
2024年08月04日
vue 父组件怎么获取子组件里面的data数据
2024年08月04日
VUE
个人开发实现AI套壳网站快速搭建(Vue+elementUI+SpringBoot)
2024年08月04日
el-table 表格封装并改造实现单元格可编辑
2024年08月04日
none
nodejs环境下创建vue项目、SSH密钥登陆!!!
2024年08月04日
vue+quill+element-ui实现视频、图片上传及缩放保姆级教程,轻松使用富文本
2024年08月04日
【three.js】22. Imported Models导入模型
2024年08月04日