您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

ext_redis.py 4.3KB

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