redis_db.py 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. #!/usr/bin/env python3
  2. # -*- coding:utf-8 -*-
  3. import redis
  4. from config import load_config
  5. cfgs = load_config()
  6. class Redis(object):
  7. def __init__(self):
  8. self.redis = redis.StrictRedis(host=cfgs['redis']['host'],
  9. port=cfgs['redis']['port'],
  10. password=cfgs['redis']['passwd'],
  11. db=cfgs['redis']['db'],
  12. decode_responses=True)
  13. if __name__ == '__main__':
  14. import random
  15. # 连接到 Redis 服务器
  16. r = Redis().redis
  17. # 有序集合的键名
  18. zset_key = 'hotkeys'
  19. data_list = ['ORDER_FULLORDR_RATE', 'MONTH6_SALE_QTY_YOY', 'MONTH6_SALE_QTY_MOM', 'MONTH6_SALE_QTY']
  20. # 清空已有的有序集合(可选,若需要全新的集合可执行此操作)
  21. r.delete(zset_key)
  22. for item in data_list:
  23. # 生成 80 到 100 之间的随机数,小数点后保留 4 位
  24. score = round(random.uniform(80, 100), 4)
  25. # 将元素和对应的分数添加到有序集合中
  26. r.zadd(zset_key, {item: score})
  27. # # 从 Redis 中读取有序集合并打印
  28. # result = r.zrange(zset_key, 0, -1, withscores=True)
  29. # for item, score in result:
  30. # print(f"元素: {item}, 分数: {score}")