From cf78ac6f5363e6fe9ee98d726af67105da6a170a Mon Sep 17 00:00:00 2001 From: iron <472263356@qq.com> Date: Thu, 18 Aug 2022 21:40:59 +0800 Subject: [PATCH] feat: add expire time --- app/api/web.py | 5 +++-- app/libs/redis.py | 3 +++ docker-compose.yml | 14 +++++++++++++- 3 files changed, 19 insertions(+), 3 deletions(-) diff --git a/app/api/web.py b/app/api/web.py index 4d37ee3..7f11592 100644 --- a/app/api/web.py +++ b/app/api/web.py @@ -1,4 +1,3 @@ -from email.policy import default import json from app.libs.db import db_helper @@ -96,6 +95,8 @@ def get_news(): if page == default_page and page_size == default_page_size: top_20 = list(map(json.dumps, data)) redis_helper.set_list(prex_key, *top_20) + # cache 6h + redis_helper.set_expire(prex_key, 6 * 60 * 60) return show_reponse( data={ @@ -113,7 +114,7 @@ def get_news_by_id(): if not data: return show_reponse(code=Status.other, message="param error") article_id = data.get("id") - + prefix_key = f"pbs_{article_id}" if redis_helper.has(prefix_key): detail = redis_helper.get(prefix_key) diff --git a/app/libs/redis.py b/app/libs/redis.py index 10f25b7..ce25143 100644 --- a/app/libs/redis.py +++ b/app/libs/redis.py @@ -23,6 +23,9 @@ def __init__(self) -> None: else: logger.error("Connect Redis Fail!") + def set_expire(self, name, time): + return self.__conn.expire(name, time) + def has(self, name): return self.__conn.exists(name) == 1 diff --git a/docker-compose.yml b/docker-compose.yml index f2d6cbb..9bfb3be 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -11,13 +11,23 @@ services: - "3308:3306" volumes: # init database and table - - ./init_db.sql:/docker-entrypoint-initdb.d/init_db.sql + - ./init_db.sql:/docker-entrypoint-initdb.d/init_db.sql + - ./mysql-data:/var/lib/mysql networks: - db environment: MYSQL_DATABASE: ai_english MYSQL_ROOT_PASSWORD: abc124 + redis: + image: redis + command: redis-server /usr/local/etc/redis/redis.conf + volumes: + - ./redis-cnf:/usr/local/etc/redis + - ./redis-data:/data + networks: + - redis + # uwsgi api: build: . @@ -34,6 +44,7 @@ services: - api depends_on: - db + - redis env_file: .env environment: UWSGI_SOCKET: 0.0.0.0:8000 @@ -93,5 +104,6 @@ services: networks: db: + redis: api: web: