脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - python导入导出redis数据的实现

python导入导出redis数据的实现

2022-10-14 11:16纯洁的小魔鬼 Python

本文主要介绍了python导入导出redis数据的实现,文中通过示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

注:以String类型为例

一.导出redis某个库的数据

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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批量导入数据

使用pipeline进行批量导入数据。包含先使用rpush插入数据,然后使用expire改动过期时间

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
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'

二.导入redis某个库的数据

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
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()

到此这篇关于python导入导出redis数据的实现的文章就介绍到这了,更多相关python导入导出redis内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://blog.csdn.net/xyy1028/article/details/122706544

延伸 · 阅读

精彩推荐