Python实现Redis数据导入与导出的完整指南

宋时安
宋时安
发布时间:2026-10-15| 5人浏览过
原创

本文详解如何使用Python进行Redis数据的导出与导入。导出部分演示通过keys获取所有String类型数据并保存为JSON文件;导入部分介绍利用Pipeline管道技术批量执行rpush命令,并结合expire设置过期时间,同时通过batch_size控制内存占用,确保大批量数据迁移的高效与稳定。

注:本文以String类型为例

一、导出Redis指定数据库的数据

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修改过期时间

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指定数据库的数据

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相关内容,请查阅本站往期文章或继续浏览后续教程,感谢大家的支持!

相关标签:

免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。

Python 相关产品和应用

全部下载
Selenium

Selenium

4.51.0 · Windows

用于浏览器自动化和 Web 测试的 Python 工具。

scikit-learn

scikit-learn

1.9.1 · Windows

常用 Python 机器学习算法与模型评估工具库。

Black

Black

26.10.1 · Windows

强调一致性的 Python 自动代码格式化工具。

Ruff

Ruff

0.17.1 · macOS

由 Rust 编写的高速 Python 代码检查和格式化工具。

pytest

pytest

9.1.1 · Windows

简洁而强大的 Python 自动化测试框架。

FastAPI

FastAPI

0.146.0 · Windows

高性能 Python API 框架,支持类型提示和自动接口文档。

Flask

Flask

3.1.3 · Windows

轻量灵活的 Python Web 应用框架。

Django

Django

6.1.2 · Windows

成熟的 Python Web 框架,适合构建内容站点和业务系统。

Spyder

Spyder

6.1.7 · Windows

面向科学计算与数据分析的 Python 集成开发环境。

SciPy

SciPy

1.18.1 · Windows

面向科学、工程和技术计算的 Python 算法库。