Documentation ¶
Index ¶
Constants ¶
const DefaultTTL = 1 * time.Hour
DefaultTTL is the default time-to-live duration for cache items.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Item ¶
type Item[Key comparable, Value any] struct { Key Key // Key is a unique identifier for the item. Value Value // Value is the data associated with the item. ExpiresAt time.Time // ExpiresAt is the time at which the item is considered expired. }
Item represents a generic item that can be stored in a priority queue. It contains a key of type Key, a value of type Value, an expiration time, and an index for heap management.
type MemoryCache ¶
type MemoryCache[K comparable, V any] struct { // contains filtered or unexported fields }
MemoryCache represents an in-memory cache with TTL support.
func NewMemoryCache ¶
func NewMemoryCache[K comparable, V any](ctx context.Context, ttl time.Duration) *MemoryCache[K, V]
NewMemoryCache creates a new MemoryCache instance. It initializes the cache with the provided context and starts a background goroutine that periodically deletes expired items from the cache.
func (*MemoryCache[K, V]) Contains ¶
func (m *MemoryCache[K, V]) Contains(key K) bool
Contains checks if a given key exists in the cache. This method acquires a lock to ensure thread safety while accessing the cache and then checks if the key is present in the map of cached items.
func (*MemoryCache[K, V]) Get ¶
func (m *MemoryCache[K, V]) Get(key K) (V, bool)
Get retrieves an item from the cache by its key. If the item is found and has not expired, it is returned along with a boolean true. If the item is not found or has expired, the zero value and boolean false are returned.
func (*MemoryCache[K, V]) Len ¶
func (m *MemoryCache[K, V]) Len() int
Len returns the number of items currently stored in the cache. This method is thread-safe and uses a read lock to ensure that the count is accurate without blocking other read operations.
func (*MemoryCache[K, V]) Remove ¶
func (m *MemoryCache[K, V]) Remove(key K) bool
Remove removes an item from the cache by its key. This method is thread-safe and ensures that the item is properly removed from both the list and the map, as well as from the expiration buckets map. It returns true if the item was found and removed, and false if the key does not exist in the cache.
func (*MemoryCache[K, V]) Set ¶
func (m *MemoryCache[K, V]) Set(key K, value V, ttl time.Duration)
Set adds or updates an item in the cache with the specified key, value, and TTL (time-to-live). If the TTL is zero, the default TTL is used. This method is thread-safe and ensures that the cache is updated atomically.