redis通过hscan导入大hash key
生活随笔
收集整理的這篇文章主要介紹了
redis通过hscan导入大hash key
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
背景
在一次業(yè)務(wù)遷移中,需要將一個redis的db導(dǎo)入另一個線上的redis中,在導(dǎo)入的db中有幾個field上百萬的hash key。直接hgetall來導(dǎo)入有點太粗暴,所以使用了hscan來操作
代碼
#!/bin/env python import rediss1 = redis.Connection(host='192.168.0.1',port=1111) s2 = redis.Connection(host='192.168.0.1',port=2222)c1 = s1.send_command('select','3') c2 = s2.send_command('select','3') print(s1.read_response()) # db里的key數(shù)量不多,我直接使用了keys* 來遍歷。若key很多的話可以用scan方法來遍歷,使用和hscan類似c1 = s1.send_command('keys','*') keys0 = s1.read_response() for i in keys0:c1 = s1.send_command('type',i)result = s1.read_response()if result == "hash":cursor = 0print("start restore",i)while True:s1.send_command('hscan',i,cursor,'count',10)hresult = s1.read_response()cursor = hresult[0]if hresult[0] == '0' :s2.send_command('hmset',i,*hresult[1])print(i,"restorte done!")breakelse:s2.send_command('hmset',i,*hresult[1])代碼只導(dǎo)入hash key。
大致原理就是通過redis的hsacn方法來遍歷hash key。cursor從0開始,每次請求會拿到一個新的cursor,當(dāng)拿到的cursor為0時,代表遍歷完畢。
其中count可以調(diào)整的更大,來使每次導(dǎo)入的數(shù)據(jù)量更大。
導(dǎo)入前建議找個redis測試一下,防止導(dǎo)入的太狠,讓線上的redis負(fù)載升高影響業(yè)務(wù)
總結(jié)
以上是生活随笔為你收集整理的redis通过hscan导入大hash key的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。