要求
- 支持设定过期时间,精确到秒
- 支持设定最大内存,当内存超过时做出合适的处理
- 支持并发安全
- 按照以下接口安全
type Cache interface{
//size : 1KB 100KB 1MB 2MB 1GB
SetMaxMemory(size string )bool
//将value写入缓存
Set(key string, val interface{
},expire time.Duration)bool
//根据key值获取value
Get(key string )(interface{
},bool)
//删除key
Del(key string)bool
//判断key是否存在
Exists(key string)bool
//清空所有key
Flush()bool
//获取缓存中所有key的数量
Keys()int64
}
- 使用示例
cache := NewMemCache()
cache.SetMaxMemory("100MB")
cache.Set("int",1)
cache.Set("bool",false)
cache.Set("data",map[string]interface(){
"a":1})
cache.Get("int")
cache.Del("int")
cache.Flush()
cache.Keys()
首先创建对应文件夹
其中main.go中填入测试案例
package main
import (
"memCache/cache"
"time"
)
func main() {
cache := cache.NewMemCache()
cache.SetMaxMemory("200MB")
cache.Set("int", 1, time.Second)
cache.Set("bool", false, time.Second)
cache.Set("data", map[string]interface{
}{
"a": 1}, time.Second)
//cache.Set("int",1)
//cache.Set("bool",false)
//cache.Set("data",map[string]interface{}{"a":1})
cache.Get("int")
cache.Del("int")
cache.Flush()
cache.Keys()
//num, str := cache.ParseSize("2KB")
//fmt.Println(num, str)
}
定义cache.go的接口
package cache
import "time"
type Cache interface {
//size : 1KB 100KB 1MB 2MB 1GB
SetMaxMemory(size string) bool
//将value写入缓存
Set(key string, val interface{
}, expire time.Duration) bool
//根据key值获取value
Get(key string) (interface{
}, bool)
//删除key
Del(key string) bool
//判断key是否存在
Exists(key string) bool
//清空所有key
Flush() bool
//获取缓存中所有key的数量
Keys() int64
}
然后在memCache.go中实现
package cache
import (
"fmt"
"time"
)
type memCache struct {
//最大内存 -- 单位字节
maxMemorySize int64
//最大内存字符串表示
maxMemorySizeStr string
//当前内存大小 -- 单位字节
currentMemorySize int64
}
func NewMemCache() Cache {
return &memCache{
}
}
// size : 1KB 100KB 1MB 2MB 1GB
func (mc *memCache) SetMaxMemory(size string) bool {
mc.maxMemorySize, mc.maxMemorySizeStr = ParseSize(size)
fmt.Println(mc.maxMemorySize, mc.maxMemorySizeStr)
fmt.Println("called set Maxmem")
return false
}
// 将value写入缓存
func (mc *memCache) Set(key string, val interface{
}, expire time.Duration) bool