golang LRU算法

package main

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

type LRUCache struct {
	Caches map[string]NodeCache
	sync.Mutex
}

type NodeCache struct {
	Obj     interface{}
	DieTime time.Time
}

func NewLRUCache() *LRUCache {
	return &LRUCache{
		Caches: make(map[string]NodeCache),
		Mutex:  sync.Mutex{},
	}
}

func (l *LRUCache) Put(key string, obj interface{}, t time.Duration) error {
	l.Lock()
	defer l.Unlock()
	n := NodeCache{
		Obj:     obj,
		DieTime: time.Now().Add(t),
	}
	l.Caches[key] = n
	return nil
}

func (l *LRUCache) Get(key string) interface{} {
	l.Lock()
	defer l.Unlock()
	if v, ok := l.Caches[key]; ok {
		if v.DieTime.After(time.Now()) {
			return v
		}
		delete(l.Caches, key)
	}
	return nil
}

func main() {
	lru := NewLRUCache()
	err := lru.Put("name", "xiaoxiao", 100)
	if err != nil {
		log.Fatal(err)
	}
	name := lru.Get("name")
	fmt.Println(name)
}

posted @ 2021-03-29 23:02  A毛毛  阅读(150)  评论(0编辑  收藏  举报