-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmemory_cache.go
More file actions
50 lines (41 loc) · 1.15 KB
/
memory_cache.go
File metadata and controls
50 lines (41 loc) · 1.15 KB
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
package ratelimit
import (
"time"
"github.com/hashicorp/golang-lru/v2/expirable"
)
// MemoryCache implements the Cache interface using an in-memory LRU cache
type MemoryCache struct {
cache *expirable.LRU[uint64, *ClientLimiter]
}
// NewMemoryCache creates a new memory cache with the specified capacity and expiration
func NewMemoryCache(capacity int, expiration time.Duration) *MemoryCache {
cache := expirable.NewLRU[uint64, *ClientLimiter](capacity, nil, expiration)
return &MemoryCache{
cache: cache,
}
}
// Get retrieves a value from the cache
func (m *MemoryCache) Get(key uint64) *ClientLimiter {
value, found := m.cache.Get(key)
if !found {
return nil
}
return value
}
// Set stores a value in the cache
func (m *MemoryCache) Set(key uint64, value *ClientLimiter) {
m.cache.Add(key, value)
}
// Delete removes a value from the cache
func (m *MemoryCache) Delete(key uint64) {
m.cache.Remove(key)
}
// Clear removes all entries from the cache
func (m *MemoryCache) Clear() {
m.cache.Purge()
}
// Close cleans up any resources used by the cache
func (m *MemoryCache) Close() error {
// Memory cache doesn't need explicit cleanup
return nil
}