redis通过hscan导入大hash key
生活随笔
收集整理的這篇文章主要介紹了
redis通过hscan导入大hash key
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
背景
在一次業務遷移中,需要將一個redis的db導入另一個線上的redis中,在導入的db中有幾個field上百萬的hash key。直接hgetall來導入有點太粗暴,所以使用了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數量不多,我直接使用了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])代碼只導入hash key。
大致原理就是通過redis的hsacn方法來遍歷hash key。cursor從0開始,每次請求會拿到一個新的cursor,當拿到的cursor為0時,代表遍歷完畢。
其中count可以調整的更大,來使每次導入的數據量更大。
導入前建議找個redis測試一下,防止導入的太狠,讓線上的redis負載升高影響業務
總結
以上是生活随笔為你收集整理的redis通过hscan导入大hash key的全部內容,希望文章能夠幫你解決所遇到的問題。