cache2go
Concurrency-safe Go caching library with expiration capabilities and access counters
Top Related Projects
An in-memory key:value store/cache (similar to Memcached) library for Go, suitable for single-machine applications.
Efficient cache for gigabytes of data written in Go.
An in-memory cache library for golang. It supports multiple eviction policies: LRU, LFU, ARC
A cache library for Go with zero GC overhead.
Quick Overview
cache2go
is a concurrent-safe, in-memory key:value cache library for Go. It provides a simple and efficient way to store and retrieve data in memory, with support for expiration times and callbacks for cache entry updates and deletions.
Pros
- Concurrent-safe: The library is designed to be thread-safe, allowing multiple goroutines to access and modify the cache concurrently without race conditions.
- Expiration: Cache entries can be set to expire after a specified duration, automatically removing stale data from the cache.
- Callbacks: Developers can register callbacks to be executed when a cache entry is updated or deleted, enabling custom logic to be triggered.
- Simple API: The library has a straightforward and easy-to-use API, making it simple to integrate into Go projects.
Cons
- Limited data types: The cache only supports string keys and values, which may limit its usefulness for more complex data structures.
- No persistence: The cache is entirely in-memory, so data will be lost when the application is restarted or the server is shut down. There is no built-in persistence mechanism.
- Limited documentation: The project's documentation could be more comprehensive, especially for advanced use cases and configuration options.
- Lack of active development: The project appears to have had limited updates in recent years, which may indicate a lack of active maintenance and development.
Code Examples
Here are a few examples of how to use the cache2go
library:
- Storing and retrieving a cache entry:
cache := cache2go.Cache("my_cache")
cacheValue := cache.Add("my_key", 60, "my_value")
value, err := cacheValue.Value()
if err == nil {
fmt.Println(value.(string)) // Output: "my_value"
}
- Setting an expiration time for a cache entry:
cache := cache2go.Cache("my_cache")
cacheValue := cache.Add("my_key", 60, "my_value")
cacheValue.SetExpiration(time.Now().Add(5 * time.Minute))
- Registering a callback for cache entry updates:
cache := cache2go.Cache("my_cache")
cache.SetUpdateCallback(func(key interface{}, entry *cache2go.CacheItem) {
fmt.Printf("Cache entry updated: %s = %v\n", key, entry.Data())
})
cache.Add("my_key", 60, "my_value")
cache.Add("my_key", 60, "updated_value") // Triggers the callback
- Removing a cache entry:
cache := cache2go.Cache("my_cache")
cache.Add("my_key", 60, "my_value")
cache.Delete("my_key")
Getting Started
To use the cache2go
library in your Go project, follow these steps:
- Install the library using
go get
:
go get github.com/muesli/cache2go
- Import the library in your Go file:
import "github.com/muesli/cache2go"
- Create a new cache and add entries:
cache := cache2go.Cache("my_cache")
cacheValue := cache.Add("my_key", 60, "my_value")
- Retrieve the value from the cache:
value, err := cacheValue.Value()
if err == nil {
fmt.Println(value.(string)) // Output: "my_value"
}
- Set an expiration time for the cache entry:
cacheValue.SetExpiration(time.Now().Add(5 * time.Minute))
- Register a callback for cache entry updates:
cache.SetUpdateCallback(func(key interface{}, entry *cache2go.CacheItem) {
fmt.Printf("Cache entry updated: %s = %v\n", key, entry.Data())
})
That's the basic usage of the cache2go
library. Refer to the project's documentation for more
Competitor Comparisons
An in-memory key:value store/cache (similar to Memcached) library for Go, suitable for single-machine applications.
Pros of go-cache
- Simpler and more lightweight than cache2go, with fewer features.
- Provides a straightforward in-memory cache implementation.
- Supports expiration and eviction of cache entries.
Cons of go-cache
- Lacks some advanced features like sharding, replication, and persistence that cache2go provides.
- May not be suitable for large-scale or distributed caching scenarios.
- Provides fewer configuration options compared to cache2go.
Code Comparison
go-cache:
cache := goCache.New(5*time.Minute, 10*time.Minute)
cache.Set("key", "value", goCache.DefaultExpiration)
value, found := cache.Get("key")
cache2go:
table := cache2go.Cache("mytable")
table.Add("key", 60, "value")
value, err := table.Value("key")
Efficient cache for gigabytes of data written in Go.
Pros of BigCache
- BigCache is designed for high-performance, low-latency caching, making it suitable for applications with high traffic and strict performance requirements.
- BigCache supports automatic expiration of cache entries, which can be useful for maintaining cache consistency.
- BigCache provides a simple and straightforward API, making it easy to integrate into existing projects.
Cons of BigCache
- BigCache is a single-process cache, which means it may not be as scalable as distributed cache solutions like Cache2go.
- BigCache does not provide built-in support for advanced features like cache eviction policies or cache sharding.
- The documentation for BigCache may be less comprehensive compared to Cache2go.
Code Comparison
Cache2go:
cache := cache2go.Cache("mycache")
item := cache.Add("mykey", 60, "some data")
data, err := item.Value()
BigCache:
cache, _ := bigcache.NewBigCache(bigcache.DefaultConfig(10 * time.Minute))
cache.Set("mykey", []byte("some data"))
data, _ := cache.Get("mykey")
An in-memory cache library for golang. It supports multiple eviction policies: LRU, LFU, ARC
Pros of bluele/gcache
- Expiration Policies: bluele/gcache offers a wider range of expiration policies, including LRU (Least Recently Used), LFU (Least Frequently Used), and TTL (Time-To-Live), allowing for more flexible cache management.
- Concurrent Access: bluele/gcache is designed to handle concurrent access to the cache, making it suitable for high-traffic applications.
- Customizable Eviction Callbacks: bluele/gcache allows you to define custom callbacks for when items are evicted from the cache, enabling more advanced cache management strategies.
Cons of bluele/gcache
- Complexity: bluele/gcache has a more complex API and configuration options compared to muesli/cache2go, which may have a steeper learning curve for some users.
- Dependency: bluele/gcache has a dependency on the
golang.org/x/sync
package, which may be a concern for some users who prefer to minimize external dependencies. - Lack of Distributed Cache Support: Unlike muesli/cache2go, bluele/gcache does not provide built-in support for distributed caching, which may be a limitation for certain use cases.
Code Comparison
muesli/cache2go:
cache := cache2go.Cache("mycache")
item := cache.Add("mykey", 60, "my value")
value, err := item.Value()
bluele/gcache:
cache := gcache.New(10).LRU().Build()
cache.Set("mykey", "my value")
value, err := cache.Get("mykey")
A cache library for Go with zero GC overhead.
Pros of coocood/freecache
- Memory Efficiency: coocood/freecache is designed to be highly memory-efficient, making it a suitable choice for applications with limited memory resources.
- Concurrent Access: coocood/freecache supports concurrent access to the cache, allowing for better performance in multi-threaded environments.
- Persistence: coocood/freecache provides the ability to persist the cache to disk, enabling data recovery in the event of a system restart.
Cons of coocood/freecache
- Complexity: coocood/freecache may have a steeper learning curve compared to muesli/cache2go, as it offers more advanced features and configuration options.
- Dependency Management: coocood/freecache has a larger set of dependencies, which may complicate the integration process in some projects.
Code Comparison
muesli/cache2go:
cache := cache2go.Cache("mycache")
item := cache.Add("mykey", 60, "my data")
data, err := item.Value()
coocood/freecache:
cache := freecache.NewCache(100 * 1024 * 1024) // 100MB
cache.Set([]byte("mykey"), []byte("my data"), 60)
data, err := cache.Get([]byte("mykey"))
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
cache2go
Concurrency-safe golang caching library with expiration capabilities.
Installation
Make sure you have a working Go environment (Go 1.2 or higher is required). See the install instructions.
To install cache2go, simply run:
go get github.com/muesli/cache2go
To compile it from source:
cd $GOPATH/src/github.com/muesli/cache2go
go get -u -v
go build && go test -v
Example
package main
import (
"github.com/muesli/cache2go"
"fmt"
"time"
)
// Keys & values in cache2go can be of arbitrary types, e.g. a struct.
type myStruct struct {
text string
moreData []byte
}
func main() {
// Accessing a new cache table for the first time will create it.
cache := cache2go.Cache("myCache")
// We will put a new item in the cache. It will expire after
// not being accessed via Value(key) for more than 5 seconds.
val := myStruct{"This is a test!", []byte{}}
cache.Add("someKey", 5*time.Second, &val)
// Let's retrieve the item from the cache.
res, err := cache.Value("someKey")
if err == nil {
fmt.Println("Found value in cache:", res.Data().(*myStruct).text)
} else {
fmt.Println("Error retrieving value from cache:", err)
}
// Wait for the item to expire in cache.
time.Sleep(6 * time.Second)
res, err = cache.Value("someKey")
if err != nil {
fmt.Println("Item is not cached (anymore).")
}
// Add another item that never expires.
cache.Add("someKey", 0, &val)
// cache2go supports a few handy callbacks and loading mechanisms.
cache.SetAboutToDeleteItemCallback(func(e *cache2go.CacheItem) {
fmt.Println("Deleting:", e.Key(), e.Data().(*myStruct).text, e.CreatedOn())
})
// Remove the item from the cache.
cache.Delete("someKey")
// And wipe the entire cache table.
cache.Flush()
}
To run this example, go to examples/mycachedapp/ and run:
go run mycachedapp.go
You can find a few more examples here. Also see our test-cases in cache_test.go for further working examples.
Top Related Projects
An in-memory key:value store/cache (similar to Memcached) library for Go, suitable for single-machine applications.
Efficient cache for gigabytes of data written in Go.
An in-memory cache library for golang. It supports multiple eviction policies: LRU, LFU, ARC
A cache library for Go with zero GC overhead.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot