添加注释

This commit is contained in:
NothAmor 2023-07-31 01:14:43 +08:00
parent 3cea33f2f9
commit a9c7787431

40
main.go
View File

@ -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
}