-
Notifications
You must be signed in to change notification settings - Fork 0
/
cache.go
77 lines (66 loc) · 1.35 KB
/
cache.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
75
76
77
package main
import (
"fmt"
"sync/atomic"
"time"
)
type Person struct {
name string
lastName string
age int
}
type readPeople struct {
resp chan []Person
}
var people []Person
var reads chan *readPeople
var cacheReads int64
var dbReads int64
var ops int64
func main() {
reads = make(chan *readPeople)
go getPeople()
//100 concurrent go routines getting people data
for p := 0; p < 100; p++ {
go func() {
for {
readP := &readPeople{
resp: make(chan []Person)}
reads <- readP
atomic.AddInt64(&ops, 1)
<-readP.resp
}
}()
}
//let the go routines read for a while
time.Sleep(time.Second)
opsFinal := atomic.LoadInt64(&ops)
dbReadsFinal := atomic.LoadInt64(&dbReads)
cacheReadsFinal := atomic.LoadInt64(&cacheReads)
fmt.Println("ops done: ", opsFinal)
fmt.Println("db reads: ", dbReadsFinal)
fmt.Println("cacheReads: ", cacheReadsFinal)
}
func getPeople() {
for {
read := <-reads
if len(people) == 0 {
//simulate reading from data base
time.Sleep(time.Millisecond * 20)
people = []Person{
Person{
name: "John",
lastName: "Snow",
age: 28},
Person{
name: "Cercie",
lastName: "Lannister",
age: 35}}
atomic.AddInt64(&dbReads, 1)
read.resp <- people
} else {
//data is cached atomic.AddInt64(&cacheReads, 1)
read.resp <- people
}
}
}