53 lines
1.2 KiB
Plaintext
53 lines
1.2 KiB
Plaintext
package cache
|
|
|
|
import (
|
|
"sync"
|
|
)
|
|
|
|
// Cache 结构体代表缓存
|
|
type Cache struct {
|
|
data map[string]any
|
|
rwmu sync.RWMutex
|
|
}
|
|
|
|
// NewCache 创建并返回一个新的缓存实例
|
|
func NewCache() *Cache {
|
|
return &Cache{
|
|
data: make(map[string]any),
|
|
}
|
|
}
|
|
|
|
// Set 方法用于向缓存中设置键值对,写操作会加写锁保证并发安全
|
|
func (c *Cache) set(key string, value any) {
|
|
c.rwmu.Lock()
|
|
defer c.rwmu.Unlock()
|
|
c.data[key] = value
|
|
}
|
|
|
|
// Get 方法用于从缓存中根据键获取对应的值,读操作会加读锁允许并发读
|
|
func (c *Cache) get(key string) any {
|
|
c.rwmu.RLock()
|
|
defer c.rwmu.RUnlock()
|
|
value := c.data[key]
|
|
return value
|
|
}
|
|
|
|
// Delete 方法用于从缓存中删除指定的键值对,写操作会加写锁保证并发安全
|
|
func (c *Cache) Delete(key string) {
|
|
c.rwmu.Lock()
|
|
defer c.rwmu.Unlock()
|
|
delete(c.data, key)
|
|
}
|
|
|
|
// GetData 方法用于从缓存中根据键获取对应的值,读操作会加读锁允许并发读
|
|
func GetData[V any](c *Cache, key string) (value V, ok bool) {
|
|
v := c.get(key)
|
|
value, ok = v.(V)
|
|
return
|
|
}
|
|
|
|
// SetData 方法用于向缓存中设置键值对,写操作会加写锁保证并发安全
|
|
func SetData(c *Cache, key string, value any) {
|
|
c.set(key, value)
|
|
}
|