### Example: PUT and GET Cache Entry with cURL Source: https://github.com/allegro/bigcache/blob/main/server/README.md Demonstrates how to use cURL to PUT data into the cache and then GET it back. Shows request and response details for both operations. ```bash $ curl -v -XPUT localhost:9090/api/v1/cache/example -d "yay!" * Trying 127.0.0.1... * Connected to localhost (127.0.0.1) port 9090 (#0) > PUT /api/v1/cache/example HTTP/1.1 > Host: localhost:9090 > User-Agent: curl/7.47.0 > Accept: */* > Content-Length: 4 > Content-Type: application/x-www-form-urlencoded > * upload completely sent off: 4 out of 4 bytes < HTTP/1.1 201 Created < Date: Fri, 17 Nov 2017 03:50:07 GMT < Content-Length: 0 < Content-Type: text/plain; charset=utf-8 > * Connection #0 to host localhost left intact $ $ curl -v -XGET localhost:9090/api/v1/cache/example Note: Unnecessary use of -X or --request, GET is already inferred. * Trying 127.0.0.1... * Connected to localhost (127.0.0.1) port 9090 (#0) > GET /api/v1/cache/example HTTP/1.1 > Host: localhost:9090 > User-Agent: curl/7.47.0 > Accept: */* > < HTTP/1.1 200 OK < Date: Fri, 17 Nov 2017 03:50:23 GMT < Content-Length: 4 < Content-Type: text/plain; charset=utf-8 > * Connection #0 to host localhost left intact yay! ``` -------------------------------- ### BigCache HTTP Server Runtime Logs Source: https://github.com/allegro/bigcache/blob/main/server/README.md Example output of the BigCache HTTP Server's runtime logs. Shows initialization, server start, cache storage, and request processing times. ```bash $ ./server 2017/11/16 22:49:22 cache initialised. 2017/11/16 22:49:22 starting server on :9090 2017/11/16 22:50:07 stored "example" in cache. 2017/11/16 22:50:07 request took 277000ns. 2017/11/16 22:50:23 request took 9000ns. ``` -------------------------------- ### Start BigCache HTTP Server Source: https://context7.com/allegro/bigcache/llms.txt Launch the BigCache HTTP server using the provided command. Configure port, shards, entry lifetime, maximum cache size, and maximum shard entry size. ```bash # Start the server go run github.com/allegro/bigcache/v3/server \ -port 9090 \ -shards 1024 \ -lifetime 10m \ -max 8192 \ -maxShardEntrySize 500 ``` -------------------------------- ### Run BigCache Benchmarks Source: https://github.com/allegro/bigcache/blob/main/README.md Execute benchmark tests for BigCache and other implementations to measure performance. Ensure you are in the correct directory and have Go installed. ```bash go version go version go1.13 linux/amd64 go test -bench=. -benchmem -benchtime=4s ./... -timeout 30m goos: linux goarch: amd64 pkg: github.com/allegro/bigcache/v3/caches_bench BenchmarkMapSet-8 12999889 376 ns/op 199 B/op 3 allocs/op BenchmarkConcurrentMapSet-8 4355726 1275 ns/op 337 B/op 8 allocs/op BenchmarkFreeCacheSet-8 11068976 703 ns/op 328 B/op 2 allocs/op BenchmarkBigCacheSet-8 10183717 478 ns/op 304 B/op 2 allocs/op BenchmarkMapGet-8 16536015 324 ns/op 23 B/op 1 allocs/op BenchmarkConcurrentMapGet-8 13165708 401 ns/op 24 B/op 2 allocs/op BenchmarkFreeCacheGet-8 10137682 690 ns/op 136 B/op 2 allocs/op BenchmarkBigCacheGet-8 11423854 450 ns/op 152 B/op 4 allocs/op BenchmarkBigCacheSetParallel-8 34233472 148 ns/op 317 B/op 3 allocs/op BenchmarkFreeCacheSetParallel-8 34222654 268 ns/op 350 B/op 3 allocs/op BenchmarkConcurrentMapSetParallel-8 19635688 240 ns/op 200 B/op 6 allocs/op BenchmarkBigCacheGetParallel-8 60547064 86.1 ns/op 152 B/op 4 allocs/op BenchmarkFreeCacheGetParallel-8 50701280 147 ns/op 136 B/op 3 allocs/op BenchmarkConcurrentMapGetParallel-8 27353288 175 ns/op 24 B/op 2 allocs/op PASS ok github.com/allegro/bigcache/v3/caches_bench 256.257s ``` -------------------------------- ### Get Cache Size Information with Go Source: https://context7.com/allegro/bigcache/llms.txt Use `Len()` to get the total number of entries and `Capacity()` to get the total allocated bytes for cache storage. These methods provide insights into the cache's current size and memory usage. ```go package main import ( "context" "fmt" "time" "github.com/allegro/bigcache/v3" ) func main() { cache, _ := bigcache.New(context.Background(), bigcache.DefaultConfig(10*time.Minute)) defer cache.Close() fmt.Printf("Initial capacity: %d bytes\n", cache.Capacity()) fmt.Printf("Initial entries: %d\n", cache.Len()) // Add entries for i := 0; i < 1000; i++ { key := fmt.Sprintf("key:%d", i) value := fmt.Sprintf("value-%d-with-some-extra-data", i) cache.Set(key, []byte(value)) } fmt.Printf("Entries after population: %d\n", cache.Len()) fmt.Printf("Capacity after population: %d bytes\n", cache.Capacity()) // Output (approximate): // Initial capacity: 5120000 bytes // Initial entries: 0 // Entries after population: 1000 // Capacity after population: 5120000 bytes } ``` -------------------------------- ### Get - Retrieve Entry from Cache Source: https://context7.com/allegro/bigcache/llms.txt Retrieves the value associated with a key. Returns ErrEntryNotFound when the key doesn't exist. ```go package main import ( "context" "errors" "fmt" "log" "time" "github.com/allegro/bigcache/v3" ) func main() { cache, _ := bigcache.New(context.Background(), bigcache.DefaultConfig(10*time.Minute)) defer cache.Close() cache.Set("config:timeout", []byte("30")) // Successful retrieval entry, err := cache.Get("config:timeout") if err != nil { log.Fatal(err) } fmt.Printf("Timeout: %s seconds\n", string(entry)) // Output: Timeout: 30 seconds // Key not found _, err = cache.Get("nonexistent-key") if errors.Is(err, bigcache.ErrEntryNotFound) { fmt.Println("Key not found in cache") } // Output: Key not found in cache } ``` -------------------------------- ### Get Per-Key Access Statistics with Go Source: https://context7.com/allegro/bigcache/llms.txt Enable per-key statistics by setting `StatsEnabled` to `true` in the cache configuration. Use `KeyMetadata()` to retrieve statistics like request count for a specific key after it has been accessed. ```go package main import ( "context" "fmt" "time" "github.com/allegro/bigcache/v3" ) func main() { config := bigcache.DefaultConfig(10 * time.Minute) config.StatsEnabled = true // Enable per-key statistics cache, _ := bigcache.New(context.Background(), config) defer cache.Close() cache.Set("popular-key", []byte("frequently accessed data")) // Access the key multiple times cache.Get("popular-key") cache.Get("popular-key") cache.Get("popular-key") metadata := cache.KeyMetadata("popular-key") fmt.Printf("Request count for 'popular-key': %d\n", metadata.RequestCount) // Output: Request count for 'popular-key': 3 } ``` -------------------------------- ### Get - Retrieve Entry from Cache Source: https://context7.com/allegro/bigcache/llms.txt Retrieves the value associated with a key from the cache. Returns `ErrEntryNotFound` if the key does not exist. ```APIDOC ## GET /cache/{key} ### Description Retrieves the value associated with a specific key from the cache. ### Method GET ### Endpoint `/cache/{key}` ### Parameters #### Path Parameters - **key** (string) - Required - The key of the entry to retrieve. ### Response #### Success Response (200) - **value** ([]byte) - The data associated with the key. #### Error Response (404) - **error** (string) - `ErrEntryNotFound` if the key does not exist. ``` -------------------------------- ### Get Cache Statistics with Go Source: https://context7.com/allegro/bigcache/llms.txt Use the Stats method to retrieve cache statistics like hit/miss counts, delete operations, and hash collisions. Ensure cache operations are performed before calling Stats. ```go package main import ( "context" "fmt" "time" "github.com/allegro/bigcache/v3" ) func main() { cache, _ := bigcache.New(context.Background(), bigcache.DefaultConfig(10*time.Minute)) defer cache.Close() // Populate and access cache cache.Set("key1", []byte("value1")) cache.Set("key2", []byte("value2")) cache.Get("key1") // Hit cache.Get("key1") // Hit cache.Get("key2") // Hit cache.Get("nonexistent") // Miss cache.Get("missing") // Miss cache.Delete("key1") // Delete hit cache.Delete("notfound") // Delete miss stats := cache.Stats() fmt.Printf("Hits: %d\n", stats.Hits) fmt.Printf("Misses: %d\n", stats.Misses) fmt.Printf("Delete Hits: %d\n", stats.DelHits) fmt.Printf("Delete Misses: %d\n", stats.DelMisses) fmt.Printf("Collisions: %d\n", stats.Collisions) // Output: // Hits: 3 // Misses: 2 // Delete Hits: 1 // Delete Misses: 1 // Collisions: 0 } ``` -------------------------------- ### BigCache HTTP Server API Endpoints Source: https://github.com/allegro/bigcache/blob/main/server/README.md Defines the RESTful API endpoints for interacting with the BigCache HTTP Server. Supports GET, PUT, and DELETE for cache operations, and GET for statistics. ```bash # cache API. GET /api/v1/cache/{key} PUT /api/v1/cache/{key} DELETE /api/v1/cache/{key} # stats API. GET /api/v1/stats ``` -------------------------------- ### HTTP Server Cache Operations with cURL Source: https://context7.com/allegro/bigcache/llms.txt Interact with the BigCache HTTP server using cURL commands to perform PUT (store), GET (retrieve), DELETE, and CLEAR operations on cache entries. Also demonstrates retrieving cache statistics. ```bash # Store a value curl -X PUT -d "Hello, World!" http://localhost:9090/api/v1/cache/greeting # Response: 201 Created # Retrieve a value curl http://localhost:9090/api/v1/cache/greeting # Response: Hello, World! # Delete a value curl -X DELETE http://localhost:9090/api/v1/cache/greeting # Response: 200 OK # Get cache statistics curl http://localhost:9090/api/v1/stats # Response: {"hits":1,"misses":0,"delete_hits":1,"delete_misses":0,"collisions":0} # Clear all cache entries curl -X POST http://localhost:9090/api/v1/cache/clear # Response: 200 OK ``` -------------------------------- ### Creating a Cache Instance with Default Config Source: https://context7.com/allegro/bigcache/llms.txt Demonstrates how to create a new BigCache instance using default configurations and a specified entry lifetime. It also shows basic storage and retrieval of a key-value pair. ```APIDOC ## Creating a Cache Instance with Default Config ### Description The `New` function creates a new BigCache instance with context support for graceful shutdown. The `DefaultConfig` function returns a configuration with sensible defaults, accepting an eviction duration parameter that determines how long entries remain valid. ### Method `bigcache.New(context.Context, bigcache.Config) (*bigcache.BigCache, error)` ### Endpoint N/A (Library function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```go package main import ( "context" "fmt" "log" "time" "github.com/allegro/bigcache/v3" ) func main() { // Create cache with 10-minute entry lifetime cache, err := bigcache.New(context.Background(), bigcache.DefaultConfig(10*time.Minute)) if err != nil { log.Fatal(err) } defer cache.Close() // Store and retrieve a value err = cache.Set("user:123", []byte(`{"name":"John","email":"john@example.com"}`)) if err != nil { log.Fatal(err) } entry, err := cache.Get("user:123") if err != nil { log.Fatal(err) } fmt.Println(string(entry)) // Output: {"name":"John","email":"john@example.com"} } ``` ### Response #### Success Response (200) N/A (Library function, returns cache instance or error) #### Response Example N/A ``` -------------------------------- ### Initialize BigCache with Custom Configuration Source: https://github.com/allegro/bigcache/blob/main/README.md This snippet demonstrates custom initialization for BigCache, allowing fine-grained control over cache parameters such as Shards, LifeWindow, CleanWindow, MaxEntriesInWindow, MaxEntrySize, Verbose logging, HardMaxCacheSize, and callback functions for entry removal. It's recommended when cache load can be predicted to avoid unnecessary memory allocations. ```go import ( "context" "fmt" "log" "time" "github.com/allegro/bigcache/v3" ) config := bigcache.Config { // number of shards (must be a power of 2) Shards: 1024, // time after which entry can be evicted LifeWindow: 10 * time.Minute, // Interval between removing expired entries (clean up). // If set to <= 0 then no action is performed. // Setting to < 1 second is counterproductive — bigcache has a one second resolution. CleanWindow: 5 * time.Minute, // rps * lifeWindow, used only in initial memory allocation MaxEntriesInWindow: 1000 * 10 * 60, // max entry size in bytes, used only in initial memory allocation MaxEntrySize: 500, // prints information about additional memory allocation Verbose: true, // cache will not allocate more memory than this limit, value in MB // if value is reached then the oldest entries can be overridden for the new ones // 0 value means no size limit HardMaxCacheSize: 8192, // callback fired when the oldest entry is removed because of its expiration time or no space left // for the new entry, or because delete was called. A bitmask representing the reason will be returned. // Default value is nil which means no callback and it prevents from unwrapping the oldest entry. OnRemove: nil, // OnRemoveWithReason is a callback fired when the oldest entry is removed because of its expiration time or no space left // for the new entry, or because delete was called. A constant representing the reason will be passed through. // Default value is nil which means no callback and it prevents from unwrapping the oldest entry. // Ignored if OnRemove is specified. OnRemoveWithReason: nil, } cache, initErr := bigcache.New(context.Background(), config) if initErr != nil { log.Fatal(initErr) } cache.Set("my-unique-key", []byte("value")) if entry, err := cache.Get("my-unique-key"); err == nil { fmt.Println(string(entry)) } ``` -------------------------------- ### Initialize BigCache with Default Configuration Source: https://github.com/allegro/bigcache/blob/main/README.md Use this for simple initialization with default settings. It requires a context and a time duration for the life window. The cache is then ready to store and retrieve byte slices. ```go import ( "context" "fmt" "time" "github.com/allegro/bigcache/v3" ) cache, _ := bigcache.New(context.Background(), bigcache.DefaultConfig(10 * time.Minute)) cache.Set("my-unique-key", []byte("value")) entry, _ := cache.Get("my-unique-key") fmt.Println(string(entry)) ``` -------------------------------- ### Create and Use BytesQueue in Go Source: https://context7.com/allegro/bigcache/llms.txt Demonstrates creating a BytesQueue with specified capacities, pushing entries, retrieving them by index, peeking, popping, and resetting the queue. Use this for specialized byte-level queue operations. ```go package main import ( "fmt" "github.com/allegro/bigcache/v3/queue" ) func main() { // Create queue: initial capacity, max capacity (0=unlimited), verbose q := queue.NewBytesQueue(1024, 0, false) // Push returns index for later retrieval index1, _ := q.Push([]byte("first entry")) index2, _ := q.Push([]byte("second entry")) index3, _ := q.Push([]byte("third entry")) fmt.Printf("Queue length: %d\n", q.Len()) fmt.Printf("Queue capacity: %d bytes\n", q.Capacity()) // Get by index entry, _ := q.Get(index1) fmt.Printf("Entry at index %d: %s\n", index1, string(entry)) // Peek oldest without removing oldest, _ := q.Peek() fmt.Printf("Oldest entry: %s\n", string(oldest)) // Pop removes and returns oldest popped, _ := q.Pop() fmt.Printf("Popped: %s\n", string(popped)) fmt.Printf("Queue length after pop: %d\n", q.Len()) // Reset clears the queue q.Reset() fmt.Printf("Queue length after reset: %d\n", q.Len()) _ = index2 _ = index3 } ``` -------------------------------- ### Create BigCache Instance with Default Configuration Source: https://context7.com/allegro/bigcache/llms.txt Initializes a new BigCache instance using default settings and a specified entry lifetime. Ensure graceful shutdown by deferring the Close method. ```go package main import ( "context" "fmt" "log" "time" "github.com/allegro/bigcache/v3" ) func main() { // Create cache with 10-minute entry lifetime cache, err := bigcache.New(context.Background(), bigcache.DefaultConfig(10*time.Minute)) if err != nil { log.Fatal(err) } defer cache.Close() // Store and retrieve a value err = cache.Set("user:123", []byte(`{"name":"John","email":"john@example.com"}`)) if err != nil { log.Fatal(err) } entry, err := cache.Get("user:123") if err != nil { log.Fatal(err) } fmt.Println(string(entry)) // Output: {"name":"John","email":"john@example.com"} } ``` -------------------------------- ### Creating a Cache with Custom Configuration Source: https://context7.com/allegro/bigcache/llms.txt Illustrates how to create a BigCache instance with a custom configuration, allowing fine-grained control over parameters like shards, eviction windows, memory limits, and removal callbacks. ```APIDOC ## Creating a Cache with Custom Configuration ### Description The `Config` struct allows fine-grained control over cache behavior including shard count, eviction windows, memory limits, and removal callbacks. Custom configuration is recommended when cache load can be predicted to avoid runtime memory allocations. ### Method `bigcache.New(context.Context, bigcache.Config) (*bigcache.BigCache, error)` ### Endpoint N/A (Library function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```go package main import ( "context" "fmt" "log" "time" "github.com/allegro/bigcache/v3" ) func main() { config := bigcache.Config{ // Number of shards (must be a power of 2) Shards: 1024, // Time after which entry can be evicted LifeWindow: 10 * time.Minute, // Interval between removing expired entries // Setting to <= 0 disables cleanup goroutine CleanWindow: 5 * time.Minute, // rps * lifeWindow, used only in initial memory allocation MaxEntriesInWindow: 1000 * 10 * 60, // Max entry size in bytes, used only in initial memory allocation MaxEntrySize: 500, // Prints information about additional memory allocation Verbose: true, // Maximum cache size in MB (0 = unlimited) // When reached, oldest entries are overwritten HardMaxCacheSize: 8192, // Callback fired when entry is removed OnRemove: func(key string, entry []byte) { fmt.Printf("Removed key: %s\n", key) }, // Alternative callback with removal reason OnRemoveWithReason: func(key string, entry []byte, reason bigcache.RemoveReason) { switch reason { case bigcache.Expired: fmt.Printf("Key %s expired\n", key) case bigcache.NoSpace: fmt.Printf("Key %s evicted due to space\n", key) case bigcache.Deleted: fmt.Printf("Key %s explicitly deleted\n", key) } }, } cache, err := bigcache.New(context.Background(), config) if err != nil { log.Fatal(err) } defer cache.Close() cache.Set("session:abc", []byte("session-data")) entry, _ := cache.Get("session:abc") fmt.Println(string(entry)) // Output: session-data } ``` ### Response #### Success Response (200) N/A (Library function, returns cache instance or error) #### Response Example N/A ``` -------------------------------- ### GetWithInfo - Retrieve Entry with Metadata Source: https://context7.com/allegro/bigcache/llms.txt Returns the entry along with metadata about its status, including whether it has expired. Useful for checking entry validity without immediate removal. ```go package main import ( "context" "fmt" "log" "time" "github.com/allegro/bigcache/v3" ) func main() { config := bigcache.DefaultConfig(1 * time.Second) config.CleanWindow = 0 // Disable automatic cleanup cache, _ := bigcache.New(context.Background(), config) defer cache.Close() cache.Set("temp-data", []byte("temporary value")) // Get entry with status info entry, response, err := cache.GetWithInfo("temp-data") if err != nil { log.Fatal(err) } fmt.Printf("Value: %s\n", string(entry)) fmt.Printf("Entry Status: %d\n", response.EntryStatus) // Wait for expiration time.Sleep(2 * time.Second) // Entry still accessible but marked as expired entry, response, err = cache.GetWithInfo("temp-data") if err == nil { if response.EntryStatus == bigcache.Expired { fmt.Println("Entry has expired") } } // Output: Entry has expired } ``` -------------------------------- ### Build BigCache HTTP Server with Go Source: https://github.com/allegro/bigcache/blob/main/server/README.md Command to build the BigCache HTTP Server executable using the Go toolchain. This is a native Go application with no external dependencies. ```bash go build server.go ``` -------------------------------- ### Implement Custom Hashing with Hasher Interface Source: https://context7.com/allegro/bigcache/llms.txt Provide a custom hash function by implementing the Hasher interface, specifically the Sum64(string) uint64 method. This allows for custom key distribution across cache shards. ```go package main import ( "context" "fmt" "hash/fnv" "time" "github.com/allegro/bigcache/v3" ) // CustomHasher implements bigcache.Hasher interface type CustomHasher struct{} func (h CustomHasher) Sum64(key string) uint64 { hasher := fnv.New64a() hasher.Write([]byte(key)) return hasher.Sum64() } func main() { config := bigcache.DefaultConfig(10 * time.Minute) config.Hasher = CustomHasher{} cache, _ := bigcache.New(context.Background(), config) defer cache.Close() cache.Set("custom-hashed-key", []byte("value with custom hashing")) entry, _ := cache.Get("custom-hashed-key") fmt.Println(string(entry)) // Output: value with custom hashing } ``` -------------------------------- ### BigCache HTTP Server Command-line Flags Source: https://github.com/allegro/bigcache/blob/main/server/README.md Lists the available command-line flags for configuring the BigCache HTTP Server. These flags control cache lifetime, logging, memory limits, port, and verbosity. ```powershell PS C:\go\src\github.com\mxplusb\bigcache\server> .\server.exe -h Usage of C:\go\src\github.com\mxplusb\bigcache\server\server.exe: -lifetime duration Lifetime of each cache object. (default 10m0s) -logfile string Location of the logfile. -max int Maximum amount of data in the cache in MB. (default 8192) -maxInWindow int Used only in initial memory allocation. (default 600000) -maxShardEntrySize int The maximum size of each object stored in a shard. Used only in initial memory allocation. (default 500) -port int The port to listen on. (default 9090) -shards int Number of shards for the cache. (default 1024) -v Verbose logging. -version Print server version. ``` -------------------------------- ### Iterate Over Cache Entries with Go Source: https://context7.com/allegro/bigcache/llms.txt Obtain an iterator using `Iterator()` to traverse all entries in the cache. Use `SetNext()` to advance the iterator and `Value()` to retrieve the current entry's key, value, and hash. Handle potential errors during value retrieval. ```go package main import ( "context" "fmt" "time" "github.com/allegro/bigcache/v3" ) func main() { cache, _ := bigcache.New(context.Background(), bigcache.DefaultConfig(10*time.Minute)) defer cache.Close() // Add some entries cache.Set("user:1", []byte("Alice")) cache.Set("user:2", []byte("Bob")) cache.Set("user:3", []byte("Charlie")) // Iterate over all entries iterator := cache.Iterator() for iterator.SetNext() { entry, err := iterator.Value() if err != nil { fmt.Println("Error reading entry:", err) continue } fmt.Printf("Key: %s, Value: %s, Hash: %d\n", entry.Key(), string(entry.Value()), entry.Hash()) } // Output (order may vary due to sharding): // Key: user:1, Value: Alice, Hash: 12345678901234567 // Key: user:2, Value: Bob, Hash: 23456789012345678 // Key: user:3, Value: Charlie, Hash: 34567890123456789 } ``` -------------------------------- ### Reset - Clear All Cache Entries Source: https://context7.com/allegro/bigcache/llms.txt Empties all entries from the cache, clearing all shards. Use with caution as it is a destructive operation. ```go package main import ( "context" "fmt" "time" "github.com/allegro/bigcache/v3" ) func main() { cache, _ := bigcache.New(context.Background(), bigcache.DefaultConfig(10*time.Minute)) defer cache.Close() // Populate cache cache.Set("key1", []byte("value1")) cache.Set("key2", []byte("value2")) cache.Set("key3", []byte("value3")) fmt.Printf("Entries before reset: %d\n", cache.Len()) // Output: Entries before reset: 3 // Clear all entries err := cache.Reset() if err != nil { fmt.Println("Reset failed:", err) } fmt.Printf("Entries after reset: %d\n", cache.Len()) // Output: Entries after reset: 0 } ``` -------------------------------- ### GetWithInfo - Retrieve Entry with Metadata Source: https://context7.com/allegro/bigcache/llms.txt Retrieves an entry along with its metadata, including its expiration status. Useful for checking if an entry has expired without necessarily removing it. ```APIDOC ## GET /cache/{key}/info ### Description Retrieves the value and metadata for a specific cache entry. ### Method GET ### Endpoint `/cache/{key}/info` ### Parameters #### Path Parameters - **key** (string) - Required - The key of the entry to retrieve. ### Response #### Success Response (200) - **value** ([]byte) - The data associated with the key. - **response** (object) - Metadata about the entry. - **EntryStatus** (int) - The status of the entry (e.g., `bigcache.Expired`). #### Error Response (404) - **error** (string) - `ErrEntryNotFound` if the key does not exist. ``` -------------------------------- ### Compare GC Pause Times Source: https://github.com/allegro/bigcache/blob/main/README.md Measure and compare Garbage Collection pause times for BigCache, FreeCache, and standard Go maps with a large number of entries. This helps in understanding the GC overhead of each caching strategy. ```bash go version go version go1.13 linux/amd64 go run caches_gc_overhead_comparison.go Number of entries: 20000000 GC pause for bigcache: 1.506077ms GC pause for freecache: 5.594416ms GC pause for map: 9.347015ms ``` ```bash go version go version go1.13 linux/arm64 go run caches_gc_overhead_comparison.go Number of entries: 20000000 GC pause for bigcache: 22.382827ms GC pause for freecache: 41.264651ms GC pause for map: 72.236853ms ``` -------------------------------- ### Configure Removal Filter with OnRemoveFilterSet Source: https://context7.com/allegro/bigcache/llms.txt Use OnRemoveFilterSet to specify which removal reasons (e.g., Expired, Deleted) should trigger the OnRemoveWithReason callback. This optimizes CPU usage by avoiding unnecessary callback processing for uninteresting removal types like NoSpace. ```go package main import ( "context" "fmt" "time" "github.com/allegro/bigcache/v3" ) func main() { config := bigcache.DefaultConfig(1 * time.Second) config.CleanWindow = 500 * time.Millisecond // Only trigger callback for expired and deleted entries, not for NoSpace config = config.OnRemoveFilterSet(bigcache.Expired, bigcache.Deleted) config.OnRemoveWithReason = func(key string, entry []byte, reason bigcache.RemoveReason) { switch reason { case bigcache.Expired: fmt.Printf("Expired: %s\n", key) case bigcache.Deleted: fmt.Printf("Deleted: %s\n", key) } } cache, _ := bigcache.New(context.Background(), config) defer cache.Close() cache.Set("temp-key", []byte("temporary")) cache.Delete("temp-key") // Output: Deleted: temp-key cache.Set("expiring-key", []byte("will expire")) time.Sleep(2 * time.Second) // Output: Expired: expiring-key } ``` -------------------------------- ### Set - Store Entry in Cache Source: https://context7.com/allegro/bigcache/llms.txt Details the `Set` method for storing byte slice values in the cache. It explains how existing keys are overwritten and the condition under which an error is returned. ```APIDOC ## Set - Store Entry in Cache ### Description The `Set` method stores a byte slice value under the specified key. If the key already exists, its value is overwritten. Returns an error if the entry exceeds the maximum shard size. ### Method `(*bigcache.BigCache).Set(key string, entry []byte) error` ### Endpoint N/A (Library function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```go package main import ( "context" "encoding/json" "log" "time" "github.com/allegro/bigcache/v3" ) func main() { cache, _ := bigcache.New(context.Background(), bigcache.DefaultConfig(10*time.Minute)) defer cache.Close() // Store simple string err := cache.Set("greeting", []byte("Hello, World!")) if err != nil { log.Fatal(err) } // Store JSON data user := map[string]interface{}{ "id": 123, "name": "Alice", "email": "alice@example.com", } userData, _ := json.Marshal(user) err = cache.Set("user:123", userData) if err != nil { log.Fatal(err) } // Overwrite existing key err = cache.Set("greeting", []byte("Updated greeting!")) if err != nil { log.Fatal(err) } } ``` ### Response #### Success Response (200) N/A (Library function, returns nil on success) #### Response Example N/A ``` -------------------------------- ### Graceful Cache Shutdown with Close and Context Source: https://context7.com/allegro/bigcache/llms.txt The Close method stops the cache's cleanup goroutine, ensuring a graceful shutdown. Alternatively, cancelling the context passed during cache initialization also stops the cleanup goroutine. ```go package main import ( "context" "fmt" "time" "github.com/allegro/bigcache/v3" ) func main() { ctx, cancel := context.WithCancel(context.Background()) config := bigcache.DefaultConfig(10 * time.Minute) config.CleanWindow = 1 * time.Second cache, _ := bigcache.New(ctx, config) // Use cache... cache.Set("key", []byte("value")) // Method 1: Close via Close() err := cache.Close() if err != nil { fmt.Println("Close error:", err) } fmt.Println("Cache closed via Close()") // Method 2: Close via context cancellation cache2, _ := bigcache.New(ctx, config) cache2.Set("key", []byte("value")) cancel() // This also stops the cleanup goroutine fmt.Println("Cache closed via context cancellation") } ``` -------------------------------- ### Reset - Clear All Cache Entries Source: https://context7.com/allegro/bigcache/llms.txt Empties all entries from the cache, effectively clearing all shards. ```APIDOC ## POST /cache/reset ### Description Clears all entries from the cache. ### Method POST ### Endpoint `/cache/reset` ### Response #### Success Response (200) - **message** (string) - Confirmation that the cache has been reset. ``` -------------------------------- ### Append - Concatenate Data to Existing Entry Source: https://context7.com/allegro/bigcache/llms.txt Appends data to an existing entry or creates a new entry if the key doesn't exist. Ideal for building values incrementally without multiple get/set operations. ```go package main import ( "context" "fmt" "time" "github.com/allegro/bigcache/v3" ) func main() { cache, _ := bigcache.New(context.Background(), bigcache.DefaultConfig(10*time.Minute)) defer cache.Close() // Append creates entry if it doesn't exist cache.Append("log:events", []byte("Event 1\n")) cache.Append("log:events", []byte("Event 2\n")) cache.Append("log:events", []byte("Event 3\n")) entry, _ := cache.Get("log:events") fmt.Println(string(entry)) // Output: // Event 1 // Event 2 // Event 3 } ``` -------------------------------- ### Delete - Remove Entry from Cache Source: https://context7.com/allegro/bigcache/llms.txt Removes an entry from the cache. Returns ErrEntryNotFound if the key doesn't exist. Useful for explicit cache invalidation. ```go package main import ( "context" "errors" "fmt" "time" "github.com/allegro/bigcache/v3" ) func main() { cache, _ := bigcache.New(context.Background(), bigcache.DefaultConfig(10*time.Minute)) defer cache.Close() cache.Set("session:xyz", []byte("session-data")) // Delete existing key err := cache.Delete("session:xyz") if err != nil { fmt.Println("Delete failed:", err) } else { fmt.Println("Session deleted successfully") } // Output: Session deleted successfully // Attempt to delete non-existent key err = cache.Delete("session:xyz") if errors.Is(err, bigcache.ErrEntryNotFound) { fmt.Println("Key already deleted or doesn't exist") } // Output: Key already deleted or doesn't exist } ``` -------------------------------- ### Cache API Source: https://github.com/allegro/bigcache/blob/main/server/README.md Endpoints for interacting with the cache, allowing for setting, retrieving, and deleting cache entries. ```APIDOC ## GET /api/v1/cache/{key} ### Description Retrieves the value associated with the specified key from the cache. ### Method GET ### Endpoint /api/v1/cache/{key} ### Parameters #### Path Parameters - **key** (string) - Required - The key of the cache entry to retrieve. ### Response #### Success Response (200) - **value** (string) - The value stored for the given key. #### Response Example ``` yay! ``` ## PUT /api/v1/cache/{key} ### Description Stores a value in the cache associated with the specified key. Accepts any content type. ### Method PUT ### Endpoint /api/v1/cache/{key} ### Parameters #### Path Parameters - **key** (string) - Required - The key for the cache entry. #### Request Body - **value** (any) - Required - The content to store in the cache. ### Request Example ```json { "example": "yay!" } ``` ### Response #### Success Response (201) - **message** (string) - Confirmation message. #### Response Example ```json { "message": "Successfully stored" } ``` ## DELETE /api/v1/cache/{key} ### Description Deletes the cache entry associated with the specified key. ### Method DELETE ### Endpoint /api/v1/cache/{key} ### Parameters #### Path Parameters - **key** (string) - Required - The key of the cache entry to delete. ### Response #### Success Response (200) - **message** (string) - Confirmation message. #### Response Example ```json { "message": "Successfully deleted" } ``` ``` -------------------------------- ### Store Entry in BigCache Source: https://context7.com/allegro/bigcache/llms.txt Stores a byte slice value under a specified key. Overwrites the value if the key already exists. Returns an error if the entry exceeds the maximum shard size. Handles serialization for complex types. ```go package main import ( "context" "encoding/json" "log" "time" "github.com/allegro/bigcache/v3" ) func main() { cache, _ := bigcache.New(context.Background(), bigcache.DefaultConfig(10*time.Minute)) defer cache.Close() // Store simple string err := cache.Set("greeting", []byte("Hello, World!")) if err != nil { log.Fatal(err) } // Store JSON data user := map[string]interface{}{ "id": 123, "name": "Alice", "email": "alice@example.com", } userData, _ := json.Marshal(user) err = cache.Set("user:123", userData) if err != nil { log.Fatal(err) } // Overwrite existing key err = cache.Set("greeting", []byte("Updated greeting!")) if err != nil { log.Fatal(err) } } ``` -------------------------------- ### Append - Concatenate Data to Existing Entry Source: https://context7.com/allegro/bigcache/llms.txt Appends new data to an existing cache entry. If the key does not exist, a new entry is created with the provided data. ```APIDOC ## POST /cache/{key}/append ### Description Appends data to an existing cache entry or creates a new one if the key is not found. ### Method POST ### Endpoint `/cache/{key}/append` ### Parameters #### Path Parameters - **key** (string) - Required - The key of the entry to append data to. #### Request Body - **data** ([]byte) - Required - The data to append to the entry. ``` -------------------------------- ### Delete - Remove Entry from Cache Source: https://context7.com/allegro/bigcache/llms.txt Removes a specified entry from the cache. Returns `ErrEntryNotFound` if the key does not exist. ```APIDOC ## DELETE /cache/{key} ### Description Removes a cache entry identified by its key. ### Method DELETE ### Endpoint `/cache/{key}` ### Parameters #### Path Parameters - **key** (string) - Required - The key of the entry to delete. ### Response #### Success Response (200) - **message** (string) - Confirmation of deletion. #### Error Response (404) - **error** (string) - `ErrEntryNotFound` if the key does not exist or has already been deleted. ``` -------------------------------- ### Stats API Source: https://github.com/allegro/bigcache/blob/main/server/README.md Endpoint for retrieving cache statistics. ```APIDOC ## GET /api/v1/stats ### Description Retrieves hit and miss statistics for the cache since the last server restart. ### Method GET ### Endpoint /api/v1/stats ### Response #### Success Response (200) - **hits** (integer) - The number of cache hits. - **misses** (integer) - The number of cache misses. #### Response Example ```json { "hits": 100, "misses": 20 } ``` ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.