caching library

Contains classes and abstractions for caching data in memory and distributed systems.

This library provides a comprehensive caching solution inspired by Microsoft.Extensions.Caching, offering both in-memory and distributed caching capabilities with features like:

  • Multiple expiration strategies (absolute, sliding, change token-based)
  • Priority-based eviction policies
  • Size-based capacity management
  • Post-eviction callbacks
  • Statistics tracking
  • Type-safe generic APIs

Memory Caching

Use IMemoryCache for fast, in-memory caching of objects:

final cache = MemoryCache(MemoryCacheOptions());

// Simple set/get
cache.set('key', 'value');
final value = cache.get<String>('key');

// With expiration
cache.set('key', 'value', MemoryCacheEntryOptions()
  ..absoluteExpirationRelativeToNow = Duration(minutes: 5));

// Get or create pattern
final data = await cache.getOrCreateAsync<String>('key', (entry) async {
  entry.slidingExpiration = Duration(minutes: 15);
  return await fetchDataFromApi();
});

Distributed Caching

Use IDistributedCache for distributed caching across multiple servers:

final cache = MemoryDistributedCache(MemoryDistributedCacheOptions());

// Store bytes
await cache.set('key', utf8.encode('value'));

// Store strings
await cache.setString('key', 'value', DistributedCacheEntryOptions()
  ..slidingExpiration = Duration(hours: 1));

// Retrieve data
final value = await cache.getString('key');

Classes

DistributedCacheEntryOptions
Provides options for configuring distributed cache entries.
ICacheEntry
Represents an entry in the IMemoryCache.
IDistributedCache
Represents a distributed cache of serialized values.
IMemoryCache
Represents a local in-memory cache whose values are not serialized.
MemoryCache
Implementation of IMemoryCache.
MemoryCacheEntryOptions
Provides options for configuring memory cache entries.
MemoryCacheOptions
Provides configuration options for MemoryCache.
MemoryCacheStatistics
Holds statistics for the memory cache.
MemoryDistributedCache
An implementation of IDistributedCache using an in-memory cache.
PostEvictionCallbackRegistration
Registration for a callback that should be called when a cache entry is evicted.

Enums

CacheItemPriority
Specifies how items are prioritized for preservation during a memory pressure triggered cleanup.
EvictionReason
Specifies the reason why a cache entry was evicted.

Extensions

CacheEntryCommit on ICacheEntry
Extension to finalize cache entries after they're configured.
DistributedCacheExtensions on IDistributedCache
Extension methods for IDistributedCache.
MemoryCacheExtensions on IMemoryCache
Extension methods for IMemoryCache.

Typedefs

PostEvictionDelegate = void Function(Object key, Object? value, EvictionReason reason, Object? state)
Signature for callbacks that are called when a cache entry is evicted.