SoFunction
Updated on 2025-03-03

Go implements a memory cache system sample code

Interview content:

  • Supports setting expiration time, accuracy to seconds
  • Supports setting maximum memory, and make appropriate processing when memory exceeds
  • Support concurrent security
  • It is required to implement it according to the following interfaces
SetMemory(size string) bool
	Set(key string, val interface{}, expire ) bool
	Get(key string) (interface{}, bool)
	Del(key string) bool
	Exists(key string) bool
	Flush() bool
	Keys() int64

The following is the specific implementation code:

interface

package cache
import "time"
type Cache interface {
	SetMemory(size string) bool
	Set(key string, val interface{}, expire ) bool
	Get(key string) (interface{}, bool)
	Del(key string) bool
	Exists(key string) bool
	Flush() bool
	Keys() int64
}

Implementation Class

package cache

import (
	"fmt"
	"sync"
	"time"
)

type MemCache struct {
	//Maximum memory	maxMemorySize int64
	// The memory currently used	currMemorySize int64
	// Maximum memory string representation	maxMemorySizeStr string
	// Cache key-value pairs	values map[string]*memCacheValue
	// Read and write lock	lock 
	//Set the time interval for clearing expired cache	clearExpireTime 
}

type memCacheValue struct {
	//value value	val interface{}
	// Expiry time	expireTime 
	//Efficient time	expire 
	//value size	size int64
}

func NewMemCache() Cache {
	mc := &MemCache{
		clearExpireTime:  * 10,
		values:          make(map[string]*memCacheValue),
	}
	go ()
	return mc
}

// SetMemory size 1KB 100KB 1M 2M 1GB
func (mc *MemCache) SetMemory(size string) bool {
	,  = ParseSize(size)
	return true
}

// Set Set cachefunc (mc *MemCache) Set(key string, val interface{}, expire ) bool {
	()
	defer ()
	v := &memCacheValue{val: val, expireTime: ().Add(expire),
		expire: expire,
		size:   GetValSize(val)}
	//[key] = v
	(key)
	(key, v)
	if  >  {
		(key)
		panic(("max memory size %d", ))
	}
	return true
}

func (mc *MemCache) get(key string) (*memCacheValue, bool) {
	val, ok := [key]
	return val, ok
}

func (mc *MemCache) del(key string) {
	tmp, ok := (key)
	if ok && tmp != nil {
		 -= 
		delete(, key)
	}
}

func (mc *MemCache) add(key string, val *memCacheValue) {
	[key] = val
	 += 
}

// Get get cached valuefunc (mc *MemCache) Get(key string) (interface{}, bool) {
	()
	defer ()
	mcv, ok := (key)
	if ok {
		if  != 0 && (()) {
			(key)
			return nil, false
		}
		return , ok
	}
	return nil, false
}

// Del delete cached valuefunc (mc *MemCache) Del(key string) bool {
	()
	defer ()
	(key)
	return true
}

func (mc *MemCache) Exists(key string) bool {
	()
	defer ()
	_, ok := (key)
	return ok
}

func (mc *MemCache) Flush() bool {
	()
	defer ()
	 = make(map[string]*memCacheValue, 0)
	 = 0
	return true
}

func (mc *MemCache) Keys() int64 {
	()
	defer ()
	return int64(len())
}

func (mc *MemCache) clearExpireItm() {
	ticker := ()
	defer ()
	for {
		select {
		case <-:
			for key, v := range  {
				if  != 0 && ().After() {
					()
					(key)
					()
				}
			}
		}
	}
}

//
//var Cache = NewMemCache()
//
//func Set(key string, val interface{}) bool {
//
//	return false
//}

Tools

package cache

import (
	"log"
	"regexp"
	"strconv"
	"strings"
)

const (
	B = 1 << (iota * 10)
	KB
	MB
	GB
	TB
	PB
)

func ParseSize(size string) (int64, string) {

	//The default size is 100M	re, _ := ("[0-9]+")
	unit := string(([]byte(size), []byte("")))
	num, _ := ((size, unit, "", 1), 10, 64)
	unit = (unit)
	var byteNum int64 = 0
	switch unit {
	case "B":
		byteNum = num
		break
	case "KB":
		byteNum = num * KB
		break
	case "MB":
		byteNum = num * MB
		break
	case "GB":
		byteNum = num * GB
		break
	case "TB":
		byteNum = num * TB
		break
	case "PB":
		byteNum = num * PB
		break
	default:
		num = 0
		byteNum = 0

	}
	if num == 0 {
		("ParseSize only supports B, KB, MB, GB, TB, PB")
		num = 100 * MB
		byteNum = num
		unit = "MB"
	}
	sizeStr := (num, 10) + unit
	return byteNum, sizeStr

}

func GetValSize(val interface{}) int64 {
	return 0
}

Agent class

package server

import (
	"go_lang_pro/cache"
	"time"
)

type cacheServer struct {
	memCache 
}

func NewMemoryCache() *cacheServer {
	return &cacheServer{
		memCache: (),
	}
}

func (cs *cacheServer) SetMemory(size string) bool {
	return (size)
}

func (cs *cacheServer) Set(key string, val interface{}, expire ...) bool {
	expirets :=  * 0
	if len(expire) > 0 {
		expirets = expire[0]
	}
	return (key, val, expirets)
}

func (cs *cacheServer) Get(key string) (interface{}, bool) {
	return (key)
}
func (cs *cacheServer) Del(key string) bool {
	return (key)
}

func (cs *cacheServer) Exists(key string) bool {
	return (key)
}

func (cs *cacheServer) Flush() bool {
	return ()
}

func (cs *cacheServer) Keys() int64 {
	return ()
}

main method

package main

import (
	"go_lang_pro/cache"
	"time"
)

func main() {

	cache := ()
	("100MB")
	("int", 1, )
	("bool", false, )
	("data", map[string]interface{}{"a": 1}, )
	("int")
	("int")
	()
	()

}

This is the end of this article about the example code of go to implement a memory cache system. For more related go to the memory cache system content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!