Debian Codegraph @

README.md

raw symbols SCIP
1 # gocache
2 ![test](https://github.com/TwiN/gocache/workflows/test/badge.svg?branch=master)
3 [![Go Report Card](https://goreportcard.com/badge/github.com/TwiN/gocache)](https://goreportcard.com/report/github.com/TwiN/gocache)
4 [![codecov](https://codecov.io/gh/TwiN/gocache/branch/master/graph/badge.svg)](https://codecov.io/gh/TwiN/gocache)
5 [![Go version](https://img.shields.io/github/go-mod/go-version/TwiN/gocache.svg)](https://github.com/TwiN/gocache)
6 [![Go Reference](https://pkg.go.dev/badge/github.com/TwiN/gocache.svg)](https://pkg.go.dev/github.com/TwiN/gocache/v2)
7 [![Follow TwiN](https://img.shields.io/github/followers/TwiN?label=Follow&style=social)](https://github.com/TwiN)
8
9 gocache is an easy-to-use, high-performance, lightweight and thread-safe (goroutine-safe) in-memory key-value cache
10 with support for LRU and FIFO eviction policies as well as expiration, bulk operations and even retrieval of keys by pattern.
11
12
13 ## Table of Contents
14
15 - [Features](#features)
16 - [Usage](#usage)
17 - [Initializing the cache](#initializing-the-cache)
18 - [Functions](#functions)
19 - [Examples](#examples)
20 - [Creating or updating an entry](#creating-or-updating-an-entry)
21 - [Getting an entry](#getting-an-entry)
22 - [Deleting an entry](#deleting-an-entry)
23 - [Complex example](#complex-example)
24 - [Persistence](#persistence)
25 - [Eviction](#eviction)
26 - [MaxSize](#maxsize)
27 - [MaxMemoryUsage](#maxmemoryusage)
28 - [Expiration](#expiration)
29 - [Performance](#performance)
30 - [Summary](#summary)
31 - [Results](#results)
32 - [FAQ](#faq)
33 - [How can I persist the data on application termination?](#how-can-i-persist-the-data-on-application-termination)
34
35
36 ## Features
37 gocache supports the following cache eviction policies:
38 - First in first out (FIFO)
39 - Least recently used (LRU)
40
41 It also supports cache entry TTL, which is both active and passive. Active expiration means that if you attempt
42 to retrieve a cache key that has already expired, it will delete it on the spot and the behavior will be as if
43 the cache key didn't exist. As for passive expiration, there's a background task that will take care of deleting
44 expired keys.
45
46 It also includes what you'd expect from a cache, like GET/SET, bulk operations and get by pattern.
47
48
49 ## Usage
50 ```
51 go get -u github.com/TwiN/gocache/v2
52 ```
53
54
55 ### Initializing the cache
56 ```go
57 cache := gocache.NewCache().WithMaxSize(1000).WithEvictionPolicy(gocache.LeastRecentlyUsed)
58 ```
59
60 If you're planning on using expiration (`SetWithTTL` or `Expire`) and you want expired entries to be automatically deleted
61 in the background, make sure to start the janitor when you instantiate the cache:
62
63 ```go
64 cache.StartJanitor()
65 ```
66
67 ### Functions
68 | Function | Description |
69 |-----------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
70 | WithMaxSize | Sets the max size of the cache. `gocache.NoMaxSize` means there is no limit. If not set, the default max size is `gocache.DefaultMaxSize`. |
71 | WithMaxMemoryUsage | Sets the max memory usage of the cache. `gocache.NoMaxMemoryUsage` means there is no limit. The default behavior is to not evict based on memory usage. |
72 | WithEvictionPolicy | Sets the eviction algorithm to be used when the cache reaches the max size. If not set, the default eviction policy is `gocache.FirstInFirstOut` (FIFO). |
73 | WithDefaultTTL | Sets the default TTL for each entry. |
74 | WithForceNilInterfaceOnNilPointer | Configures whether values with a nil pointer passed to write functions should be forcefully set to nil. Defaults to true. |
75 | StartJanitor | Starts the janitor, which is in charge of deleting expired cache entries in the background. |
76 | StopJanitor | Stops the janitor. |
77 | Set | Same as `SetWithTTL`, but using the default TTL (which is `gocache.NoExpiration`, unless configured otherwise). |
78 | SetWithTTL | Creates or updates a cache entry with the given key, value and expiration time. If the max size after the aforementioned operation is above the configured max size, the tail will be evicted. Depending on the eviction policy, the tail is defined as the oldest |
79 | SetAll | Same as `Set`, but in bulk. |
80 | SetAllWithTTL | Same as `SetWithTTL`, but in bulk. |
81 | Get | Gets a cache entry by its key. |
82 | GetByKeys | Gets a map of entries by their keys. The resulting map will contain all keys, even if some of the keys in the slice passed as parameter were not present in the cache. |
83 | GetAll | Gets all cache entries. |
84 | GetKeysByPattern | Retrieves a slice of keys that matches a given pattern. |
85 | Delete | Removes a key from the cache. |
86 | DeleteAll | Removes multiple keys from the cache. |
87 | DeleteKeysByPattern | Removes all keys that that matches a given pattern. |
88 | Count | Gets the size of the cache. This includes cache keys which may have already expired, but have not been removed yet. |
89 | Clear | Wipes the cache. |
90 | TTL | Gets the time until a cache key expires. |
91 | Expire | Sets the expiration time of an existing cache key. |
92
93 For further documentation, please refer to [Go Reference](https://pkg.go.dev/github.com/TwiN/gocache)
94
95
96 ### Examples
97
98 #### Creating or updating an entry
99 ```go
100 cache.Set("key", "value")
101 cache.Set("key", 1)
102 cache.Set("key", struct{ Text string }{Test: "value"})
103 cache.SetWithTTL("key", []byte("value"), 24*time.Hour)
104 ```
105
106 #### Getting an entry
107 ```go
108 value, exists := cache.Get("key")
109 ```
110 You can also get multiple entries by using `cache.GetByKeys([]string{"key1", "key2"})`
111
112 #### Deleting an entry
113 ```go
114 cache.Delete("key")
115 ```
116 You can also delete multiple entries by using `cache.DeleteAll([]string{"key1", "key2"})`
117
118 #### Complex example
119 ```go
120 package main
121
122 import (
123 "fmt"
124 "time"
125
126 "github.com/TwiN/gocache/v2"
127 )
128
129 func main() {
130 cache := gocache.NewCache().WithEvictionPolicy(gocache.LeastRecentlyUsed).WithMaxSize(10000)
131 cache.StartJanitor() // Passively manages expired entries
132 defer cache.StopJanitor()
133
134 cache.Set("key", "value")
135 cache.SetWithTTL("key-with-ttl", "value", 60*time.Minute)
136 cache.SetAll(map[string]any{"k1": "v1", "k2": "v2", "k3": "v3"})
137
138 fmt.Println("[Count] Cache size:", cache.Count())
139
140 value, exists := cache.Get("key")
141 fmt.Printf("[Get] key=key; value=%s; exists=%v\n", value, exists)
142 for key, value := range cache.GetByKeys([]string{"k1", "k2", "k3"}) {
143 fmt.Printf("[GetByKeys] key=%s; value=%s\n", key, value)
144 }
145 for _, key := range cache.GetKeysByPattern("key*", 0) {
146 fmt.Printf("[GetKeysByPattern] pattern=key*; key=%s\n", key)
147 }
148
149 cache.Expire("key", time.Hour)
150 time.Sleep(500*time.Millisecond)
151 timeUntilExpiration, _ := cache.TTL("key")
152 fmt.Println("[TTL] Number of minutes before 'key' expires:", int(timeUntilExpiration.Seconds()))
153
154 cache.Delete("key")
155 cache.DeleteAll([]string{"k1", "k2", "k3"})
156
157 cache.Clear()
158 fmt.Println("[Count] Cache size after clearing the cache:", cache.Count())
159 }
160 ```
161
162 <details>
163 <summary>Output</summary>
164
165 ```
166 [Count] Cache size: 5
167 [Get] key=key; value=value; exists=true
168 [GetByKeys] key=k1; value=v1
169 [GetByKeys] key=k2; value=v2
170 [GetByKeys] key=k3; value=v3
171 [GetKeysByPattern] pattern=key*; key=key-with-ttl
172 [GetKeysByPattern] pattern=key*; key=key
173 [TTL] Number of minutes before 'key' expires: 3599
174 [Count] Cache size after clearing the cache: 0
175 ```
176 </details>
177
178
179 ## Persistence
180 Prior to v2, gocache supported persistence out of the box.
181
182 After some thinking, I decided that persistence added too many dependencies, and given than this is a cache library
183 and most people wouldn't be interested in persistence, I decided to get rid of it.
184
185 That being said, you can use the `GetAll` and `SetAll` methods of `gocache.Cache` to implement persistence yourself.
186
187
188 ## Eviction
189 ### MaxSize
190 Eviction by MaxSize is the default behavior, and is also the most efficient.
191
192 The code below will create a cache that has a maximum size of 1000:
193 ```go
194 cache := gocache.NewCache().WithMaxSize(1000)
195 ```
196 This means that whenever an operation causes the total size of the cache to go above 1000, the tail will be evicted.
197
198 ### MaxMemoryUsage
199 Eviction by MaxMemoryUsage is **disabled by default**, and is in alpha.
200
201 The code below will create a cache that has a maximum memory usage of 50MB:
202 ```go
203 cache := gocache.NewCache().WithMaxSize(0).WithMaxMemoryUsage(50*gocache.Megabyte)
204 ```
205 This means that whenever an operation causes the total memory usage of the cache to go above 50MB, one or more tails
206 will be evicted.
207
208 Unlike evictions caused by reaching the MaxSize, evictions triggered by MaxMemoryUsage may lead to multiple entries
209 being evicted in a row. The reason for this is that if, for instance, you had 100 entries of 0.1MB each and you suddenly added
210 a single entry of 10MB, 100 entries would need to be evicted to make enough space for that new big entry.
211
212 It's very important to keep in mind that eviction by MaxMemoryUsage is approximate.
213
214 **The only memory taken into consideration is the size of the cache, not the size of the entire application.**
215 If you pass along 100MB worth of data in a matter of seconds, even though the cache's memory usage will remain
216 under 50MB (or whatever you configure the MaxMemoryUsage to), the memory footprint generated by that 100MB will
217 still exist until the next GC cycle.
218
219 As previously mentioned, this is a work in progress, and here's a list of the things you should keep in mind:
220 - The memory usage of structs are a gross estimation and may not reflect the actual memory usage.
221 - Native types (string, int, bool, []byte, etc.) are the most accurate for calculating the memory usage.
222 - Adding an entry bigger than the configured MaxMemoryUsage will work, but it will evict all other entries.
223
224
225 ## Expiration
226 There are two ways that the deletion of expired keys can take place:
227 - Active
228 - Passive
229
230 **Active deletion of expired keys** happens when an attempt is made to access the value of a cache entry that expired.
231 `Get`, `GetByKeys` and `GetAll` are the only functions that can trigger active deletion of expired keys.
232
233 **Passive deletion of expired keys** runs in the background and is managed by the janitor.
234 If you do not start the janitor, there will be no passive deletion of expired keys.
235
236
237 ## Performance
238 ### Summary
239 - **Set**: Both map and gocache have the same performance.
240 - **Get**: Map is faster than gocache.
241
242 This is because gocache keeps track of the head and the tail for eviction and expiration/TTL.
243
244 Ultimately, the difference is negligible.
245
246 We could add a way to disable eviction or disable expiration altogether just to match the map's performance,
247 but if you're looking into using a library like gocache, odds are, you want more than just a map.
248
249
250 ### Results
251 | key | value |
252 |:-------|:---------|
253 | goos | windows |
254 | goarch | amd64 |
255 | cpu | i7-9700K |
256 | mem | 32G DDR4 |
257
258 ```
259 // Normal map
260 BenchmarkMap_Get-8 49944228 24.2 ns/op 7 B/op 0 allocs/op
261 BenchmarkMap_Set/small_value-8 3939964 394.1 ns/op 188 B/op 2 allocs/op
262 BenchmarkMap_Set/medium_value-8 3868586 395.5 ns/op 191 B/op 2 allocs/op
263 BenchmarkMap_Set/large_value-8 3992138 385.3 ns/op 186 B/op 2 allocs/op
264 // Gocache
265 BenchmarkCache_Get/FirstInFirstOut-8 27907950 44.3 ns/op 7 B/op 0 allocs/op
266 BenchmarkCache_Get/LeastRecentlyUsed-8 28211396 44.2 ns/op 7 B/op 0 allocs/op
267 BenchmarkCache_Set/FirstInFirstOut_small_value-8 3139538 373.5 ns/op 185 B/op 3 allocs/op
268 BenchmarkCache_Set/FirstInFirstOut_medium_value-8 3099516 378.6 ns/op 186 B/op 3 allocs/op
269 BenchmarkCache_Set/FirstInFirstOut_large_value-8 3086776 386.7 ns/op 186 B/op 3 allocs/op
270 BenchmarkCache_Set/LeastRecentlyUsed_small_value-8 3070555 379.0 ns/op 187 B/op 3 allocs/op
271 BenchmarkCache_Set/LeastRecentlyUsed_medium_value-8 3056928 383.8 ns/op 187 B/op 3 allocs/op
272 BenchmarkCache_Set/LeastRecentlyUsed_large_value-8 3108250 383.8 ns/op 186 B/op 3 allocs/op
273 BenchmarkCache_SetUsingMaxMemoryUsage/medium_value-8 2773315 449.0 ns/op 210 B/op 4 allocs/op
274 BenchmarkCache_SetUsingMaxMemoryUsage/large_value-8 2731818 440.0 ns/op 211 B/op 4 allocs/op
275 BenchmarkCache_SetUsingMaxMemoryUsage/small_value-8 2659296 446.8 ns/op 213 B/op 4 allocs/op
276 BenchmarkCache_SetWithMaxSize/100_small_value-8 4848658 248.8 ns/op 114 B/op 3 allocs/op
277 BenchmarkCache_SetWithMaxSize/10000_small_value-8 4117632 293.7 ns/op 106 B/op 3 allocs/op
278 BenchmarkCache_SetWithMaxSize/100000_small_value-8 3867402 313.0 ns/op 110 B/op 3 allocs/op
279 BenchmarkCache_SetWithMaxSize/100_medium_value-8 4750057 250.1 ns/op 113 B/op 3 allocs/op
280 BenchmarkCache_SetWithMaxSize/10000_medium_value-8 4143772 294.5 ns/op 106 B/op 3 allocs/op
281 BenchmarkCache_SetWithMaxSize/100000_medium_value-8 3768883 313.2 ns/op 111 B/op 3 allocs/op
282 BenchmarkCache_SetWithMaxSize/100_large_value-8 4822646 251.1 ns/op 114 B/op 3 allocs/op
283 BenchmarkCache_SetWithMaxSize/10000_large_value-8 4154428 291.6 ns/op 106 B/op 3 allocs/op
284 BenchmarkCache_SetWithMaxSize/100000_large_value-8 3897358 313.7 ns/op 110 B/op 3 allocs/op
285 BenchmarkCache_SetWithMaxSizeAndLRU/100_small_value-8 4784180 254.2 ns/op 114 B/op 3 allocs/op
286 BenchmarkCache_SetWithMaxSizeAndLRU/10000_small_value-8 4067042 292.0 ns/op 106 B/op 3 allocs/op
287 BenchmarkCache_SetWithMaxSizeAndLRU/100000_small_value-8 3832760 313.8 ns/op 111 B/op 3 allocs/op
288 BenchmarkCache_SetWithMaxSizeAndLRU/100_medium_value-8 4846706 252.2 ns/op 114 B/op 3 allocs/op
289 BenchmarkCache_SetWithMaxSizeAndLRU/10000_medium_value-8 4103817 292.5 ns/op 106 B/op 3 allocs/op
290 BenchmarkCache_SetWithMaxSizeAndLRU/100000_medium_value-8 3845623 315.1 ns/op 111 B/op 3 allocs/op
291 BenchmarkCache_SetWithMaxSizeAndLRU/100_large_value-8 4744513 257.9 ns/op 114 B/op 3 allocs/op
292 BenchmarkCache_SetWithMaxSizeAndLRU/10000_large_value-8 3956316 299.5 ns/op 106 B/op 3 allocs/op
293 BenchmarkCache_SetWithMaxSizeAndLRU/100000_large_value-8 3876843 351.3 ns/op 110 B/op 3 allocs/op
294 BenchmarkCache_GetSetMultipleConcurrent-8 750088 1566.0 ns/op 128 B/op 8 allocs/op
295 BenchmarkCache_GetSetConcurrentWithFrequentEviction/FirstInFirstOut-8 3836961 316.2 ns/op 80 B/op 1 allocs/op
296 BenchmarkCache_GetSetConcurrentWithFrequentEviction/LeastRecentlyUsed-8 3846165 315.6 ns/op 80 B/op 1 allocs/op
297 BenchmarkCache_GetConcurrently/FirstInFirstOut-8 4830342 239.8 ns/op 8 B/op 1 allocs/op
298 BenchmarkCache_GetConcurrently/LeastRecentlyUsed-8 4895587 243.2 ns/op 8 B/op 1 allocs/op
299 (Trimmed "BenchmarkCache_" for readability)
300 WithForceNilInterfaceOnNilPointer/true_with_nil_struct_pointer-8 6901461 178.5 ns/op 7 B/op 1 allocs/op
301 WithForceNilInterfaceOnNilPointer/true-8 6629566 180.7 ns/op 7 B/op 1 allocs/op
302 WithForceNilInterfaceOnNilPointer/false_with_nil_struct_pointer-8 6282798 170.1 ns/op 7 B/op 1 allocs/op
303 WithForceNilInterfaceOnNilPointer/false-8 6741382 172.6 ns/op 7 B/op 1 allocs/op
304 WithForceNilInterfaceOnNilPointerWithConcurrency/true_with_nil_struct_pointer-8 4432951 258.0 ns/op 8 B/op 1 allocs/op
305 WithForceNilInterfaceOnNilPointerWithConcurrency/true-8 4676943 244.4 ns/op 8 B/op 1 allocs/op
306 WithForceNilInterfaceOnNilPointerWithConcurrency/false_with_nil_struct_pointer-8 4818418 239.6 ns/op 8 B/op 1 allocs/op
307 WithForceNilInterfaceOnNilPointerWithConcurrency/false-8 5025937 238.2 ns/op 8 B/op 1 allocs/op
308 ```
309
310
311 ## FAQ
312
313 ### How can I persist the data on application termination?
314 While creating your own auto save feature might come in handy, it may still lead to loss of data if the application
315 automatically saves every 10 minutes and your application crashes 9 minutes after the previous save.
316
317 To increase your odds of not losing any data, you can use Go's `signal` package, more specifically its `Notify` function
318 which allows listening for termination signals like SIGTERM and SIGINT. Once a termination signal is caught, you can
319 add the necessary logic for a graceful shutdown.
320
321 In the following example, the code that would usually be present in the `main` function is moved to a different function
322 named `Start` which is launched on a different goroutine so that listening for a termination signals is what blocks the
323 main goroutine instead:
324 ```go
325 package main
326
327 import (
328 "log"
329 "os"
330 "os/signal"
331 "syscall"
332
333 "github.com/TwiN/gocache/v2"
334 )
335
336 var cache = gocache.NewCache()
337
338 func main() {
339 data := retrieveCacheEntriesUsingWhateverMeanYouUsedToPersistIt()
340 cache.SetAll(data)
341 // Start everything else on another goroutine to prevent blocking the main goroutine
342 go Start()
343 // Wait for termination signal
344 sig := make(chan os.Signal, 1)
345 done := make(chan bool, 1)
346 signal.Notify(sig, os.Interrupt, syscall.SIGTERM)
347 go func() {
348 <-sig
349 log.Println("Received termination signal, attempting to gracefully shut down")
350 // Persist the cache entries
351 cacheEntries := cache.GetAll()
352 persistCacheEntriesHoweverYouWant(cacheEntries)
353 // Tell the main goroutine that we're done
354 done <- true
355 }()
356 <-done
357 log.Println("Shutting down")
358 }
359 ```
360
361 Note that this won't protect you from a SIGKILL, as this signal cannot be caught.