Sobes.tech
Junior — Middle

Kas saaksite anda näite andmete vahemälu korraldamise lähenemisest süsteemis?

sobes.tech AI

Vastus AI-lt

Go keeles kasutatakse andmete vahemälu korraldamiseks sageli sisseehitatud andmestruktuure, näiteks map koos täiendava logiikaga vahemälu eluea (TTL) haldamiseks. Üks lihtne lähenemisviis on luua struktuur, mis salvestab andmed ja nende loomise aja ning päringul kontrollib, kas andmed on aegunud.

Lihtne TTL-vahemälu näide:

package main

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

type cacheItem struct {
    value      interface{}
    expiration time.Time
}

type Cache struct {
    items map[string]cacheItem
    mu    sync.RWMutex
    ttl   time.Duration
}

func NewCache(ttl time.Duration) *Cache {
    return &Cache{
        items: make(map[string]cacheItem),
        ttl:   ttl,
    }
}

func (c *Cache) Set(key string, value interface{}) {
    c.mu.Lock()
    defer c.mu.Unlock()
    c.items[key] = cacheItem{
        value:      value,
        expiration: time.Now().Add(c.ttl),
    }
}

func (c *Cache) Get(key string) (interface{}, bool) {
    c.mu.RLock()
    defer c.mu.RUnlock()
    item, found := c.items[key]
    if !found || time.Now().After(item.expiration) {
        return nil, false
    }
    return item.value, true
}

func main() {
    cache := NewCache(5 * time.Minute)
    cache.Set("user_1", "John Doe")

    if val, ok := cache.Get("user_1"); ok {
        fmt.Println("Cached value:", val)
    } else {
        fmt.Println("Value not found or expired")
    }
}

Selline lähenemine sobib lihtsate juhtumite jaoks. Keerulisemate süsteemide jaoks kasutatakse spetsialiseeritud teeke või väliseid vahemälusid (nt Redis, Memcached).