如何利用 Redis 實現(xiàn)接口頻次限制
介紹:
我們可以利用 redis 過期Key來實現(xiàn)接口的頻次限制。可以自定義一些訪問的(速度)限制條件來把那些觸發(fā)限制的請求拒之門外.一般常用來進(jìn)行對爬蟲的限制.
下面就利用 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過期的時候需要注意,在設(shè)置了過期時間后,再次改變 Key 的 Value 值時,之前設(shè)置的過期時間會失效。
解決辦法:
1)在修改 Value 值的時候,查一下過期時間還有多少 ttl 在修改值的時候把過期時間重新賦值回去(本文用的就是此方法)
2)redis 中設(shè)置了過期時間,如果 list 結(jié)構(gòu)中添加一個數(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對應(yīng)存儲的值替換成新的,命令也會清除掉超時時間;如果list結(jié)構(gòu)中添加一個數(shù)據(jù)或者改變hset數(shù)據(jù)的一個字段是不會清除超時時間的;如果想要通過set去覆蓋值那就必須重新設(shè)置expire。
到此這篇關(guān)于如何利用 Redis 實現(xiàn)接口頻次限制的文章就介紹到這了,更多相關(guān)Redis 實現(xiàn)接口頻次限制內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Redis集群增加節(jié)點(diǎn)與刪除節(jié)點(diǎn)的方法詳解
這篇文章主要給大家介紹了關(guān)于Redis集群增加節(jié)點(diǎn)與刪除節(jié)點(diǎn)的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家學(xué)習(xí)或者使用Redis具有一定的參考學(xué)習(xí)價值,需要的朋友們下面來一起學(xué)習(xí)學(xué)習(xí)吧2019-09-09Redis官方ORM框架比RedisTemplate更優(yōu)雅
這篇文章主要為大家介紹了Redis官方ORM框架比RedisTemplate更優(yōu)雅的使用詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-07-07為什么RedisCluster設(shè)計成16384個槽
本文主要介紹了為什么RedisCluster設(shè)計成16384個槽,文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-09-09