python pipeline写入redis

Posted on 2019-05-14 19:48  jackley  阅读(1535)  评论(0编辑  收藏  举报
1.需求描述

在实际业务中,需要将百万量级的数据导入到redis。而由于写入程序和redis所在机房不同,导致每条记录的写入存在一定时延,被百万次写入放大后,竟然需要用3个小时才能完成全部写入。

2.解决方法

为此,改用pipeline写入redis。pipeline的作用,是能够将多条命令集中起来,一次发送到redis服务端,从而减少网络IO时延。

举个例子,假设每条记录的写入(包括服务器的返回响应)网络时延为20ms,则100万条记录的总时延可达5.5小时。但如果使用pipeline,每次写入1万条记录、分100次写入,则网络时延仅为2秒。可以说,数据量越大,则采用pipeline的提速效果越是明显。

3.示例如下:
from rediscluster import StrictRedisCluster

tag='xxx'
startup_nodes = [
    {"host": "xxx", "port": "6379"},
]
rs = StrictRedisCluster(startup_nodes=startup_nodes, decode_responses=True, skip_full_coverage_check=True)

cnt = 0
# 通过pipeline批量写入redis
p=rs.pipeline()
for line in sys.stdin:
    line_split = line.strip().split('\t')
    rec_key = line_split[0]
    rec_value = line_split[1]
    p.hset(rec_key, tag, rec_value)
    cnt += 1
    if cnt%10000==0:
        p.execute()
p.execute()