1.描述
-用Python
将100W+
数据快速写入Redis
2.思路
(1)引入redis
-
redis
配置看了看源码:host='localhost', port=6379, db=0, password=None,密码没有设置,所以我这里使用第1个db,其它不做修改
r = redis.Redis(db=1)
# transaction表示是否应自动执行所有命令
pipe = r.pipeline(transaction=False)
我是通过追加的方式,写入到redis中。
pipe.append('data',data) # 10W+ 14s
pipe.execute()
(2)多线程
- 引入
threading
import threading
'''省略部分代码'''
if __name__ == '__main__':
thread = threading.Thread(target=coupon_code)
thread.start()
(3)redis
用到的指令
01.切换DB:SELECT 1
02.删除DB为1所有数据:flushdb清空当前数据库中的所有 key
(4)redis
、pipeline
、pipeline + 多线程
对比
redis
r.append('data',data)
pipeline
pipe.append('data',data)
pipe.execute()
pipeline + 多线程
thread = threading.Thread(target=coupon_code)
thread.start()
3.代码
- 完整代码
'''
Function:
再教一招 | 将100W+数据快速写入Redis
Author:
Eleven
微信公众号:
ElevenKeep
编写日期:
2020-07-30
'''
from faker import Faker
import time
import redis
import threading
# 装饰器,计算插入100000条数据需要的时间
def timer(func):
def decor(*args):
start_time = time.time()
func(*args)
end_time = time.time()
d_time = end_time - start_time
print("【pipeline+多线程】100W+插入Redis耗时: ", d_time)
return decor
@timer
def coupon_code():
r = redis.Redis(db=1)
# transaction表示是否应自动执行所有命令
pipe = r.pipeline(transaction=False)
fake = Faker()
for count in range(1000000):
count += 1
data = 'code no.' + str(count) + ' ' + fake.password(length=12, special_chars=None, lower_case=None) + '\n'
# r.append('data',data)
pipe.append('data',data)
pipe.execute()
if __name__ == '__main__':
thread = threading.Thread(target=coupon_code)
thread.start()
4.问题
Could not connect to Redis at 127.0.0.1:6379:由于目标计算机积极拒绝,无法连接。
- 解决办法:
我的redis之前删除了,所以需要重新安装,
需要在https://github.com/tporadowski/redis/releases
下载以msi结尾的文件,安装步骤如下链接:https://www.redis.com.cn/redis-installation