This commit is contained in:
2024-08-17 12:04:33 +08:00
commit c13f9b8b82
12 changed files with 791 additions and 0 deletions

75
up.go Normal file
View File

@@ -0,0 +1,75 @@
package cache
import (
"errors"
"time"
)
func (c *Cache[K, V]) update(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 not exists")
}
c.data[key] = &Data[V]{End: t, Val: val}
if c.cUpData != nil {
c.cUpData(key, *c.data[key])
}
if c.cUpTTL != nil {
c.cUpTTL(key, *c.data[key])
}
return true, nil
}
func (c *Cache[K, V]) updateData(key K, val V) (bool, error) {
c.mu.Lock()
defer c.mu.Unlock()
if _, ok := c.data[key]; !ok {
return false, errors.New("key not exists")
}
c.data[key].Val = val
if c.cUpData != nil {
c.cUpData(key, *c.data[key])
}
return true, nil
}
func (c *Cache[K, V]) updateTTL(key K, ttl time.Time) (bool, error) {
c.mu.Lock()
defer c.mu.Unlock()
if _, ok := c.data[key]; !ok {
return false, errors.New("key not exists")
}
c.data[key].End = ttl
if c.cUpTTL != nil {
c.cUpTTL(key, *c.data[key])
}
return true, nil
}
// UpdateData 更新数据
// key: 键 Val: 数据 返回值: 是否更新成功 错误
func (c *Cache[K, V]) UpdateData(key K, val V) (bool, error) {
return c.updateData(key, val)
}
// UpdateTTL 更新数据过期时间
// key: 键 ttl: 过期时间(秒) 0表示永不过期 返回值: 是否更新成功 错误
func (c *Cache[K, V]) UpdateTTL(key K, ttl int64) (bool, 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) (bool, error) {
return c.updateTTL(key, t)
}