AsyncSearchWithResult 异步搜索方法,返回PluginSearchResult
(
keyword string,
searchFunc func(*http.Client, string, map[string]interface{}) ([]model.SearchResult, error),
mainCacheKey string,
ext map[string]interface{},
)
| 783 | |
| 784 | // AsyncSearchWithResult 异步搜索方法,返回PluginSearchResult |
| 785 | func (p *BaseAsyncPlugin) AsyncSearchWithResult( |
| 786 | keyword string, |
| 787 | searchFunc func(*http.Client, string, map[string]interface{}) ([]model.SearchResult, error), |
| 788 | mainCacheKey string, |
| 789 | ext map[string]interface{}, |
| 790 | ) (model.PluginSearchResult, error) { |
| 791 | // 确保ext不为nil |
| 792 | if ext == nil { |
| 793 | ext = make(map[string]interface{}) |
| 794 | } |
| 795 | |
| 796 | now := time.Now() |
| 797 | |
| 798 | // 修改缓存键,确保包含插件名称 |
| 799 | pluginSpecificCacheKey := fmt.Sprintf("%s:%s", p.name, keyword) |
| 800 | |
| 801 | // 检查缓存 |
| 802 | if cachedItems, ok := apiResponseCache.Load(pluginSpecificCacheKey); ok { |
| 803 | cachedResult := cachedItems.(cachedResponse) |
| 804 | |
| 805 | // 缓存完全有效(未过期且完整) |
| 806 | if time.Since(cachedResult.Timestamp) < p.cacheTTL && cachedResult.Complete { |
| 807 | recordCacheHit() |
| 808 | recordCacheAccess(pluginSpecificCacheKey) |
| 809 | |
| 810 | // 如果缓存接近过期(已用时间超过TTL的80%),在后台刷新缓存 |
| 811 | if time.Since(cachedResult.Timestamp) > (p.cacheTTL * 4 / 5) { |
| 812 | go p.refreshCacheInBackground(keyword, pluginSpecificCacheKey, searchFunc, cachedResult, mainCacheKey, ext) |
| 813 | } |
| 814 | |
| 815 | return model.PluginSearchResult{ |
| 816 | Results: cachedResult.Results, |
| 817 | IsFinal: cachedResult.Complete, |
| 818 | Timestamp: cachedResult.Timestamp, |
| 819 | Source: p.name, |
| 820 | Message: "从缓存获取", |
| 821 | }, nil |
| 822 | } |
| 823 | |
| 824 | // 缓存已过期但有结果,启动后台刷新,同时返回旧结果 |
| 825 | if len(cachedResult.Results) > 0 { |
| 826 | recordCacheHit() |
| 827 | recordCacheAccess(pluginSpecificCacheKey) |
| 828 | |
| 829 | // 标记为部分过期 |
| 830 | if time.Since(cachedResult.Timestamp) >= p.cacheTTL { |
| 831 | // 在后台刷新缓存 |
| 832 | go p.refreshCacheInBackground(keyword, pluginSpecificCacheKey, searchFunc, cachedResult, mainCacheKey, ext) |
| 833 | } |
| 834 | |
| 835 | return model.PluginSearchResult{ |
| 836 | Results: cachedResult.Results, |
| 837 | IsFinal: false, // 🔥 过期数据标记为非最终结果 |
| 838 | Timestamp: cachedResult.Timestamp, |
| 839 | Source: p.name, |
| 840 | Message: "缓存已过期,后台刷新中", |
| 841 | }, nil |
| 842 | } |
no test coverage detected