-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path02_cache_response.go
74 lines (62 loc) · 1.34 KB
/
02_cache_response.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package main
import (
"fmt"
"sync"
"time"
)
type CacheItem struct {
Value interface{}
Expiration int64
}
type Cache struct {
store map[string]CacheItem
rwMu sync.RWMutex
}
func NewCache() *Cache {
return &Cache{
store: make(map[string]CacheItem),
}
}
// Set adds an item to the cache with a TTL (Time To Live).
func (c *Cache) Set(key string, value interface{}, ttl time.Duration) {
c.rwMu.Lock()
defer c.rwMu.Unlock()
expiration := time.Now().Add(ttl).UnixNano()
c.store[key] = CacheItem{
Value: value,
Expiration: expiration,
}
}
// Get retrieves an item from the cache.
func (c *Cache) Get(key string) (interface{}, bool) {
c.rwMu.RLock()
defer c.rwMu.RUnlock()
item, ok := c.store[key]
if !ok {
return nil, false
}
if time.Now().UnixNano() > item.Expiration {
return nil, false
}
return item.Value, true
}
func multipleGoroutinesReadingCache() {
cache := NewCache()
key := "news_123"
cache.Set(key, "Breaking News: DarkVard comeback!", time.Nanosecond)
var wg sync.WaitGroup
for i := 0; i < 5; i++ {
wg.Add(1)
go func(id int) {
defer wg.Done()
fmt.Printf("Goroutine %d fetching news...\n", i)
news, found := cache.Get(key)
if found {
fmt.Printf("Goroutine %d fetched: %v\n", i, news)
} else {
fmt.Printf("Goroutine %d: News not found or expired\n", i)
}
}(i)
}
wg.Wait()
}