import time
from flask import Flask
import redis

app = Flask(__name__)

# 使用服务名 "redis" 作为 host，docker-compose 会自动识别
def get_redis_client():
    return redis.Redis(host='hadoop102', port=6379)

def get_hit_count():
    retries = 5
    while True:
        try:
            return get_redis_client().incr('hits')
        except redis.exceptions.ConnectionError as exc:
            if retries == 0:
                raise exc
            retries -= 1
            time.sleep(0.5)

@app.route('/')
def hello():
    count = get_hit_count()
    return f'Hello World! I have been seen {count} times.\n'

if __name__ == '__main__':
    app.run(debug=True)