Go中的单例实现

Rud*_*koŭ 1 singleton casting thread-safety go

我有一个结构:

type cache struct {
    cap     int
    ttl     time.Duration
    items   map[interface{}]*entry
    heap    *ttlHeap
    lock    sync.RWMutex
    NoReset bool
}
Run Code Online (Sandbox Code Playgroud)

它实现的接口:

type Cache interface {
    Set(key, value interface{}) bool
    Get(key interface{}) (interface{}, bool)
    Keys() []interface{}
    Len() int
    Cap() int
    Purge()
    Del(key interface{}) bool
}
Run Code Online (Sandbox Code Playgroud)

函数返回单例:

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
}
Run Code Online (Sandbox Code Playgroud)

我不确定哪种类型应该是我的singleton:

  1. var singleton cache我无法检查零

  2. 如果var singleton Cache我不能转向singleton.(cache).lock.Lock()O得到错误:cache is not a type

如何以正确的方式在Go中编写goroutine-safe Singleton?

Cer*_*món 6

使用sync.Once懒惰地初始化单例值:

var (
    singleton Cache
    once      sync.Once
)

func Singleton() Cache {
    once.Do(func() {
        singleton = New(10000, WithTTL(10000*100))
    })
    return singleton
}
Run Code Online (Sandbox Code Playgroud)

如果可以在程序启动时初始化,那么执行以下操作:

var singleton Cache = New(10000, WithTTL(10000*100))

func Singleton() Cache {
    return singleton
}
Run Code Online (Sandbox Code Playgroud)