cache.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. package cache
  2. import (
  3. "context"
  4. "time"
  5. "github.com/dgraph-io/ristretto/v2"
  6. "github.com/uozi-tech/cosy/logger"
  7. )
  8. // Global cache instance
  9. var cache *ristretto.Cache[string, any]
  10. // Init initializes the cache system with search indexing and config scanning
  11. func Init(ctx context.Context) {
  12. // Force release any existing file system resources before initialization
  13. logger.Info("Initializing cache system - ensuring clean state...")
  14. ForceReleaseResources()
  15. // Initialize the main cache
  16. var err error
  17. cache, err = ristretto.NewCache(&ristretto.Config[string, any]{
  18. NumCounters: 1e7, // Track frequency of 10M keys
  19. MaxCost: 1 << 30, // Maximum cache size: 1GB
  20. BufferItems: 64, // Keys per Get buffer
  21. })
  22. if err != nil {
  23. logger.Fatal("Failed to initialize cache:", err)
  24. }
  25. // Initialize search index
  26. if err = InitSearchIndex(ctx); err != nil {
  27. logger.Error("Failed to initialize search index:", err)
  28. }
  29. // Initialize config file scanner
  30. logger.Info("Starting config scanner initialization...")
  31. InitScanner(ctx)
  32. logger.Info("Cache system initialization completed")
  33. go func() {
  34. <-ctx.Done()
  35. Shutdown()
  36. }()
  37. }
  38. // Set stores a value in cache with TTL
  39. func Set(key string, value interface{}, ttl time.Duration) {
  40. cache.SetWithTTL(key, value, 0, ttl)
  41. cache.Wait()
  42. }
  43. // Get retrieves a value from cache
  44. func Get(key string) (interface{}, bool) {
  45. return cache.Get(key)
  46. }
  47. // Del removes a value from cache
  48. func Del(key string) {
  49. cache.Del(key)
  50. }
  51. // Shutdown gracefully shuts down the cache system and releases all resources
  52. func Shutdown() {
  53. logger.Info("Shutting down cache system...")
  54. // Force release all file system resources
  55. ForceReleaseResources()
  56. // Close main cache
  57. if cache != nil {
  58. cache.Close()
  59. cache = nil
  60. logger.Info("Main cache closed")
  61. }
  62. logger.Info("Cache system shutdown completed")
  63. }