Files
cache/set.go
2025-02-21 08:42:56 +08:00

63 lines
1.8 KiB
Go

package cache
import (
"errors"
"time"
)
func (c *Cache[K, V]) set(key K, val V, t time.Time) error {
data := &Data[V]{End: t, Val: val}
if dataAny, ok := c.data.LoadOrStore(key, data); ok {
data = dataAny.(*Data[V])
if data.End.After(time.Now()) {
return errors.New("key already exists")
} else {
c.data.Store(key, data)
}
}
if c.cSet != nil {
c.cSet(key, *data)
}
return nil
}
// setForced 强制设置数据 数据存在则覆盖
func (c *Cache[K, V]) setForced(key K, val V, t time.Time) error {
data := &Data[V]{End: t, Val: val}
c.data.Store(key, data)
if c.cSet != nil {
c.cSet(key, *data)
}
return nil
}
// Set 设置数据 数据存在则报错
// key: 键 Val: 数据 ttl: 过期时间(秒) 0表示永不过期 返回值: 错误
func (c *Cache[K, V]) Set(key K, val V, ttl int64) error {
if ttl == 0 {
return c.set(key, val, time.Time{})
}
return c.set(key, val, time.Now().Add(time.Second*time.Duration(ttl)))
}
// SetData 设置数据 数据存在则报错 永不过期
// key: 键 Val: 数据 返回值: 是否设置成功 错误 返回值: 是否设置成功 错误
func (c *Cache[K, V]) SetData(key K, val V) error {
return c.set(key, val, time.Time{})
}
// SetF 设置数据 数据存在则覆盖
// key: 键 Val: 数据 ttl: 过期时间(秒) 0表示永不过期 返回值: 错误
func (c *Cache[K, V]) SetF(key K, val V, ttl int64) error {
if ttl == 0 {
return c.setForced(key, val, time.Time{})
}
return c.setForced(key, val, time.Now().Add(time.Second*time.Duration(ttl)))
}
// SetFData 设置数据 数据存在则覆盖 永不过期
// key: 键 Val: 数据 返回值: 是否设置成功 错误 返回值: 是否设置成功 错误
func (c *Cache[K, V]) SetFData(key K, val V) error {
return c.setForced(key, val, time.Time{})
}