cache.go 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  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. // Initialize the main cache
  13. var err error
  14. cache, err = ristretto.NewCache(&ristretto.Config[string, any]{
  15. NumCounters: 1e7, // Track frequency of 10M keys
  16. MaxCost: 1 << 30, // Maximum cache size: 1GB
  17. BufferItems: 64, // Keys per Get buffer
  18. })
  19. if err != nil {
  20. logger.Fatal("Failed to initialize cache:", err)
  21. }
  22. // Initialize search index
  23. if err = InitSearchIndex(ctx); err != nil {
  24. logger.Error("Failed to initialize search index:", err)
  25. }
  26. // Initialize config file scanner
  27. InitScanner(ctx)
  28. }
  29. // Set stores a value in cache with TTL
  30. func Set(key string, value interface{}, ttl time.Duration) {
  31. cache.SetWithTTL(key, value, 0, ttl)
  32. cache.Wait()
  33. }
  34. // Get retrieves a value from cache
  35. func Get(key string) (interface{}, bool) {
  36. return cache.Get(key)
  37. }
  38. // Del removes a value from cache
  39. func Del(key string) {
  40. cache.Del(key)
  41. }