memcache.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. package cache
  2. import (
  3. "context"
  4. "git.nspix.com/golang/kos/util/env"
  5. "github.com/patrickmn/go-cache"
  6. "os"
  7. "time"
  8. )
  9. var (
  10. memCacheDefaultExpired time.Duration
  11. memCacheCleanupInterval time.Duration
  12. )
  13. func init() {
  14. memCacheDefaultExpired, _ = time.ParseDuration(env.Get("MEMCACHE_DEFAULT_EXPIRED", "1h"))
  15. memCacheCleanupInterval, _ = time.ParseDuration(env.Get("MEMCACHE_CLEANUP_INTERVAL", "10m"))
  16. if memCacheDefaultExpired < time.Second*5 {
  17. memCacheDefaultExpired = time.Second * 5
  18. }
  19. if memCacheCleanupInterval < time.Minute {
  20. memCacheCleanupInterval = time.Minute
  21. }
  22. }
  23. type MemCache struct {
  24. engine *cache.Cache
  25. }
  26. func (cache *MemCache) Try(ctx context.Context, key string, cb LoadFunc) (value any, err error) {
  27. var (
  28. ok bool
  29. )
  30. if value, ok = cache.engine.Get(key); ok {
  31. return value, nil
  32. }
  33. if cb == nil {
  34. return nil, os.ErrNotExist
  35. }
  36. if value, err = cb(ctx); err == nil {
  37. cache.engine.Set(key, value, 0)
  38. }
  39. return
  40. }
  41. func (cache *MemCache) Set(ctx context.Context, key string, value any) {
  42. cache.engine.Set(key, value, 0)
  43. }
  44. func (cache *MemCache) SetEx(ctx context.Context, key string, value any, expire time.Duration) {
  45. cache.engine.Set(key, value, expire)
  46. }
  47. func (cache *MemCache) Get(ctx context.Context, key string) (value any, ok bool) {
  48. return cache.engine.Get(key)
  49. }
  50. func (cache *MemCache) Del(ctx context.Context, key string) {
  51. cache.engine.Delete(key)
  52. }
  53. func NewMemCache() *MemCache {
  54. return &MemCache{
  55. engine: cache.New(memCacheDefaultExpired, memCacheCleanupInterval),
  56. }
  57. }