options.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. package cache
  2. import "time"
  3. type Option func(*options)
  4. type options struct {
  5. ttl time.Duration // 缓存 TTL
  6. async bool // 是否异步写缓存
  7. lockEnabled bool // 是否启用分布式锁防击穿
  8. lockTTL time.Duration // 锁过期
  9. prefix string // key 前缀
  10. waitForCache time.Duration // 获取不到锁时等待缓存可用的最大时间(轮询)
  11. staleThreshold time.Duration // stale 模式中视为“过期但可用”的阈值
  12. }
  13. func defaultOptions() *options {
  14. return &options{
  15. ttl: 5 * time.Minute,
  16. async: true,
  17. lockEnabled: true,
  18. lockTTL: 5 * time.Second,
  19. prefix: "",
  20. waitForCache: 500 * time.Millisecond,
  21. staleThreshold: 30 * time.Second,
  22. }
  23. }
  24. // 配置 helper
  25. func WithTTL(ttl time.Duration) Option {
  26. return func(o *options) { o.ttl = ttl }
  27. }
  28. func WithAsync(async bool) Option {
  29. return func(o *options) { o.async = async }
  30. }
  31. func WithLock(enabled bool) Option {
  32. return func(o *options) { o.lockEnabled = enabled }
  33. }
  34. func WithLockTTL(ttl time.Duration) Option {
  35. return func(o *options) { o.lockTTL = ttl }
  36. }
  37. func WithPrefix(prefix string) Option {
  38. return func(o *options) { o.prefix = prefix }
  39. }
  40. func WithWaitForCache(d time.Duration) Option {
  41. return func(o *options) { o.waitForCache = d }
  42. }
  43. func WithStaleThreshold(d time.Duration) Option {
  44. return func(o *options) { o.staleThreshold = d }
  45. }