Skip to content

Commit 0d500fd

Browse files
committed
update handle memory cleanup properly
1 parent c6653c7 commit 0d500fd

File tree

3 files changed

+13
-20
lines changed

3 files changed

+13
-20
lines changed

cache/cache.go

-10
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,6 @@ type Cache interface {
1616
setWithExpiry(key string, value []byte, expiry time.Duration) error
1717
get(key string) []byte
1818
delete(key string) error
19-
cleanUp()
2019
}
2120

2221
var conn Cache
@@ -32,7 +31,6 @@ func init() {
3231
panic("unknown cache driver")
3332
}
3433

35-
go conn.cleanUp()
3634
}
3735

3836
// Client ...
@@ -64,11 +62,3 @@ func Get[T any](key string) (T, error) {
6462
func Delete(key string) error {
6563
return conn.delete(key)
6664
}
67-
68-
// CleanUp ...
69-
func CleanUp() {
70-
tick := time.NewTicker(time.Second)
71-
for range tick.C {
72-
conn.cleanUp()
73-
}
74-
}

cache/memory.go

+13-6
Original file line numberDiff line numberDiff line change
@@ -17,11 +17,14 @@ type memoryCache struct {
1717
}
1818

1919
func newMemoryCache() Cache {
20-
return &memoryCache{
20+
c := &memoryCache{
2121
cacheWorkers: env.Int("CACHE_TOTAL_WORKERS", 10),
2222
items: make(map[string]cacheItem),
2323
mut: sync.Mutex{},
2424
}
25+
26+
go c.cleanUp()
27+
return c
2528
}
2629

2730
// getClient ...
@@ -77,11 +80,15 @@ func (m *memoryCache) delete(key string) error {
7780

7881
// cleanUp deletes expired cache items and calls their callbacks
7982
func (m *memoryCache) cleanUp() {
80-
m.mut.Lock()
81-
defer m.mut.Unlock()
82-
for key, item := range m.items {
83-
if item.expired() {
84-
delete(m.items, key)
83+
for {
84+
m.mut.Lock()
85+
for key, item := range m.items {
86+
if item.expired() {
87+
delete(m.items, key)
88+
}
8589
}
90+
91+
m.mut.Unlock()
92+
<-time.After(time.Second)
8693
}
8794
}

cache/redis.go

-4
Original file line numberDiff line numberDiff line change
@@ -78,7 +78,3 @@ func (r *redisCache) delete(key string) error {
7878

7979
return nil
8080
}
81-
82-
func (r *redisCache) cleanUp() {
83-
// TODO
84-
}

0 commit comments

Comments
 (0)