49 lines
1.2 KiB
Go
49 lines
1.2 KiB
Go
package cache
|
|
|
|
import (
|
|
"errors"
|
|
"time"
|
|
)
|
|
|
|
func (c *Cache[K, V]) set(key K, val V, t time.Time) (bool, error) {
|
|
c.mu.Lock()
|
|
defer c.mu.Unlock()
|
|
|
|
if _, ok := c.data[key]; ok {
|
|
return false, errors.New("key already exists")
|
|
}
|
|
|
|
c.data[key] = &Data[V]{End: t, Val: val}
|
|
if c.cSet != nil {
|
|
c.cSet(key, *c.data[key])
|
|
}
|
|
return true, nil
|
|
}
|
|
|
|
// setForced 强制设置数据 数据存在则覆盖
|
|
func (c *Cache[K, V]) setForced(key K, val V, t time.Time) error {
|
|
c.mu.Lock()
|
|
defer c.mu.Unlock()
|
|
|
|
c.data[key] = &Data[V]{End: t, Val: val}
|
|
if c.cSet != nil {
|
|
c.cSet(key, *c.data[key])
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// Set 设置数据 数据存在则报错
|
|
// key: 键 Val: 数据 ttl: 过期时间(秒) 0表示永不过期 返回值: 是否设置成功 错误
|
|
func (c *Cache[K, V]) Set(key K, val V, ttl int64) (bool, 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) (bool, error) {
|
|
return c.set(key, val, time.Time{})
|
|
}
|