个人总结,有问题请指出
假设:有数条从SQL检索出的结果,需要以时间为序,存入sorted set
import redis
import pickle # 序列化库
import datetime
sql_rst = [
{'sn': 'A', 'price': 2, 'dt': datetime.datetime(2020,4,24,8)},
{'sn': 'B', 'price': 3, 'dt': datetime.datetime(2020,4,24,9)},
{'sn': 'C', 'price': 4, 'dt': datetime.datetime(2020,4,24,10)},
]
r = redis.Redis('localhost', 6379)
params_dict = {}
for d in sql_rst:
params_dict.setdefault(pickle.dumps(d), d.get('dt').timestamp())
r.zadd(name='tst', mapping=params_dict)
关键在于mapping参数需要是一个{member1: score1, memeber2: score2, …}的字典
import redis
import pickle # 序列化库
import datetime
sql_rst = [
{'sn': 'A', 'price': 2, 'dt': datetime.datetime(2020,4,24,8)},
{'sn': 'B', 'price': 3, 'dt': datetime.datetime(2020,4,24,9)},
{'sn': 'C', 'price': 4, 'dt': datetime.datetime(2020,4,24,10)},
]
r = redis.Redis('localhost', 6379)
params_list = []
for d in sql_rst:
params_list.append(d.get('dt').timestamp())
params_list.append(pickle.dumps(d))
r.execute_command('ZADD', 'tst', *params_list)
params_list是一个偶数长度的列表,偶数下标为score,奇数下标为member。(其实它就是模拟redis命令行执行zadd语句)
import redis
import pickle # 序列化库
import datetime
sql_rst = [
{'sn': 'A', 'price': 2, 'dt': datetime.datetime(2020,4,24,8)},
{'sn': 'B', 'price': 3, 'dt': datetime.datetime(2020,4,24,9)},
{'sn': 'C', 'price': 4, 'dt': datetime.datetime(2020,4,24,10)},
]
r = redis.Redis('localhost', 6379)
pipe = r.pipeline()
for d in sql_rst:
pipe.zadd(name='tst', mapping={pickle.dumps(d): d.get('dt').timestamp()})
pipe.execute()