Documentation
¶
Index ¶
- Variables
- func Clear(name string) error
- func ClearAll()
- func Close()
- func Delete(name string) error
- func GetOptimizerMetrics() resource.CacheOptimizerMetrics
- func List() []string
- func Stats() map[string]*ristretto.Metrics
- type APICache
- type Builder
- func APICacheBuilder(name string) *Builder
- func LargeCacheBuilder(name string) *Builder
- func MediumCacheBuilder(name string) *Builder
- func NewBuilder(name string) *Builder
- func ObjectCacheBuilder(name string) *Builder
- func SessionCacheBuilder(name string, sessionTTL time.Duration) *Builder
- func SmallCacheBuilder(name string) *Builder
- func (b *Builder) Build() (*Cache, error)
- func (b *Builder) BuildAndRegister() (*Cache, error)
- func (b *Builder) WithBufferItems(items int64) *Builder
- func (b *Builder) WithCostFunction(fn func(value interface{}) int64) *Builder
- func (b *Builder) WithEvictionCallback(fn func(item *ristretto.Item)) *Builder
- func (b *Builder) WithExitCallback(fn func(interface{})) *Builder
- func (b *Builder) WithHashFunction(fn func(key interface{}) (uint64, uint64)) *Builder
- func (b *Builder) WithMaxCost(cost int64) *Builder
- func (b *Builder) WithMaxItems(items int64) *Builder
- func (b *Builder) WithMaxMemory(bytes int64) *Builder
- func (b *Builder) WithMetrics(enabled bool) *Builder
- func (b *Builder) WithNumCounters(num int64) *Builder
- func (b *Builder) WithRejectionCallback(fn func(item *ristretto.Item)) *Builder
- type Cache
- func Create(name string, opts *Options) (*Cache, error)
- func Get(name string) (*Cache, bool)
- func GetOrCreate(name string, opts *Options) (*Cache, error)
- func LargeCache(name string) (*Cache, error)
- func New(name string, opts *Options) (*Cache, error)
- func QuickCache(name string) (*Cache, error)
- func SmallCache(name string) (*Cache, error)
- func TTLCache(name string, defaultTTL time.Duration) (*Cache, error)
- func (c *Cache) Clear()
- func (c *Cache) Close()
- func (c *Cache) Delete(key interface{})
- func (c *Cache) DeleteMulti(keys []interface{})
- func (c *Cache) Get(key interface{}) (interface{}, error)
- func (c *Cache) GetMulti(keys []interface{}) map[interface{}]interface{}
- func (c *Cache) GetOrSet(key interface{}, fn func() (interface{}, error), ttl time.Duration) (interface{}, error)
- func (c *Cache) GetOrSetContext(ctx context.Context, key interface{}, ...) (interface{}, error)
- func (c *Cache) GetWithExpiration(key interface{}) (interface{}, bool)
- func (c *Cache) Has(key interface{}) bool
- func (c *Cache) Metrics() *ristretto.Metrics
- func (c *Cache) Name() string
- func (c *Cache) Set(key interface{}, value interface{}, ttl time.Duration) error
- func (c *Cache) SetMulti(items map[interface{}]interface{}, ttl time.Duration) error
- func (c *Cache) SetWithCost(key interface{}, value interface{}, cost int64, ttl time.Duration) error
- type Config
- type Manager
- func (m *Manager) Clear(name string) error
- func (m *Manager) ClearAll()
- func (m *Manager) Close() error
- func (m *Manager) Create(name string, opts *Options) (*Cache, error)
- func (m *Manager) CreateOptimized(name string, config Config) (*OptimizedCacheWrapper, error)
- func (m *Manager) Delete(name string) error
- func (m *Manager) Get(name string) (*Cache, bool)
- func (m *Manager) GetOptimizerMetrics() resource.CacheOptimizerMetrics
- func (m *Manager) GetOrCreate(name string, opts *Options) (*Cache, error)
- func (m *Manager) List() []string
- func (m *Manager) Stats() map[string]*ristretto.Metrics
- type OptimizedCacheWrapper
- func (w *OptimizedCacheWrapper) Clear()
- func (w *OptimizedCacheWrapper) Close()
- func (w *OptimizedCacheWrapper) Delete(key interface{})
- func (w *OptimizedCacheWrapper) DeleteMulti(keys []interface{})
- func (w *OptimizedCacheWrapper) Get(key interface{}) (interface{}, error)
- func (w *OptimizedCacheWrapper) GetMulti(keys []interface{}) map[interface{}]interface{}
- func (w *OptimizedCacheWrapper) GetOrSet(key interface{}, fn func() (interface{}, error), ttl time.Duration) (interface{}, error)
- func (w *OptimizedCacheWrapper) GetWithExpiration(key interface{}) (interface{}, bool)
- func (w *OptimizedCacheWrapper) Has(key interface{}) bool
- func (w *OptimizedCacheWrapper) Metrics() *ristretto.Metrics
- func (w *OptimizedCacheWrapper) Name() string
- func (w *OptimizedCacheWrapper) Set(key interface{}, value interface{}, ttl time.Duration) error
- func (w *OptimizedCacheWrapper) SetMulti(items map[interface{}]interface{}, ttl time.Duration) error
- func (w *OptimizedCacheWrapper) SetWithCost(key interface{}, value interface{}, cost int64, ttl time.Duration) error
- type Options
- type Session
- type SessionCache
- type User
- type UserService
- func (s *UserService) Close()
- func (s *UserService) GetCacheStats() string
- func (s *UserService) GetMultipleUsers(ctx context.Context, userIDs []string) (map[string]*User, error)
- func (s *UserService) GetUser(ctx context.Context, userID string) (*User, error)
- func (s *UserService) GetUsersByRole(ctx context.Context, role string) ([]*User, error)
- func (s *UserService) InvalidateUserCache()
- func (s *UserService) UpdateUser(ctx context.Context, user *User) error
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var ( // ErrCacheMiss indicates that a key was not found in the cache ErrCacheMiss = errors.New("cache: key not found") // ErrCacheSet indicates that a value could not be set in the cache ErrCacheSet = errors.New("cache: failed to set value") // ErrInvalidTTL indicates that an invalid TTL was provided ErrInvalidTTL = errors.New("cache: invalid TTL") )
Functions ¶
func GetOptimizerMetrics ¶
func GetOptimizerMetrics() resource.CacheOptimizerMetrics
GetOptimizerMetrics gets optimizer metrics from the default manager
Types ¶
type APICache ¶
type APICache struct {
// contains filtered or unexported fields
}
APICache demonstrates caching for API responses
func (*APICache) CacheResponse ¶
CacheResponse caches an API response
func (*APICache) GetCachedResponse ¶
GetCachedResponse retrieves a cached API response
type Builder ¶
type Builder struct {
// contains filtered or unexported fields
}
Builder provides a fluent interface for building cache instances
Example ¶
package main
import (
"fmt"
"log"
"time"
"github.com/dgraph-io/ristretto"
"github.com/go-lynx/lynx/cache"
)
func main() {
// Build a custom cache with specific settings
c, err := cache.NewBuilder("custom").
WithMaxItems(1000). // Maximum 1000 items
WithMaxMemory(1 << 26). // 64MB memory limit
WithMetrics(true). // Enable metrics
WithEvictionCallback(func(item *ristretto.Item) {
fmt.Printf("Evicted key: %v\n", item.Key)
}).
Build()
if err != nil {
log.Fatal(err)
}
defer c.Close()
// Use the cache
c.Set("test", "value", 1*time.Minute)
}
func APICacheBuilder ¶
APICacheBuilder creates a builder for API response caches
func LargeCacheBuilder ¶
LargeCacheBuilder creates a builder for large caches
func MediumCacheBuilder ¶
MediumCacheBuilder creates a builder for medium caches
func ObjectCacheBuilder ¶
ObjectCacheBuilder creates a builder for object caches with custom cost calculation
func SessionCacheBuilder ¶
SessionCacheBuilder creates a builder for session caches
func SmallCacheBuilder ¶
SmallCacheBuilder creates a builder for small caches
func (*Builder) BuildAndRegister ¶
BuildAndRegister creates the cache and registers it with the default manager
func (*Builder) WithBufferItems ¶
WithBufferItems sets the buffer items for the cache
func (*Builder) WithCostFunction ¶
WithCostFunction sets a custom cost calculation function
func (*Builder) WithEvictionCallback ¶
WithEvictionCallback sets the eviction callback
func (*Builder) WithExitCallback ¶
WithExitCallback sets the exit callback
func (*Builder) WithHashFunction ¶
WithHashFunction sets a custom hash function
func (*Builder) WithMaxCost ¶
WithMaxCost sets the maximum cost for the cache
func (*Builder) WithMaxItems ¶
WithMaxItems sets the maximum number of items (approximation)
func (*Builder) WithMaxMemory ¶
WithMaxMemory sets the maximum memory usage in bytes
func (*Builder) WithMetrics ¶
WithMetrics enables or disables metrics collection
func (*Builder) WithNumCounters ¶
WithNumCounters sets the number of counters for the cache
type Cache ¶
type Cache struct {
// contains filtered or unexported fields
}
Cache represents a thread-safe in-memory cache with TTL support
Example (Basic) ¶
package main
import (
"fmt"
"log"
"time"
"github.com/go-lynx/lynx/cache"
)
func main() {
// Create a simple cache
c, err := cache.QuickCache("example")
if err != nil {
log.Fatal(err)
}
defer c.Close()
// Set a value with 5 minute TTL
err = c.Set("user:123", "John Doe", 5*time.Minute)
if err != nil {
log.Fatal(err)
}
// Get the value
value, err := c.Get("user:123")
if err != nil {
fmt.Println("Not found")
} else {
fmt.Println(value)
}
}
Output: John Doe
Example (Batch) ¶
package main
import (
"fmt"
"log"
"time"
"github.com/go-lynx/lynx/cache"
)
func main() {
c, err := cache.QuickCache("batch-example")
if err != nil {
log.Fatal(err)
}
defer c.Close()
// Set multiple values at once
items := map[interface{}]interface{}{
"key1": "value1",
"key2": "value2",
"key3": "value3",
}
err = c.SetMulti(items, 5*time.Minute)
if err != nil {
log.Fatal(err)
}
// Get multiple values at once
keys := []interface{}{"key1", "key2", "key3", "key4"}
values := c.GetMulti(keys)
for _, key := range keys {
if val, ok := values[key]; ok {
fmt.Printf("%v: %v\n", key, val)
} else {
fmt.Printf("%v: not found\n", key)
}
}
}
Output: key1: value1 key2: value2 key3: value3 key4: not found
Example (Concurrent) ¶
package main
import (
"fmt"
"log"
"sync"
"time"
"github.com/go-lynx/lynx/cache"
)
func main() {
c, err := cache.QuickCache("concurrent")
if err != nil {
log.Fatal(err)
}
defer c.Close()
var wg sync.WaitGroup
// Concurrent writes
for i := 0; i < 100; i++ {
wg.Add(1)
go func(id int) {
defer wg.Done()
key := fmt.Sprintf("key:%d", id)
value := fmt.Sprintf("value:%d", id)
c.Set(key, value, 5*time.Minute)
}(i)
}
// Concurrent reads
for i := 0; i < 100; i++ {
wg.Add(1)
go func(id int) {
defer wg.Done()
key := fmt.Sprintf("key:%d", id)
c.Get(key)
}(i)
}
wg.Wait()
fmt.Println("Concurrent operations completed")
}
Output: Concurrent operations completed
func GetOrCreate ¶
GetOrCreate retrieves or creates a cache in the default manager
func LargeCache ¶
LargeCache creates a large cache suitable for big data
func QuickCache ¶
QuickCache creates a simple cache with default settings
func SmallCache ¶
SmallCache creates a small cache suitable for limited data
func (*Cache) DeleteMulti ¶
func (c *Cache) DeleteMulti(keys []interface{})
DeleteMulti removes multiple keys from the cache
func (*Cache) GetMulti ¶
func (c *Cache) GetMulti(keys []interface{}) map[interface{}]interface{}
GetMulti retrieves multiple values from the cache
func (*Cache) GetOrSet ¶
func (c *Cache) GetOrSet(key interface{}, fn func() (interface{}, error), ttl time.Duration) (interface{}, error)
GetOrSet retrieves a value from the cache or sets it if not found
Example ¶
package main
import (
"fmt"
"log"
"time"
"github.com/go-lynx/lynx/cache"
)
func main() {
c, err := cache.QuickCache("lazy-load")
if err != nil {
log.Fatal(err)
}
defer c.Close()
// This function is only called if the key doesn't exist
value, err := c.GetOrSet("expensive-data", func() (interface{}, error) {
// Simulate expensive operation
time.Sleep(100 * time.Millisecond)
return "computed value", nil
}, 10*time.Minute)
if err != nil {
log.Fatal(err)
}
fmt.Println(value)
// Second call will get from cache (no sleep)
value, _ = c.GetOrSet("expensive-data", func() (interface{}, error) {
return "this won't be called", nil
}, 10*time.Minute)
fmt.Println(value)
}
Output: computed value computed value
func (*Cache) GetOrSetContext ¶
func (c *Cache) GetOrSetContext(ctx context.Context, key interface{}, fn func(context.Context) (interface{}, error), ttl time.Duration) (interface{}, error)
GetOrSetContext is like GetOrSet but with context support
Example ¶
package main
import (
"context"
"fmt"
"log"
"time"
"github.com/go-lynx/lynx/cache"
)
func main() {
c, err := cache.QuickCache("context-example")
if err != nil {
log.Fatal(err)
}
defer c.Close()
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
// Fetch with context support
value, err := c.GetOrSetContext(ctx, "api-data",
func(ctx context.Context) (interface{}, error) {
// Simulate API call
select {
case <-time.After(1 * time.Second):
return "api response", nil
case <-ctx.Done():
return nil, ctx.Err()
}
}, 5*time.Minute)
if err != nil {
log.Fatal(err)
}
fmt.Println(value)
}
Output: api response
func (*Cache) GetWithExpiration ¶
GetWithExpiration retrieves a value and checks if it exists
type Manager ¶
type Manager struct {
// contains filtered or unexported fields
}
Manager manages multiple cache instances
Example ¶
package main
import (
"fmt"
"log"
"time"
"github.com/go-lynx/lynx/cache"
)
func main() {
// Create different caches for different purposes
userCache, err := cache.Create("users", cache.DefaultOptions())
if err != nil {
log.Fatal(err)
}
sessionCache, err := cache.SessionCacheBuilder("sessions", 30*time.Minute).
BuildAndRegister()
if err != nil {
log.Fatal(err)
}
apiCache, err := cache.APICacheBuilder("api-responses").
BuildAndRegister()
if err != nil {
log.Fatal(err)
}
// Use the caches
userCache.Set("user:1", "Alice", 10*time.Minute)
sessionCache.Set("session:xyz", "session-data", 30*time.Minute)
apiCache.Set("/api/users", "cached-response", 1*time.Minute)
// List all caches
fmt.Println("Active caches:", cache.List())
// Get statistics
stats := cache.Stats()
for name, metrics := range stats {
if metrics != nil {
fmt.Printf("Cache %s - Hits: %d, Misses: %d\n",
name, metrics.Hits(), metrics.Misses())
}
}
// Clean up
cache.Close()
}
var DefaultManager *Manager
DefaultManager is the global cache manager instance
func NewManager ¶
func NewManager() *Manager
NewManager creates a new cache manager with a default logger.
func NewManagerWithLogger ¶
NewManagerWithLogger creates a new cache manager using the provided logger.
func (*Manager) CreateOptimized ¶
func (m *Manager) CreateOptimized(name string, config Config) (*OptimizedCacheWrapper, error)
CreateOptimized creates an optimized cache instance
func (*Manager) GetOptimizerMetrics ¶
func (m *Manager) GetOptimizerMetrics() resource.CacheOptimizerMetrics
GetOptimizerMetrics gets optimizer metrics
func (*Manager) GetOrCreate ¶
GetOrCreate retrieves an existing cache or creates a new one
type OptimizedCacheWrapper ¶
type OptimizedCacheWrapper struct {
// contains filtered or unexported fields
}
OptimizedCacheWrapper optimized cache wrapper
func CreateOptimizedCache ¶
func CreateOptimizedCache(name string, maxSize int, ttl time.Duration) (*OptimizedCacheWrapper, error)
CreateOptimizedCache creates an optimized cache (convenience function)
func (*OptimizedCacheWrapper) Clear ¶
func (w *OptimizedCacheWrapper) Clear()
func (*OptimizedCacheWrapper) Close ¶
func (w *OptimizedCacheWrapper) Close()
func (*OptimizedCacheWrapper) Delete ¶
func (w *OptimizedCacheWrapper) Delete(key interface{})
func (*OptimizedCacheWrapper) DeleteMulti ¶
func (w *OptimizedCacheWrapper) DeleteMulti(keys []interface{})
func (*OptimizedCacheWrapper) Get ¶
func (w *OptimizedCacheWrapper) Get(key interface{}) (interface{}, error)
func (*OptimizedCacheWrapper) GetMulti ¶
func (w *OptimizedCacheWrapper) GetMulti(keys []interface{}) map[interface{}]interface{}
func (*OptimizedCacheWrapper) GetOrSet ¶
func (w *OptimizedCacheWrapper) GetOrSet(key interface{}, fn func() (interface{}, error), ttl time.Duration) (interface{}, error)
func (*OptimizedCacheWrapper) GetWithExpiration ¶
func (w *OptimizedCacheWrapper) GetWithExpiration(key interface{}) (interface{}, bool)
func (*OptimizedCacheWrapper) Has ¶
func (w *OptimizedCacheWrapper) Has(key interface{}) bool
func (*OptimizedCacheWrapper) Metrics ¶
func (w *OptimizedCacheWrapper) Metrics() *ristretto.Metrics
func (*OptimizedCacheWrapper) Name ¶
func (w *OptimizedCacheWrapper) Name() string
func (*OptimizedCacheWrapper) Set ¶
func (w *OptimizedCacheWrapper) Set(key interface{}, value interface{}, ttl time.Duration) error
func (*OptimizedCacheWrapper) SetMulti ¶
func (w *OptimizedCacheWrapper) SetMulti(items map[interface{}]interface{}, ttl time.Duration) error
func (*OptimizedCacheWrapper) SetWithCost ¶
func (w *OptimizedCacheWrapper) SetWithCost(key interface{}, value interface{}, cost int64, ttl time.Duration) error
type Options ¶
type Options struct {
// NumCounters is the number of 4-bit counters for admission policy (10x max items)
NumCounters int64
// MaxCost is the maximum cost of cache (sum of all items' costs)
MaxCost int64
// BufferItems is the number of keys per Get buffer
BufferItems int64
// Metrics enables cache metrics collection
Metrics bool
// OnEvict is called when an item is evicted from the cache
OnEvict func(item *ristretto.Item)
// OnReject is called when an item is rejected from the cache
OnReject func(item *ristretto.Item)
// OnExit is called when cache.Close() is called
OnExit func(interface{})
// KeyToHash is a custom hash function for keys
KeyToHash func(key interface{}) (uint64, uint64)
// Cost is a function to calculate the cost of a value
Cost func(value interface{}) int64
}
Options represents cache configuration options
type Session ¶
type Session struct {
ID string `json:"id"`
UserID string `json:"user_id"`
Data map[string]interface{} `json:"data"`
ExpiresAt time.Time `json:"expires_at"`
}
Session represents a user session
type SessionCache ¶
type SessionCache struct {
// contains filtered or unexported fields
}
SessionCache demonstrates session management with cache
func NewSessionCache ¶
func NewSessionCache(sessionTTL time.Duration) (*SessionCache, error)
NewSessionCache creates a new session cache
func (*SessionCache) CreateSession ¶
CreateSession creates a new session
func (*SessionCache) DeleteSession ¶
func (s *SessionCache) DeleteSession(sessionID string)
DeleteSession removes a session
func (*SessionCache) GetSession ¶
func (s *SessionCache) GetSession(sessionID string) (*Session, error)
GetSession retrieves a session
func (*SessionCache) UpdateSession ¶
func (s *SessionCache) UpdateSession(session *Session) error
UpdateSession updates session data
type User ¶
type User struct {
ID string `json:"id"`
Name string `json:"name"`
Email string `json:"email"`
Role string `json:"role"`
CreatedAt time.Time `json:"created_at"`
}
User represents a user entity
type UserService ¶
type UserService struct {
// contains filtered or unexported fields
}
UserService demonstrates cache usage in a service layer
func NewUserService ¶
func NewUserService() (*UserService, error)
NewUserService creates a new user service with cache
func (*UserService) GetCacheStats ¶
func (s *UserService) GetCacheStats() string
GetCacheStats returns cache statistics
func (*UserService) GetMultipleUsers ¶
func (s *UserService) GetMultipleUsers(ctx context.Context, userIDs []string) (map[string]*User, error)
GetMultipleUsers demonstrates batch get
func (*UserService) GetUsersByRole ¶
GetUsersByRole demonstrates batch caching
func (*UserService) InvalidateUserCache ¶
func (s *UserService) InvalidateUserCache()
InvalidateUserCache clears all user-related caches
func (*UserService) UpdateUser ¶
func (s *UserService) UpdateUser(ctx context.Context, user *User) error
UpdateUser updates a user and invalidates cache