From a9c77874311dcde97100a731cb65b6758c3c43dd Mon Sep 17 00:00:00 2001 From: NothAmor Date: Mon, 31 Jul 2023 01:14:43 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E6=B3=A8=E9=87=8A?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- main.go | 40 +++++++++++++++++++++++++++++++++++----- 1 file changed, 35 insertions(+), 5 deletions(-) diff --git a/main.go b/main.go index 68153eb..88109d1 100644 --- a/main.go +++ b/main.go @@ -33,12 +33,16 @@ type CacheInterface interface { } type Cache struct { - ObjectCount int64 - CurrentMemory int64 - MaxMemory *int64 - Storage map[string]interface{} + ObjectCount int64 // 缓存中对象数量 + CurrentMemory int64 // 当前缓存占用内存大小 + MaxMemory *int64 // 最大缓存内存大小 + Storage map[string]interface{} // 缓存存储 } +/* + * 设置最大内存 + * size: 1KB 100KB 1MB 2MB 1GB + */ func (C *Cache) SetMaxMemory(size string) (err error) { var ( gb bool = strings.Contains(size, "GB") || strings.Contains(size, "gb") @@ -94,16 +98,25 @@ func (C *Cache) SetMaxMemory(size string) (err error) { return } +/* + * 设置缓存 + * key: 缓存key + * val: 缓存value + * expire: 过期时间 + */ func (C *Cache) Set(key string, val interface{}, expire time.Duration) (err error) { + // 判断是否超过最大内存 valSize := unsafe.Sizeof(val) if valSize+uintptr(C.CurrentMemory) > uintptr(*C.MaxMemory) { return fmt.Errorf("exceed maximum memory, set failed") } + // 设置缓存 C.Storage[key] = val C.CurrentMemory += int64(valSize) C.ObjectCount++ + // 设置过期时间 go func() { time.Sleep(expire) C.Del(key) @@ -111,6 +124,10 @@ func (C *Cache) Set(key string, val interface{}, expire time.Duration) (err erro return } +/* + * 获取缓存 + * key: 缓存key + */ func (C *Cache) Get(key string) (val interface{}, err error) { var ok bool if val, ok = C.Storage[key]; ok { @@ -121,10 +138,13 @@ func (C *Cache) Get(key string) (val interface{}, err error) { } } +/* + * 删除缓存 + * key: 缓存key + */ func (C *Cache) Del(key string) (err error) { if val, ok := C.Storage[key]; ok { delete(C.Storage, key) - C.ObjectCount-- valSize := unsafe.Sizeof(val) @@ -135,6 +155,10 @@ func (C *Cache) Del(key string) (err error) { } } +/* + * 判断key是否存在 + * key: 缓存key + */ func (C *Cache) Exists(key string) (exist bool, err error) { if _, ok := C.Storage[key]; ok { exist = true @@ -145,6 +169,9 @@ func (C *Cache) Exists(key string) (exist bool, err error) { } } +/* + * 清空所有缓存 + */ func (C *Cache) Flush() (err error) { C.Storage = make(map[string]interface{}) C.ObjectCount = 0 @@ -153,6 +180,9 @@ func (C *Cache) Flush() (err error) { return } +/* + * 获取缓存中所有key的数量 + */ func (C *Cache) Keys() (count int64) { return C.ObjectCount }