cache.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. package rag
  2. import (
  3. "fmt"
  4. "sync"
  5. "time"
  6. )
  7. // Cache 检索结果缓存
  8. type Cache struct {
  9. mu sync.RWMutex
  10. data map[string]*cacheEntry
  11. ttl time.Duration
  12. }
  13. type cacheEntry struct {
  14. results []SearchResult
  15. expiresAt time.Time
  16. }
  17. // NewCache 创建缓存实例
  18. func NewCache() *Cache {
  19. return &Cache{
  20. data: make(map[string]*cacheEntry),
  21. ttl: 0, // 默认不缓存
  22. }
  23. }
  24. // SetTTL 设置缓存过期时间
  25. func (c *Cache) SetTTL(ttl int) {
  26. c.ttl = time.Duration(ttl) * time.Second
  27. }
  28. // Get 获取缓存结果
  29. func (c *Cache) Get(query string, topK int, knowledgeBaseID *uint) ([]SearchResult, bool) {
  30. if c.ttl == 0 {
  31. return nil, false
  32. }
  33. c.mu.RLock()
  34. defer c.mu.RUnlock()
  35. key := c.buildKey(query, topK, knowledgeBaseID)
  36. entry, ok := c.data[key]
  37. if !ok {
  38. return nil, false
  39. }
  40. // 检查是否过期
  41. if time.Now().After(entry.expiresAt) {
  42. delete(c.data, key)
  43. return nil, false
  44. }
  45. return entry.results, true
  46. }
  47. // Set 设置缓存结果
  48. func (c *Cache) Set(query string, topK int, knowledgeBaseID *uint, results []SearchResult) {
  49. if c.ttl == 0 {
  50. return
  51. }
  52. c.mu.Lock()
  53. defer c.mu.Unlock()
  54. key := c.buildKey(query, topK, knowledgeBaseID)
  55. c.data[key] = &cacheEntry{
  56. results: results,
  57. expiresAt: time.Now().Add(c.ttl),
  58. }
  59. }
  60. // buildKey 构建缓存键
  61. func (c *Cache) buildKey(query string, topK int, knowledgeBaseID *uint) string {
  62. key := fmt.Sprintf("%s|%d", query, topK)
  63. if knowledgeBaseID != nil {
  64. key += fmt.Sprintf("|%d", *knowledgeBaseID)
  65. }
  66. return key
  67. }