memcache.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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) (buf []byte, err error) {
  27. var (
  28. ok bool
  29. )
  30. if buf, ok = cache.Get(ctx, key); ok {
  31. return buf, nil
  32. }
  33. if cb == nil {
  34. return nil, os.ErrNotExist
  35. }
  36. if buf, err = cb(ctx); err == nil {
  37. cache.Set(ctx, key, buf)
  38. }
  39. return
  40. }
  41. func (cache *MemCache) Set(ctx context.Context, key string, buf []byte) {
  42. cache.engine.Set(key, buf, 0)
  43. }
  44. func (cache *MemCache) SetEx(ctx context.Context, key string, buf []byte, expire time.Duration) {
  45. cache.engine.Set(key, buf, expire)
  46. }
  47. func (cache *MemCache) Get(ctx context.Context, key string) (buf []byte, ok bool) {
  48. var (
  49. val any
  50. )
  51. if val, ok = cache.engine.Get(key); ok {
  52. buf, ok = val.([]byte)
  53. }
  54. return
  55. }
  56. func (cache *MemCache) Del(ctx context.Context, key string) {
  57. cache.engine.Delete(key)
  58. }
  59. func NewMemCache() *MemCache {
  60. return &MemCache{
  61. engine: cache.New(memCacheDefaultExpired, memCacheCleanupInterval),
  62. }
  63. }