python redis 關于pipline(),lua腳本和scan命令的初步使用

  • conn=redis.StrictRedis(connection_pool=config_manager_list[str(app_id)].redis_pool,socket_timeout=5,socket_connect_timeout=5, retry_on_timeout=5) 連接數據庫

  • r = conn.pipeline() 獲取管道

使用pipelining 發送命令時,redis server必須部分請求放到隊列中(使用內存)執行完畢后一次性發送結果
pipeline期間將“獨占”鏈接,此期間將不能進行非“管道”類型的其他操作,直到pipeline關閉;如果你的pipeline的指令集很龐大,為了不干擾鏈接中的其他操作,你可以為pipeline操作新建Client鏈接,讓pipeline和其他正常操作分離在2個client中

  • r.hset(name, "JWT", new_JWT) 更新key為name的哈希記錄里叫做 JWT字段的值為new_JWT
  • r.rename(old_name, new_name) 將old_name對應的哈希記錄的key更新為new_name
  • r.execute() 執行命令

pipeline和 execute合起來相當于使用事務來操作,可以一次性執行多個命令

#!/usr/bin/python2
import redis
import time
def without_pipeline():
    r=redis.Redis()
    for i in range(10000):
        r.ping()
    return
def with_pipeline():
    r=redis.Redis()
    pipeline=r.pipeline()
    for i in range(10000):
        pipeline.ping()
    pipeline.execute()
    return
def bench(desc):
    start=time.clock()
    desc()
    stop=time.clock()
    diff=stop-start
    print "%s has token %s" % (desc.func_name,str(diff))
if __name__=='__main__':
    bench(without_pipeline)
    bench(with_pipeline)

# 測試結果
without_pipeline has token 4.64443057954
with_pipeline has token 0.098383873589

python 調用lua腳本操作redis

  • s = self.conn.register_script(GET_COUNT_SCRIPT)
  • res = s(args=patterns)
GET_ALL_RID_SCRIPT = """
local cursor = "0"
local matchKey = ARGV[1]
local matchKeyPrefix = string.sub(matchKey,1,-2)
local ridList = {};
local done = false;
repeat
    local result = redis.call("SCAN", cursor, "match", matchKey)
    cursor = result[1];
    for i, key in ipairs(result[2]) do
        local rid = string.gsub(key,matchKeyPrefix,"");
        table.insert(ridList,rid);
    end
    if cursor == "0" then
        done = true;
    end
until done

return ridList;
"""

s = self.conn.register_script(GET_ALL_RID_SCRIPT)
res = s(args=[match])

參考鏈接

scan 命令

通過key '*' 查找所有key
無匹配模式遍歷
有匹配模式遍歷
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • 1、redis連接 redis提供兩個類Redis和StrictRedis用于實現Redis的命令,StrictR...
    君惜丶閱讀 231,938評論 15 117
  • Spring Cloud為開發人員提供了快速構建分布式系統中一些常見模式的工具(例如配置管理,服務發現,斷路器,智...
    卡卡羅2017閱讀 134,991評論 19 139
  • 1.1 資料 ,最好的入門小冊子,可以先于一切文檔之前看,免費。 作者Antirez的博客,Antirez維護的R...
    JefferyLcm閱讀 17,120評論 1 51
  • 安全性 設置客戶端連接后進行任何其他指令前需要使用的密碼。 警告:因為redis 速度相當快,所以在一臺比較好的服...
    OzanShareing閱讀 1,832評論 1 7
  • 笙歌一曲醉寒淚, 捂泣揮影笑離殤; 夢與佳人共一舞, 卻是天涯各一方。
    霧夜憂魂閱讀 549評論 3 20