81 lines
1.6 KiB
Go
81 lines
1.6 KiB
Go
package cache
|
|
|
|
import (
|
|
"time"
|
|
)
|
|
|
|
func (c *Cache[K, V]) update(key K, val V, t time.Time) error {
|
|
if _, ok := c.data.Load(key); !ok {
|
|
return KeyNotExists
|
|
}
|
|
|
|
data := &Data[V]{End: t, Val: val}
|
|
c.data.Store(key, data)
|
|
if c.cUpData != nil {
|
|
c.cUpData(key, *data)
|
|
}
|
|
if c.cUpTTL != nil {
|
|
c.cUpTTL(key, *data)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (c *Cache[K, V]) updateData(key K, val V) error {
|
|
dataAny, ok := c.data.Load(key)
|
|
if !ok {
|
|
return KeyNotExists
|
|
}
|
|
|
|
data, ok := dataAny.(*Data[V])
|
|
if !ok {
|
|
return TypeErrMsg
|
|
}
|
|
|
|
data.Val = val
|
|
c.data.Store(key, data)
|
|
if c.cUpData != nil {
|
|
c.cUpData(key, *data)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (c *Cache[K, V]) updateTTL(key K, ttl time.Time) error {
|
|
dataAny, ok := c.data.Load(key)
|
|
if !ok {
|
|
return KeyNotExists
|
|
}
|
|
|
|
data, ok := dataAny.(*Data[V])
|
|
if !ok {
|
|
return TypeErrMsg
|
|
}
|
|
|
|
data.End = ttl
|
|
c.data.Store(key, data)
|
|
if c.cUpTTL != nil {
|
|
c.cUpTTL(key, *data)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// UpdateData 更新数据
|
|
// key: 键 Val: 数据 返回值: 是否更新成功 错误
|
|
func (c *Cache[K, V]) UpdateData(key K, val V) error {
|
|
return c.updateData(key, val)
|
|
}
|
|
|
|
// UpdateTTL 更新数据过期时间
|
|
// key: 键 ttl: 过期时间(秒) 0表示永不过期 返回值: 是否更新成功 错误
|
|
func (c *Cache[K, V]) UpdateTTL(key K, ttl int64) error {
|
|
if ttl == 0 {
|
|
return c.updateTTL(key, time.Time{})
|
|
}
|
|
return c.updateTTL(key, time.Now().Add(time.Second*time.Duration(ttl)))
|
|
}
|
|
|
|
// UpdateTime 更新数据到期时间(time.Time)
|
|
// key: 键 t: 到期时间 返回值: 是否更新成功 错误
|
|
func (c *Cache[K, V]) UpdateTime(key K, t time.Time) error {
|
|
return c.updateTTL(key, t)
|
|
}
|