其他分享
首页 > 其他分享> > 【Golang】golang实现简单memcache

【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{}
}

使用方法

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

    name := mem.Get("name")

 

标签:golang,return,mem,Memory,Golang,memcache,key,time,data
来源: https://www.cnblogs.com/taoshihan/p/16504015.html