python mysql数据批量导入 redis
作者:互联网
python mysql数据批量导入 redis
作为单线程数据库,redis在批量执行一系列命令时,如果每次都单独执行,就需要多次等待服务器进行响应,由于网络延迟通常会导致命令运行效率低下,而pipline能够做到一次性提交大量请求给redisserver,执行完成后再获取相应结果,只需要进行一次请求,命令越多,pipline对于效率的提升就越为明显,因此是一种高效数据导入的方式。mysql数据导入redis就是pipline的一个应用场景。
以下是通过python进行mysql数据导入redis的例子:
from rediscluster import RedisCluster
import pymysql
import pickle
startup_nodes = [{"host":'10.132.221.120',"port":'6379'},{"host":'10.132.2
21.120',"port":'6379'},\
{"host":'10.132.221.121',"port":'6379'},{"host":'10.132.221.12
1',"port":'6380'},\
{"host":'10.132.221.123',"port":'6379'},{"host":'10.132.221.12
3',"port":'6380'}]
def createConnect():
conn = pymysql.connect(
host='****',
user='****', password='****',
database='****',
port=3306,
charset='utf8'
)
return conn
sql = '''select * from telecom'''
cursor = createConnect().cursor()
cursor.execute(sql)
res = cursor.fetchall()
rc = RedisCluster(startup_nodes=startup_nodes)
pipline = rc.pipeline()
cnt = 0
for one in res:
key = '****' #自己根据mysql的数据结构编造
value = '****'
pipline.set(key,value)
print('insert key={} value={}'.format(key,value))
cnt+=1
if cnt%10000==0:
cnt%=10000 #每积累一万条指令对redisserver进行一次请求
pipline.execute()
pipline.execute()
标签:python,10.132,redis,host,mysql,port,pipline 来源: https://www.cnblogs.com/Do-n/p/13427598.html