cache.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. package cache
  2. import (
  3. "time"
  4. "github.com/jellydator/ttlcache/v3"
  5. )
  6. // CacheContainer is a container for all caches.
  7. type CacheContainer struct {
  8. caches map[string]*CacheInstance
  9. }
  10. // CacheInstance is a single cache instance.
  11. type CacheInstance struct {
  12. cache *ttlcache.Cache[string, []byte]
  13. }
  14. // This is the global singleton instance. (To be removed after refactor).
  15. var _instance *CacheContainer
  16. // NewCache creates a new cache instance.
  17. func NewGlobalCache() *CacheContainer {
  18. _instance = &CacheContainer{
  19. caches: make(map[string]*CacheInstance),
  20. }
  21. return _instance
  22. }
  23. // GetCache returns the cache instance.
  24. func GetGlobalCache() *CacheContainer {
  25. if _instance != nil {
  26. return _instance
  27. }
  28. return NewGlobalCache()
  29. }
  30. // GetOrCreateCache returns the cache instance or creates a new one.
  31. func (c *CacheContainer) GetOrCreateCache(name string, expiration time.Duration) *CacheInstance {
  32. if _, ok := c.caches[name]; !ok {
  33. c.CreateCache(name, expiration)
  34. }
  35. return c.caches[name]
  36. }
  37. // CreateCache creates a new cache instance.
  38. func (c *CacheContainer) CreateCache(name string, expiration time.Duration) *CacheInstance {
  39. cache := ttlcache.New[string, []byte](
  40. ttlcache.WithTTL[string, []byte](expiration),
  41. ttlcache.WithDisableTouchOnHit[string, []byte](),
  42. )
  43. ci := &CacheInstance{cache: cache}
  44. c.caches[name] = ci
  45. go cache.Start()
  46. return ci
  47. }
  48. // GetCache returns the cache instance.
  49. func (c *CacheContainer) GetCache(name string) *CacheInstance {
  50. return c.caches[name]
  51. }
  52. // GetValueForKey returns the value for the given key.
  53. func (ci *CacheInstance) GetValueForKey(key string) []byte {
  54. value := ci.cache.Get(key, ttlcache.WithDisableTouchOnHit[string, []byte]())
  55. if value == nil {
  56. return nil
  57. }
  58. if value.IsExpired() {
  59. return nil
  60. }
  61. val := value.Value()
  62. return val
  63. }
  64. // Set sets the value for the given key..
  65. func (ci *CacheInstance) Set(key string, value []byte) {
  66. ci.cache.Set(key, value, 0)
  67. }