Skip to content
เข้าสู่ระบบ

Caching

Caching ช่วยลด latency และ load โดยเก็บข้อมูลที่ใช้บ่อยไว้ใกล้มือ

package main
import (
"fmt"
"sync"
"time"
)
type CacheItem struct {
Value interface{}
Expiration int64
}
type Cache struct {
items map[string]CacheItem
mu sync.RWMutex
}
func NewCache() *Cache {
c := &Cache{
items: make(map[string]CacheItem),
}
go c.cleanup()
return c
}
func (c *Cache) Set(key string, value interface{}, ttl time.Duration) {
c.mu.Lock()
defer c.mu.Unlock()
var expiration int64
if ttl > 0 {
expiration = time.Now().Add(ttl).UnixNano()
}
c.items[key] = CacheItem{
Value: value,
Expiration: expiration,
}
}
func (c *Cache) Get(key string) (interface{}, bool) {
c.mu.RLock()
defer c.mu.RUnlock()
item, found := c.items[key]
if !found {
return nil, false
}
// Check expiration
if item.Expiration > 0 && time.Now().UnixNano() > item.Expiration {
return nil, false
}
return item.Value, true
}
func (c *Cache) Delete(key string) {
c.mu.Lock()
defer c.mu.Unlock()
delete(c.items, key)
}
func (c *Cache) cleanup() {
ticker := time.NewTicker(1 * time.Minute)
for range ticker.C {
c.mu.Lock()
now := time.Now().UnixNano()
for key, item := range c.items {
if item.Expiration > 0 && now > item.Expiration {
delete(c.items, key)
}
}
c.mu.Unlock()
}
}
func main() {
cache := NewCache()
// Set with TTL
cache.Set("user:1", "John Doe", 5*time.Second)
// Get
if val, found := cache.Get("user:1"); found {
fmt.Println("Found:", val)
}
// Wait for expiration
time.Sleep(6 * time.Second)
if _, found := cache.Get("user:1"); !found {
fmt.Println("Expired!")
}
}

เข้าสู่ระบบเพื่อดูเนื้อหาเต็ม

ยืนยันตัวตนด้วยบัญชี Google เพื่อปลดล็อกบทความทั้งหมด