新增搜索结果缓存功能

- 新增 search_cache 数据库表存储搜索缓存
- 搜索前优先查询缓存,命中则直接返回
- 缓存默认有效期7天,可配置
- 前端支持'使用缓存'开关选项
- 显示缓存状态提示
- 支持自动清理过期缓存
This commit is contained in:
2026-07-13 22:55:36 +08:00
parent 50379f5ecf
commit c960d959ad
5 changed files with 115 additions and 6 deletions
+17 -2
View File
@@ -33,7 +33,7 @@ class SearchService:
)
return result.stdout, result.stderr, result.returncode
def search_internet(self, keyword, max_results=None, engine='bing_cn'):
def search_internet(self, keyword, max_results=None, engine='bing_cn', use_cache=True, cache_days=7):
"""
从互联网搜索(使用 agent-browser 浏览器自动化)
@@ -42,10 +42,21 @@ class SearchService:
- bing_global: Bing 国际版
- google: Google
- baidu: 百度
参数:
- use_cache: 是否使用缓存(默认True)
- cache_days: 缓存有效天数(默认7天)
"""
max_results = max_results or self.max_results
results = []
# 优先查询缓存
if use_cache:
cached = db.get_search_cache(keyword, engine)
if cached:
print(f"使用缓存结果: {keyword} ({engine})")
return cached['results']
# 根据搜索引擎选择 URL
encoded_keyword = urllib.parse.quote(keyword)
search_urls = {
@@ -74,7 +85,7 @@ class SearchService:
return results
# 3. 解析 JSON 提取搜索结果
try:
try {
data = json.loads(stdout)
except json.JSONDecodeError:
print(f"解析 JSON 失败: {stdout[:500]}")
@@ -89,6 +100,10 @@ class SearchService:
# 5. 关闭浏览器
self._run_browser('close')
# 6. 保存到缓存
if results and use_cache:
db.save_search_cache(keyword, engine, results, cache_days)
except subprocess.TimeoutExpired:
print(f"搜索超时: {keyword}")
except Exception as e: