Golang项目:实现一个内存缓存系统

要求

  1. 支持设定过期时间,精确到秒
  2. 支持设定最大内存,当内存超过时做出合适的处理
  3. 支持并发安全
  4. 按照以下接口安全

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
}
  1. 使用示例
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 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值