当前位置: 首页>编程语言>正文

【Golang】golang实现简单memcache

如果有使用内存存一些简单数据的功能,可以实现下面这样的带有过期时间的内存类

内存中存储key-value,并且可以设置过期时间

package tools

import (
"sync"
"time"
)

// Memory struct contains *memcache.Client
type Memory struct {
sync.Mutex

data map[string]*data
}

type data struct {
Data interface{}
Expired time.Time
}

// NewMemory create new memcache
func NewMemory() *Memory {
return &Memory{
data: map[string]*data{},
}
}

// Get return cached value
func (mem *Memory) Get(key string) interface{} {
if ret, ok := mem.data[key]; ok {
if ret.Expired.Before(time.Now()) {
mem.deleteKey(key)
return nil
}
return ret.Data
}
return nil
}

// IsExist check value exists in memcache.
func (mem *Memory) IsExist(key string) bool {
if ret, ok := mem.data[key]; ok {
if ret.Expired.Before(time.Now()) {
mem.deleteKey(key)
return false
}
return true
}
return false
}

// Set cached value with key and expire time.
func (mem *Memory) Set(key string, val interface{}, timeout time.Duration) (err error) {
mem.Lock()
defer mem.Unlock()

mem.data[key] = &data{
Data: val,
Expired: time.Now().Add(timeout),
}
return nil
}

// Delete delete value in memcache.
func (mem *Memory) Delete(key string) error {
mem.deleteKey(key)
return nil
}

// deleteKey
func (mem *Memory) deleteKey(key string) {
mem.Lock()
defer mem.Unlock()
delete(mem.data, key)
}

// clean all data
func (mem *Memory) Clean() {
mem.Lock()
defer mem.Unlock()
mem.data = map[string]*data{}
}

使用方法

NewMemory()
mem.Set("name", "livechat", time.Duration(10)*time.Second)
time.Sleep(time.Duration(2) * time.Second)

name := mem.Get("name")

 

开源作品

github地址:​​go-fly​​


https://www.xamrdz.com/lan/5r61967372.html

相关文章: