第一次写博客,如题,直接上代码,欢迎指正!
#coding:utf8
import redis
import json
'''
用于备份zset,zset分两种:score值唯一的zset、score值不唯一的zset
使用时注意:不要在备份的同时对old_key执行添加和删除操作
'''
redis1 = redis.StrictRedis.from_url("redis地址")
old_key = 'old_zset_name'
new_key = 'new_zset_name'
def zset_to_zset():
total = redis1.zcard(old_key)
start = 0
step = 10000
while start < total:
print start
end = start + step - 1
if end > total:
end = total
lis = redis1.zrange(old_key, start, end)
if lis:
dic = dict().fromkeys(lis, 0)
redis1.zadd(new_key, **dic)
start += step
# redis1.delete(old_key)
print 'all finished!'
def export_to_list(score, error_name):
total = redis1.zcount(old_key, score, score) # 查询对应score值的链接数量
start = 0
step = 10000
while start < total:
print start
url_list = redis1.zrangebyscore(old_key, score, score, start, step)
if url_list:
dic = dict().fromkeys(url_list, int(score))
redis1.zadd(new_key, **dic)
start += step
def copy_error():
error_dic = redis1.hget('hash_dic', old_key)
error_dic = json.loads(error_dic)
for score, error_name in error_dic.items():
export_to_list(score, error_name)
error_dic = json.dumps(error_dic)
redis1.hset('hash_dic', new_key, error_dic) # 将new_key存到hash中
# redis1.delete(old_key)
print 'all finished!'
if __name__ == '__main__':
# zset_to_zset() # score值唯一的zset备份
copy_error() # score值不唯一的zset备份
对’hash_dic’的说明:之所以将score值存到一个hash中,是因为不同的score值代表不同的意义。例如:
1 time false
2 geo false
3 startDate false