memory_storage.py 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. import redis
  2. class MemoryStorage:
  3. def __init__(self, config):
  4. self.ip = config['ip']
  5. self.port = config['port']
  6. self.conn = None
  7. self.connected()
  8. def connected(self):
  9. self.conn = redis.StrictRedis(host=self.ip, port=self.port, db=0, decode_responses=True)
  10. def set_value(self, data_dict):
  11. try:
  12. pipe = self.conn.pipeline(transaction=True)
  13. for key_name in data_dict.keys():
  14. pipe.set(key_name, data_dict[key_name], ex=30*60) # redis过期时间
  15. pipe.execute()
  16. except Exception as e:
  17. print(e)
  18. return e
  19. else:
  20. return True
  21. def get_value(self, keys):
  22. data_dict = {}
  23. try:
  24. pipe = self.conn.pipeline(transaction=True)
  25. for index in range(len(keys)):
  26. pipe.get(keys[index])
  27. result = pipe.execute()
  28. for index in range(len(keys)):
  29. data_dict[keys[index]] = result[index]
  30. return data_dict
  31. except Exception as e:
  32. return e
  33. def is_connected(self):
  34. if self.conn:
  35. return True
  36. else:
  37. return False
  38. def re_connected(self):
  39. self.conn = redis.StrictRedis(host=self.ip, port=self.port, db=0, decode_responses=True)