perf: model manage (#3226)

This commit is contained in:
shaohuzhang1 2025-06-09 21:09:51 +08:00 committed by GitHub
parent 6a0a57e785
commit 5f19924f9f
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 37 additions and 24 deletions

View File

@ -6,40 +6,56 @@
@date2023/10/23 16:03 @date2023/10/23 16:03
@desc: @desc:
""" """
import threading import threading
import time import time
from common.cache.mem_cache import MemCache from common.cache.mem_cache import MemCache
lock = threading.Lock() _lock = threading.Lock()
locks = {}
class ModelManage: class ModelManage:
cache = MemCache('model', {}) cache = MemCache('model', {})
up_clear_time = time.time() up_clear_time = time.time()
@staticmethod
def _get_lock(_id):
lock = locks.get(_id)
if lock is None:
with _lock:
lock = locks.get(_id)
if lock is None:
lock = threading.Lock()
locks[_id] = lock
return lock
@staticmethod @staticmethod
def get_model(_id, get_model): def get_model(_id, get_model):
# 获取锁
lock.acquire()
try:
model_instance = ModelManage.cache.get(_id) model_instance = ModelManage.cache.get(_id)
if model_instance is None or not model_instance.is_cache_model(): if model_instance is None:
lock = ModelManage._get_lock(_id)
with lock:
model_instance = ModelManage.cache.get(_id)
if model_instance is None:
model_instance = get_model(_id) model_instance = get_model(_id)
ModelManage.cache.set(_id, model_instance, timeout=60 * 30) ModelManage.cache.set(_id, model_instance, timeout=60 * 60 * 8)
return model_instance else:
# 续期 if model_instance.is_cache_model():
ModelManage.cache.touch(_id, timeout=60 * 30) ModelManage.cache.touch(_id, timeout=60 * 60 * 8)
else:
model_instance = get_model(_id)
ModelManage.cache.set(_id, model_instance, timeout=60 * 60 * 8)
ModelManage.clear_timeout_cache() ModelManage.clear_timeout_cache()
return model_instance return model_instance
finally:
# 释放锁
lock.release()
@staticmethod @staticmethod
def clear_timeout_cache(): def clear_timeout_cache():
if time.time() - ModelManage.up_clear_time > 60: if time.time() - ModelManage.up_clear_time > 60 * 60:
ModelManage.cache.clear_timeout_data() threading.Thread(target=lambda: ModelManage.cache.clear_timeout_data()).start()
ModelManage.up_clear_time = time.time()
@staticmethod @staticmethod
def delete_key(_id): def delete_key(_id):

View File

@ -40,15 +40,12 @@ def generate():
def get_key_pair(): def get_key_pair():
rsa_value = rsa_cache.get(cache_key) rsa_value = rsa_cache.get(cache_key)
if rsa_value is None: if rsa_value is None:
lock.acquire() with lock:
rsa_value = rsa_cache.get(cache_key) rsa_value = rsa_cache.get(cache_key)
if rsa_value is not None: if rsa_value is not None:
return rsa_value return rsa_value
try:
rsa_value = get_key_pair_by_sql() rsa_value = get_key_pair_by_sql()
rsa_cache.set(cache_key, rsa_value) rsa_cache.set(cache_key, rsa_value)
finally:
lock.release()
return rsa_value return rsa_value