我有一个结构:
type cache struct {
cap int
ttl time.Duration
items map[interface{}]*entry
heap *ttlHeap
lock sync.RWMutex
NoReset bool
}
由它实现的接口:
type Cache interface {
Set(key, value interface{}) bool
Get(key interface{}) (interface{}, bool)
Keys() []interface{}
Len() int
Cap() int
Purge()
Del(key interface{}) bool
}
函数返回单例:
func Singleton() (cache *Cache) {
if singleton != nil {
return &singleton
}
//default
singleton.(cache).lock.Lock()
defer singleton.(cache).lock.Unlock()
c := New(10000, WithTTL(10000 * 100))
return &c
}
我不确定哪种类型应该是singleton
:
当var singleton cache
我无法检查时
如果var singleton Cache
我无法转发singleton.(cache).lock.Lock()
,则会收到错误:cache is not a type
如何以正确的方式在Go中编写goroutine-safe Singleton?
答案 0 :(得分:6)
使用sync.Once延迟初始化单例值:
var (
singleton Cache
once sync.Once
)
func Singleton() Cache {
once.Do(func() {
singleton = New(10000, WithTTL(10000*100))
})
return singleton
}
如果在程序启动时初始化是可以的,那么就这样做:
var singleton Cache = New(10000, WithTTL(10000*100))
func Singleton() Cache {
return singleton
}