• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

如何利用 Redis 实现接口频次限制

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

介绍:

我们可以利用 redis 过期Key来实现接口的频次限制。可以自定义一些访问的(速度)限制条件来把那些触发限制的请求拒之门外.一般常用来进行对爬虫的限制.

下面就利用 redis 来实现了一个简单的案例:

装饰器实现

def frequency_limit(f):
  @wraps(f)
  def frequency_function(*args, **kwargs):
    if 'csrf_token' in session:
      token = session.get("csrf_token")
      url_ = request.url_rule
      redis_key = token + str(url_)
      conn = redis.StrictRedis(host="127.0.0.1", port="6379", password="123456", db=0)
      clicks = conn.get(redis_key)
      if not clicks:
        conn.set(redis_key, 1)
        conn.expire(redis_key, 60)
      else:
        if int(clicks) >= 5:
          return jsonify({'code': 500, 'status': 0, 'message': "您的访问频率太快,请稍后再试", 'data': [],
                  'token': token})
        overdue = 1 if conn.ttl(redis_key) <= 0 else conn.ttl(redis_key)
        conn.set(redis_key, int(clicks) + 1)
        conn.expire(redis_key, overdue)
    return f(*args, **kwargs)

  return frequency_function

注:在使用 redis Key过期的时候需要注意,在设置了过期时间后,再次改变 Key 的 Value 值时,之前设置的过期时间会失效。

解决办法:

1)在修改 Value 值的时候,查一下过期时间还有多少 ttl 在修改值的时候把过期时间重新赋值回去(本文用的就是此方法)

2)redis 中设置了过期时间,如果 list 结构中添加一个数据或者改变 hset 数据的一个字段是不会清除超时时间的;

官方网站看了一下expire的说明:
这样解释的:

The timeout will only be cleared by commands that delete or overwrite the contents of the key, including DEL, SET, GETSET and all the *STORE commands. This means that all the operations that conceptually alter the value stored at the key without replacing it with a new one will leave the timeout untouched. For instance, incrementing the value of a key with INCR, pushing a new value into a list with LPUSH, or altering the field value of a hash with HSET are all operations that will leave the timeout untouched.

如果用DEL, SET, GETSET会将key对应存储的值替换成新的,命令也会清除掉超时时间;如果list结构中添加一个数据或者改变hset数据的一个字段是不会清除超时时间的;如果想要通过set去覆盖值那就必须重新设置expire。

到此这篇关于如何利用 Redis 实现接口频次限制的文章就介绍到这了,更多相关Redis 实现接口频次限制内容请搜索极客世界以前的文章或继续浏览下面的相关文章希望大家以后多多支持极客世界!


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
MySql数据库单表查询与多表连接查询效率对比发布时间:2022-02-08
下一篇:
MySql escape的使用案例详解发布时间:2022-02-08
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap