Sobes.tech
Senior

// Գրեք cache-ի իրականացմանը TTL (ապահովության ժամկետ) համար User կառուցվածքի համար։ // Կարող եք օգտագործել User.ID որպես բանալի // Մենք ուզում ենք, որ դա լինի թրեդ-անվտանգ // Մենք չենք ուզում ստանալ գրառումներ, որոնց TTL-ն սպառվել է ընթերցման ժամանակ // Մենք ուզում ենք, որ սպառված TTL-ով գրառումները ջնջվեն և չպահվեն // API get/set/del

sobes.tech AI

Պատասխան AI-ից

go package main

import ( "sync" "time" )

type User struct { ID string // այլ դաշտեր }

type cacheItem struct { user User expiresAt time.Time }

type UserCache struct { mu sync.RWMutex items map[string]cacheItem }

func NewUserCache() *UserCache { c := &UserCache{ items: make(map[string]cacheItem), } // Սկսում ենք գորուտին՝ ժամանակավոր մաքրելու համար go func() { for { time.Sleep(time.Minute) // մաքրության միջակայք c.cleanup() } }() return c }

func (c *UserCache) Set(user User, ttl time.Duration) { c.mu.Lock() defer c.mu.Unlock() c.items[user.ID] = cacheItem{ user: user, expiresAt: time.Now().Add(ttl), } }

func (c *UserCache) Get(id string) (User, bool) { c.mu.RLock() item, found := c.items[id] c.mu.RUnlock() if !found { return User{}, false } if time.Now().After(item.expiresAt) { // ժամկետանց գրառում, հեռացնել c.mu.Lock() delete(c.items, id) c.mu.Unlock() return User{}, false } return item.user, true }

func (c *UserCache) Del(id string) { c.mu.Lock() defer c.mu.Unlock() delete(c.items, id) }

func (c *UserCache) cleanup() { c.mu.Lock() defer c.mu.Unlock() now := time.Now() for id, item := range c.items { if now.After(item.expiresAt) { delete(c.items, id) } } }

// Օգտագործման օրինակ // func main() { // cache := NewUserCache() // user := User{ID: "123"} // cache.Set(user, 5*time.Minute) // u, ok := cache.Get("123") // if ok { // fmt.Println("գտնվեց օգտատեր:", u) // } // }