This commit is contained in:
2025-02-21 08:42:56 +08:00
parent a0ee3b858b
commit 2f99149d92
9 changed files with 146 additions and 124 deletions

69
up.go
View File

@@ -1,67 +1,72 @@
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")
func (c *Cache[K, V]) update(key K, val V, t time.Time) error {
if _, ok := c.data.Load(key); !ok {
return KeyNotExists
}
c.data[key] = &Data[V]{End: t, Val: val}
data := &Data[V]{End: t, Val: val}
c.data.Store(key, data)
if c.cUpData != nil {
c.cUpData(key, *c.data[key])
c.cUpData(key, *data)
}
if c.cUpTTL != nil {
c.cUpTTL(key, *c.data[key])
c.cUpTTL(key, *data)
}
return true, nil
return 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")
func (c *Cache[K, V]) updateData(key K, val V) error {
dataAny, ok := c.data.Load(key)
if !ok {
return KeyNotExists
}
c.data[key].Val = val
data, ok := dataAny.(*Data[V])
if !ok {
return TypeErrMsg
}
data.Val = val
c.data.Store(key, data)
if c.cUpData != nil {
c.cUpData(key, *c.data[key])
c.cUpData(key, *data)
}
return true, nil
return 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")
func (c *Cache[K, V]) updateTTL(key K, ttl time.Time) error {
dataAny, ok := c.data.Load(key)
if !ok {
return KeyNotExists
}
c.data[key].End = ttl
data, ok := dataAny.(*Data[V])
if !ok {
return TypeErrMsg
}
data.End = ttl
c.data.Store(key, data)
if c.cUpTTL != nil {
c.cUpTTL(key, *c.data[key])
c.cUpTTL(key, *data)
}
return true, nil
return nil
}
// UpdateData 更新数据
// key: 键 Val: 数据 返回值: 是否更新成功 错误
func (c *Cache[K, V]) UpdateData(key K, val V) (bool, error) {
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) (bool, error) {
func (c *Cache[K, V]) UpdateTTL(key K, ttl int64) error {
if ttl == 0 {
return c.updateTTL(key, time.Time{})
}
@@ -70,6 +75,6 @@ func (c *Cache[K, V]) UpdateTTL(key K, ttl int64) (bool, error) {
// UpdateTime 更新数据到期时间(time.Time)
// key: 键 t: 到期时间 返回值: 是否更新成功 错误
func (c *Cache[K, V]) UpdateTime(key K, t time.Time) (bool, error) {
func (c *Cache[K, V]) UpdateTime(key K, t time.Time) error {
return c.updateTTL(key, t)
}