python導(dǎo)入導(dǎo)出redis數(shù)據(jù)的實現(xiàn)
注:以String類型為例
一.導(dǎo)出redis某個庫的數(shù)據(jù)
import redis
import json
file_path = "why.json"
redis_conn = redis.Redis(host="192.168.1.123", port=6387, password="123zxcv", db=2, decode_responses=True)
data_keys = redis_conn.keys()
all_data = {}
for i in data_keys:
? ? all_data[i] = json.loads(redis_conn.get(i))
file_object = open(file_path, 'w', encoding="utf8")
json.dump(all_data, file_object, ensure_ascii=False)
file_object.close()使用python向Redis批量導(dǎo)入數(shù)據(jù)
使用pipeline進(jìn)行批量導(dǎo)入數(shù)據(jù)。包含先使用rpush插入數(shù)據(jù),然后使用expire改動過期時間
class Redis_Handler(Handler):
?? ?def connect(self):
?? ??? ?#print self.host,self.port,self.table
?? ??? ?self.conn = Connection(self.host,self.port,self.table)?? ?
?? ??? ?
?? ?def execute(self, action_name):
?? ??? ?filename = "/tmp/temp.txt"
?? ??? ?batch_size = 10000
?? ??? ?with open(filename) as file:
?? ??? ??? ?try:
?? ??? ??? ??? ?count = 0
?? ??? ??? ??? ?pipeline_redis = self.conn.client.pipeline()
?? ??? ??? ??? ?for lines in file:
?? ??? ??? ??? ??? ?(key,value) = lines.split(',')
?? ??? ??? ??? ??? ??? ?count = count + 1
?? ??? ??? ??? ??? ??? ?if len(key)>0:
?? ??? ??? ??? ??? ??? ??? ?pipeline_redis.rpush(key,value.strip())
?? ??? ??? ??? ??? ??? ??? ?if not count % batch_size:
?? ??? ??? ??? ??? ??? ??? ??? ?pipeline_redis.execute()
?? ??? ??? ??? ??? ??? ??? ??? ?count = 0
?? ??? ??? ?
?? ?
?? ??? ??? ??? ?#send the last batch
?? ??? ??? ??? ?pipeline_redis.execute()
?? ??? ??? ?except Exception:
?? ??? ??? ??? ?print 'redis add error'二.導(dǎo)入redis某個庫的數(shù)據(jù)
import redis import json file_path = "why.json" redis_conn = redis.Redis(host="192.168.1.123", port=6387, password="123zxcv", db=1, decode_responses=True) file_object = open(file_path, 'r', encoding="utf8") all_data = json.load(file_object) for key in all_data: ? ? redis_conn.set(key, json.dumps(all_data[key], ensure_ascii=False)) file_object.close()
到此這篇關(guān)于python導(dǎo)入導(dǎo)出redis數(shù)據(jù)的實現(xiàn)的文章就介紹到這了,更多相關(guān)python導(dǎo)入導(dǎo)出redis內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python QTimer實現(xiàn)多線程及QSS應(yīng)用過程解析
這篇文章主要介紹了Python QTimer實現(xiàn)多線程及QSS應(yīng)用過程解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-07-07
python爬蟲流程基礎(chǔ)示例零基礎(chǔ)學(xué)習(xí)
這篇文章主要為大家介紹了python爬蟲流程基礎(chǔ)示例零基礎(chǔ)學(xué)習(xí),我們將討論 Python 網(wǎng)絡(luò)編程中的爬蟲基礎(chǔ),作為一個完全的初學(xué)者,你將學(xué)習(xí)到爬蟲的基本概念、常用庫以及如何編寫一個簡單的爬蟲2023-06-06

