2024-01-22 17:22:41: merge [master:56d3e06e49d7a75f142424293788a4f3b6245430];
This commit is contained in:
1 parent
7014f56cbb
commit
2b91caece0
60 files changed
+3558
No files matched your search
Vendored
+53
@@ -0,0 +1,53 @@
|
||||
package cache
|
||||
|
||||
import (
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Item struct {
|
||||
data []byte
|
||||
expiredAt time.Time
|
||||
}
|
||||
|
||||
type Cache struct {
|
||||
store map[string]Item
|
||||
lock *sync.RWMutex
|
||||
}
|
||||
|
||||
func New() *Cache {
|
||||
return &Cache{
|
||||
store: map[string]Item{},
|
||||
lock: &sync.RWMutex{},
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Cache) Get(key string) ([]byte, bool) {
|
||||
c.lock.RLock()
|
||||
defer c.lock.RUnlock()
|
||||
|
||||
item, ok := c.store[key]
|
||||
if !ok {
|
||||
return nil, false
|
||||
}
|
||||
|
||||
if c.now().After(item.expiredAt) {
|
||||
return nil, false
|
||||
}
|
||||
|
||||
return item.data, true
|
||||
}
|
||||
|
||||
func (c *Cache) Set(key string, data []byte, lifeTime time.Duration) {
|
||||
c.lock.Lock()
|
||||
defer c.lock.Unlock()
|
||||
|
||||
c.store[key] = Item{
|
||||
data: data,
|
||||
expiredAt: c.now().Add(lifeTime),
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Cache) now() time.Time {
|
||||
return time.Now()
|
||||
}
|
||||
Reference in new issue
Block a user