Подробности среды:
- Версия Redis: 7.0.15
- Работает в Docker, сеть: мост
- Хост-система: Windows 10
- Версия Python: 3.13
- Использование redis-py-cluster для подключения
Код: Выделить всё
Conexión al Redis Cluster establecida correctamente.
Error al conectarse al Redis Cluster: Timeout connecting to server
Код: Выделить всё
import rediscluster
import time
# Configuración de los nodos del Redis Cluster
startup_nodes = [
{"host": "host.docker.internal", "port": 7001},
{"host": "host.docker.internal", "port": 7002},
{"host": "host.docker.internal", "port": 7003}
]
# Conectar al Redis Cluster
retries = 3 # Número de intentos de reconexión
for attempt in range(retries):
try:
redis_cluster = rediscluster.RedisCluster(
startup_nodes=startup_nodes,
decode_responses=True,
skip_full_coverage_check=True,
socket_connect_timeout=60, # Incrementar el tiempo de espera de conexión a 60 segundos
socket_timeout=120, # Incrementar el tiempo de espera para las operaciones a 120 segundos
retry_on_timeout=True # Habilitar reintento en caso de timeout
)
print("Conexión al Redis Cluster establecida correctamente.")
break
except Exception as e:
print(f"Error al conectarse al Redis Cluster (intento {attempt + 1}/{retries}): {e}")
if attempt == retries - 1:
raise
time.sleep(5) # Esperar 5 segundos antes de reintentar
# Verificar el estado del cluster antes de realizar operaciones
try:
cluster_info = redis_cluster.cluster_info()
if cluster_info.get('cluster_state') != 'ok':
raise Exception("El estado del cluster no es 'ok'. Verifique la configuración del cluster.")
# Ejemplo de operación usando un nodo maestro
redis_cluster.set("clave", "valor")
print("Valor de 'clave':", redis_cluster.get("clave"))
except Exception as e:
print(f"Error durante la operación en el Redis Cluster: {e}")
Чтобы создать узлы кластера Redis, я использовал следующие команды для запуска трех отдельных контейнеров Docker, в каждом из которых работает экземпляр Redis:
Код: Выделить всё
docker run -d --name redis-node1 --net redis-cluster-network -p 7001:6379 redis:7.0 redis-server --port 6379 --cluster-enabled yes --cluster-config-file nodes.conf --cluster-node-timeout 5000 --appendonly yes
docker run -d --name redis-node2 --net redis-cluster-network -p 7002:6379 redis:7.0 redis-server --port 6379 --cluster-enabled yes --cluster-config-file nodes.conf --cluster-node-timeout 5000 --appendonly yes
docker run -d --name redis-node3 --net redis-cluster-network -p 7003:6379 redis:7.0 redis-server --port 6379 --cluster-enabled yes --cluster-config-file nodes.conf --cluster-node-timeout 5000 --appendonly yes
Код: Выделить всё
redis-cli --cluster create 172.18.0.2:6379 172.18.0.3:6379 172.18.0.4:6379 --cluster-replicas 0
Код: Выделить всё
7001
Что я пробовал:
- Увеличение значений Socket_connect_timeout и Socket_timeout.
- Проверка состояния кластера Redis, чтобы убедиться, что все в порядке перед выполнением операций.
- Сопоставление портов контейнера Docker (7001, 7002, 7003) с моим локальным компьютером и используя host.docker.internal в качестве имени хоста.
- Проверка того, что каждый узел Redis имеет правильное покрытие слотов с использованием узлов кластера и слотов кластера команды.
Код: Выделить всё
2024-11-19 11:14:01 1:C 19 Nov 2024 17:14:01.843 # oO0OoO0OoO0Oo Redis is starting oO0OoO0OoO0Oo
2024-11-19 11:14:01 1:C 19 Nov 2024 17:14:01.843 # Redis version=7.0.15, bits=64, commit=00000000, modified=0, pid=1, just started
2024-11-19 11:14:01 1:C 19 Nov 2024 17:14:01.843 # Configuration loaded
2024-11-19 11:14:01 1:M 19 Nov 2024 17:14:01.844 * monotonic clock: POSIX clock_gettime
2024-11-19 11:14:01 1:M 19 Nov 2024 17:14:01.844 * No cluster configuration found, I'm 39fa992aad12f83ca4ea684d0a20ee9202e4288b
2024-11-19 11:14:01 1:M 19 Nov 2024 17:14:01.852 * Running mode=cluster, port=6379.
2024-11-19 11:14:01 1:M 19 Nov 2024 17:14:01.857 # Server initialized
2024-11-19 11:14:01 1:M 19 Nov 2024 17:14:01.861 * Creating AOF base file appendonly.aof.1.base.rdb on server start
2024-11-19 11:14:01 1:M 19 Nov 2024 17:14:01.868 * Creating AOF incr file appendonly.aof.1.incr.aof on server start
2024-11-19 11:14:01 1:M 19 Nov 2024 17:14:01.868 * Ready to accept connections
2024-11-19 11:16:43 1:M 19 Nov 2024 17:16:43.524 # configEpoch set to 2 via CLUSTER SET-CONFIG-EPOCH
2024-11-19 11:16:43 1:M 19 Nov 2024 17:16:43.691 # IP address for this node updated to 172.18.0.3
2024-11-19 11:16:48 1:M 19 Nov 2024 17:16:48.535 # Cluster state changed: ok
Почему я продолжаю получать сообщение об ошибке тайм-аута при выполнении операций, даже если первоначальное соединение прошло успешно? Может ли быть какая-либо неправильная конфигурация в настройке кластера или что-то, чего мне не хватает в коде Python? Любая помощь будет принята с благодарностью!
Подробнее здесь: https://stackoverflow.com/questions/792 ... hon-script