Go中的单例实现

问题描述 投票:1回答:1

我有一个结构:

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

  1. var singleton cache我不能检查零
  2. 如果var singleton Cache我不能施放到singleton.(cache).lock.Lock() O得到错误:cache is not a type

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

go casting thread-safety singleton
1个回答
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
}
© www.soinside.com 2019 - 2024. All rights reserved.