濮阳杆衣贸易有限公司

主頁 > 知識庫 > 如何利用 Redis 實現(xiàn)接口頻次限制

如何利用 Redis 實現(xiàn)接口頻次限制

熱門標簽:十堰營銷電銷機器人哪家便宜 魔獸2青云地圖標注 日本中國地圖標注 北京400電話辦理收費標準 超呼電話機器人 山東外呼銷售系統(tǒng)招商 貴州電銷卡外呼系統(tǒng) 宿遷便宜外呼系統(tǒng)平臺 鄭州人工智能電銷機器人系統(tǒng)

介紹:

我們可以利用 redis 過期Key來實現(xiàn)接口的頻次限制。可以自定義一些訪問的(速度)限制條件來把那些觸發(fā)限制的請求拒之門外.一般常用來進行對爬蟲的限制.

下面就利用 redis 來實現(xiàn)了一個簡單的案例:

裝飾器實現(xiàn)

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 結構中添加一個數(shù)據(jù)或者改變 hset 數(shù)據(jù)的一個字段是不會清除超時時間的;

官方網(wǎng)站看了一下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結構中添加一個數(shù)據(jù)或者改變hset數(shù)據(jù)的一個字段是不會清除超時時間的;如果想要通過set去覆蓋值那就必須重新設置expire。

到此這篇關于如何利用 Redis 實現(xiàn)接口頻次限制的文章就介紹到這了,更多相關Redis 實現(xiàn)接口頻次限制內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

您可能感興趣的文章:
  • spring boot+ redis 接口訪問頻率限制的實現(xiàn)
  • SpringBoot下token短信驗證登入登出權限操作(token存放redis,ali短信接口)
  • Springboot+redis+Interceptor+自定義annotation實現(xiàn)接口自動冪等
  • C++訪問Redis的mset 二進制數(shù)據(jù)接口封裝方案

標簽:朝陽 大慶 北京 吉安 江蘇 楊凌 臺州 果洛

巨人網(wǎng)絡通訊聲明:本文標題《如何利用 Redis 實現(xiàn)接口頻次限制》,本文關鍵詞  如何,利用,Redis,實現(xiàn),接口,;如發(fā)現(xiàn)本文內容存在版權問題,煩請?zhí)峁┫嚓P信息告之我們,我們將及時溝通與處理。本站內容系統(tǒng)采集于網(wǎng)絡,涉及言論、版權與本站無關。
  • 相關文章
  • 下面列出與本文章《如何利用 Redis 實現(xiàn)接口頻次限制》相關的同類信息!
  • 本頁收集關于如何利用 Redis 實現(xiàn)接口頻次限制的相關信息資訊供網(wǎng)民參考!
  • 推薦文章
    通山县| 呼图壁县| 邹平县| 平阴县| 共和县| 富川| 林芝县| 阿克苏市| 甘孜县| 缙云县| 鄂托克前旗| 博罗县| 岑巩县| 诏安县| 蒲城县| 德化县| 龙南县| 呼伦贝尔市| 寿光市| 论坛| 越西县| 哈密市| 门头沟区| 来安县| 武胜县| 常州市| 潼南县| 临邑县| 新蔡县| 茌平县| 饶河县| 凉山| 赫章县| 平安县| 唐河县| 塔城市| 石棉县| 南昌市| 老河口市| 方城县| 济阳县|