From 6db708d5e6ef3579ad987f13e3ec7a39c8ae9f6d Mon Sep 17 00:00:00 2001 From: cuiweizhi <560397@gree.com.cn> Date: Sat, 4 Nov 2023 15:04:51 +0800 Subject: [PATCH] Update project --- .../libs/flask_elasticsearch/elasticsearch.py | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/application/libs/flask_elasticsearch/elasticsearch.py b/application/libs/flask_elasticsearch/elasticsearch.py index 9eee7d0..f82f912 100644 --- a/application/libs/flask_elasticsearch/elasticsearch.py +++ b/application/libs/flask_elasticsearch/elasticsearch.py @@ -10,6 +10,7 @@ # @Description : """ +import time from typing import Any from elasticsearch import Elasticsearch @@ -65,11 +66,17 @@ class FlaskElasticsearch: if not hasattr(ctx, 'elasticsearch'): cfg = self._get_config() ctx.elasticsearch = Elasticsearch(**cfg) - if ctx.elasticsearch.ping(): - logger.info('Connected to Elasticsearch') + # Retry connection on failure + for i in range(5): # Retry up to 5 times + if ctx.elasticsearch.ping(): + logger.info('Connected to Elasticsearch') + break + else: + logger.warning(f'Attempt {i + 1} to connect to Elasticsearch failed. Retrying...') + time.sleep(2 ** i) # Exponential backoff else: - logger.error('Can not connect to Elasticsearch') - raise ConnectionError('Can not connect to Elasticsearch') + logger.error('Can not connect to Elasticsearch after 5 attempts') + raise ConnectionError('Can not connect to Elasticsearch after 5 attempts') return getattr(ctx.elasticsearch, item) @staticmethod -- GitLab