conn=redis.StrictRedis(connection_pool=config_manager_list[str(app_id)].redis_pool,socket_timeout=5,socket_connect_timeout=5, retry_on_timeout=5) 連接數(shù)據(jù)庫
r = conn.pipeline() 獲取管道
使用pipelining 發(fā)送命令時(shí),redis server必須部分請(qǐng)求放到隊(duì)列中(使用內(nèi)存)執(zhí)行完畢后一次性發(fā)送結(jié)果
pipeline期間將“獨(dú)占”鏈接,此期間將不能進(jìn)行非“管道”類型的其他操作,直到pipeline關(guān)閉;如果你的pipeline的指令集很龐大,為了不干擾鏈接中的其他操作,你可以為pipeline操作新建Client鏈接,讓pipeline和其他正常操作分離在2個(gè)client中
- r.hset(name, "JWT", new_JWT) 更新key為name的哈希記錄里叫做 JWT字段的值為new_JWT
- r.rename(old_name, new_name) 將old_name對(duì)應(yīng)的哈希記錄的key更新為new_name
- r.execute() 執(zhí)行命令
pipeline和 execute合起來相當(dāng)于使用事務(wù)來操作,可以一次性執(zhí)行多個(gè)命令
#!/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)
# 測(cè)試結(jié)果
without_pipeline has token 4.64443057954
with_pipeline has token 0.098383873589
python 調(diào)用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

無匹配模式遍歷

有匹配模式遍歷