/
batch_cache.go
114 lines (91 loc) · 2.23 KB
/
batch_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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
package appx
import (
"appengine/memcache"
"encoding/json"
"github.com/drborges/rivers/stream"
)
type MemcacheSaveBatch struct {
Size int
Items []*memcache.Item
}
func (batch *MemcacheSaveBatch) Full() bool {
return len(batch.Items) == batch.Size
}
func (batch *MemcacheSaveBatch) Empty() bool {
return len(batch.Items) == 0
}
func (batch *MemcacheSaveBatch) Add(data stream.T) {
entity := data.(Entity)
cacheable := data.(Cacheable)
cachedEntity := &CachedEntity{
Entity: entity,
Key: entity.Key(),
}
jsonCachedEntity, err := json.Marshal(cachedEntity)
if err != nil {
panic(err)
}
batch.Items = append(batch.Items, &memcache.Item{
Key: cacheable.CacheID(),
Value: jsonCachedEntity,
})
}
func (batch *MemcacheSaveBatch) Commit(emitter stream.Emitter) {
emitter.Emit(&MemcacheSaveBatch{
Size: batch.Size,
Items: batch.Items,
})
batch.Items = []*memcache.Item{}
}
type MemcacheLoadBatch struct {
Size int
Keys []string
Items map[string]*CachedEntity
}
func (batch *MemcacheLoadBatch) Full() bool {
return len(batch.Keys) == batch.Size
}
func (batch *MemcacheLoadBatch) Empty() bool {
return len(batch.Keys) == 0
}
func (batch *MemcacheLoadBatch) Add(data stream.T) {
entity := data.(Entity)
cacheable := data.(Cacheable)
if batch.Items == nil {
batch.Items = make(map[string]*CachedEntity)
}
batch.Keys = append(batch.Keys, cacheable.CacheID())
batch.Items[cacheable.CacheID()] = &CachedEntity{
Entity: entity,
}
}
func (batch *MemcacheLoadBatch) Commit(emitter stream.Emitter) {
emitter.Emit(&MemcacheLoadBatch{
Size: batch.Size,
Keys: batch.Keys,
Items: batch.Items,
})
batch.Keys = []string{}
batch.Items = make(map[string]*CachedEntity)
}
type MemcacheDeleteBatch struct {
Size int
Keys []string
}
func (batch *MemcacheDeleteBatch) Full() bool {
return len(batch.Keys) == batch.Size
}
func (batch *MemcacheDeleteBatch) Empty() bool {
return len(batch.Keys) == 0
}
func (batch *MemcacheDeleteBatch) Add(data stream.T) {
cacheable := data.(Cacheable)
batch.Keys = append(batch.Keys, cacheable.CacheID())
}
func (batch *MemcacheDeleteBatch) Commit(emitter stream.Emitter) {
emitter.Emit(&MemcacheDeleteBatch{
Size: batch.Size,
Keys: batch.Keys,
})
batch.Keys = []string{}
}