github.com/woocoos/entcache@v0.0.0-20231206055445-856f0148efa5/option.go (about) 1 package entcache 2 3 import ( 4 "github.com/mitchellh/hashstructure/v2" 5 "github.com/tsingsun/woocoo/pkg/cache" 6 "github.com/tsingsun/woocoo/pkg/conf" 7 "strconv" 8 "time" 9 ) 10 11 type ( 12 // Config wraps the basic configuration cache options. 13 Config struct { 14 // Name of the driver, used for ent cache driver mandger. 15 Name string `yaml:"name" json:"name"` 16 // Cache defines the cache implementation for holding the cache entries. 17 // Default is tinyLFU with size 100000 and HashQueryTTL 1 minute. 18 Cache cache.Cache `yaml:"-" json:"-"` 19 // HashQueryTTL defines the period of time that an Entry that is hashed through by not Get 20 // is valid in the cache. 21 HashQueryTTL time.Duration `yaml:"hashQueryTTL" json:"hashQueryTTL"` 22 // KeyQueryTTL defines the period of time that an Entry that is not hashed through by Get. This is keep the cached 23 // data fresh, can be set to long time, such as 1 hour. 24 KeyQueryTTL time.Duration `yaml:"keyQueryTTL" json:"keyQueryTTL"` 25 // GCInterval defines the period of time that the cache will be GC. 26 GCInterval time.Duration `yaml:"gcInterval" json:"gcInterval"` 27 // StoreKey is the driver name of cache driver 28 StoreKey string `yaml:"storeKey" json:"storeKey"` 29 // CachePrefix is the prefix of cache key, avoid key conflict in redis cache 30 CachePrefix string `yaml:"cachePrefix" json:"cachePrefix"` 31 // ChangeSet manages data change 32 ChangeSet *ChangeSet 33 } 34 35 // Option allows configuring the cache 36 // driver using functional options. 37 Option func(*Config) 38 ) 39 40 func WithChangeSet(cs *ChangeSet) Option { 41 return func(c *Config) { 42 c.ChangeSet = cs 43 } 44 } 45 46 // WithCache provides a cache implementation for holding the cache entries. 47 func WithCache(cc cache.Cache) Option { 48 return func(c *Config) { 49 c.Cache = cc 50 } 51 } 52 53 // WithConfiguration provides a configuration option for the cache driver. 54 func WithConfiguration(cnf *conf.Configuration) Option { 55 return func(c *Config) { 56 if err := cnf.Unmarshal(c); err != nil { 57 panic(err) 58 } 59 } 60 } 61 62 // DefaultHash provides the default implementation for converting 63 // a query and its argument to a cache key. 64 func DefaultHash(query string, args []any) (Key, error) { 65 key, err := hashstructure.Hash(struct { 66 Q string 67 A []any 68 }{ 69 Q: query, 70 A: args, 71 }, hashstructure.FormatV2, nil) 72 if err != nil { 73 return "", err 74 } 75 return Key(strconv.FormatUint(key, 10)), nil 76 }