ext_redis.py 3.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. import redis
  2. from redis.cluster import ClusterNode, RedisCluster
  3. from redis.connection import Connection, SSLConnection
  4. from redis.sentinel import Sentinel
  5. from configs import dify_config
  6. class RedisClientWrapper:
  7. """
  8. A wrapper class for the Redis client that addresses the issue where the global
  9. `redis_client` variable cannot be updated when a new Redis instance is returned
  10. by Sentinel.
  11. This class allows for deferred initialization of the Redis client, enabling the
  12. client to be re-initialized with a new instance when necessary. This is particularly
  13. useful in scenarios where the Redis instance may change dynamically, such as during
  14. a failover in a Sentinel-managed Redis setup.
  15. Attributes:
  16. _client (redis.Redis): The actual Redis client instance. It remains None until
  17. initialized with the `initialize` method.
  18. Methods:
  19. initialize(client): Initializes the Redis client if it hasn't been initialized already.
  20. __getattr__(item): Delegates attribute access to the Redis client, raising an error
  21. if the client is not initialized.
  22. """
  23. def __init__(self):
  24. self._client = None
  25. def initialize(self, client):
  26. if self._client is None:
  27. self._client = client
  28. def __getattr__(self, item):
  29. if self._client is None:
  30. raise RuntimeError("Redis client is not initialized. Call init_app first.")
  31. return getattr(self._client, item)
  32. redis_client = RedisClientWrapper()
  33. def init_app(app):
  34. global redis_client
  35. connection_class = Connection
  36. if dify_config.REDIS_USE_SSL:
  37. connection_class = SSLConnection
  38. redis_params = {
  39. "username": dify_config.REDIS_USERNAME,
  40. "password": dify_config.REDIS_PASSWORD,
  41. "db": dify_config.REDIS_DB,
  42. "encoding": "utf-8",
  43. "encoding_errors": "strict",
  44. "decode_responses": False,
  45. }
  46. if dify_config.REDIS_USE_SENTINEL:
  47. sentinel_hosts = [
  48. (node.split(":")[0], int(node.split(":")[1])) for node in dify_config.REDIS_SENTINELS.split(",")
  49. ]
  50. sentinel = Sentinel(
  51. sentinel_hosts,
  52. sentinel_kwargs={
  53. "socket_timeout": dify_config.REDIS_SENTINEL_SOCKET_TIMEOUT,
  54. "username": dify_config.REDIS_SENTINEL_USERNAME,
  55. "password": dify_config.REDIS_SENTINEL_PASSWORD,
  56. },
  57. )
  58. master = sentinel.master_for(dify_config.REDIS_SENTINEL_SERVICE_NAME, **redis_params)
  59. redis_client.initialize(master)
  60. elif dify_config.REDIS_USE_CLUSTERS:
  61. nodes = [
  62. ClusterNode(host=node.split(":")[0], port=int(node.split.split(":")[1]))
  63. for node in dify_config.REDIS_CLUSTERS.split(",")
  64. ]
  65. redis_client.initialize(RedisCluster(startup_nodes=nodes, password=dify_config.REDIS_CLUSTERS_PASSWORD))
  66. else:
  67. redis_params.update(
  68. {
  69. "host": dify_config.REDIS_HOST,
  70. "port": dify_config.REDIS_PORT,
  71. "connection_class": connection_class,
  72. }
  73. )
  74. pool = redis.ConnectionPool(**redis_params)
  75. redis_client.initialize(redis.Redis(connection_pool=pool))
  76. app.extensions["redis"] = redis_client