CacheFlow 0.0.7

dotnet add package CacheFlow --version 0.0.7                
NuGet\Install-Package CacheFlow -Version 0.0.7                
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="CacheFlow" Version="0.0.7" />                
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add CacheFlow --version 0.0.7                
#r "nuget: CacheFlow, 0.0.7"                
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
// Install CacheFlow as a Cake Addin
#addin nuget:?package=CacheFlow&version=0.0.7

// Install CacheFlow as a Cake Tool
#tool nuget:?package=CacheFlow&version=0.0.7                

CacheFlow

A high-performance, thread-safe, multi-layer caching library for .NET with advanced features including cache stampede protection and distributed caching support.

Features

  • 🚀 High Performance: Optimized for speed and efficiency
  • 🔒 Thread-safe Operations: Safe for concurrent access
  • 📦 Multi-layer Caching: Combine memory and distributed caching
  • 🛡️ Cache Stampede Protection: Prevent thundering herd problems
  • 🏷️ Tag-based Operations: Group and manage related cache entries
  • 📊 Advanced Monitoring: Comprehensive metrics and insights
  • 🔄 Flexible Serialization: Customizable serialization options
  • 💾 Memory Pressure Handling: Automatic memory management
  • 📝 Comprehensive Logging: Detailed operation tracking
  • 🌐 Distributed Cache Support: Scale across multiple nodes

Installation

dotnet add package CacheFlow

Quick Start

// Configure services
services.AddCacheFlow(options =>
{
    options.EnableLogging = true;
    options.EnableMetrics = true;
    options.DefaultDuration = TimeSpan.FromMinutes(10);
});

// Use in your code
public class ProductService
{
    private readonly CacheFlowManager _cache;

    public ProductService(CacheFlowManager cache)
    {
        _cache = cache;
    }

    public async Task<Product> GetProductAsync(string productId)
    {
        return await _cache.GetOrCreateAsync(
            $"product:{productId}",
            productId,
            async (id, ct) => await FetchProductFromDatabase(id),
            new CacheFlowEntryOptions
            {
                Duration = TimeSpan.FromHours(1),
                Tags = new[] { "products" }
            }
        );
    }
}

Configuration Options

Option Description Default
DefaultDuration Default cache duration 30 minutes
EnableLogging Enable detailed logging true
EnableMetrics Enable performance metrics true
MaxMemorySize Maximum memory cache size null (no limit)
SerializerType Type of serializer to use JSON

Cache Operations

Basic Operations

// Set a value
await _cache.SetAsync("key", value);

// Get a value
var result = await _cache.GetOrCreateAsync("key", factory);

// Remove a value
await _cache.RemoveAsync("key");

Tag-based Operations

// Set with tags
await _cache.SetAsync(
    "product:1",
    product,
    new CacheFlowEntryOptions
    {
        Tags = new[] { "products", "active" }
    }
);

// Remove by tag
await _cache.RemoveByTagAsync("products");

Advanced Features

// Custom serialization
services.AddCacheFlow()
        .WithCustomSerializer<MyCustomSerializer>();

// Memory pressure handling
services.AddCacheFlow(options =>
{
    options.MemoryPressureMonitoringEnabled = true;
    options.MaxMemorySize = 1024 * 1024 * 100; // 100MB
});

// Metrics collection
services.AddCacheFlow(options =>
{
    options.EnableMetrics = true;
    options.MetricsUpdateInterval = TimeSpan.FromSeconds(5);
});

Best Practices

  1. Performance Optimization

    • Use appropriate cache durations
    • Implement cache stampede protection
    • Monitor memory usage
  2. Data Management

    • Use tags for related items
    • Implement cache invalidation strategy
    • Handle cache misses gracefully
  3. Monitoring

    • Enable logging for debugging
    • Track cache hit/miss ratios
    • Monitor memory pressure

Integration Examples

ASP.NET Core Controller

[ApiController]
[Route("api/[controller]")]
public class ProductsController : ControllerBase
{
    private readonly CacheFlowManager _cache;

    public ProductsController(CacheFlowManager cache)
    {
        _cache = cache;
    }

    [HttpGet("{id}")]
    public async Task<IActionResult> GetProduct(string id)
    {
        var product = await _cache.GetOrCreateAsync(
            $"product:{id}",
            id,
            async (pid, ct) => await _repository.GetProductAsync(pid),
            new CacheFlowEntryOptions
            {
                Duration = TimeSpan.FromHours(1),
                Tags = new[] { "products" }
            }
        );

        return Ok(product);
    }
}

Background Service

public class CacheMaintenanceService : BackgroundService
{
    private readonly CacheFlowManager _cache;
    private readonly ILogger<CacheMaintenanceService> _logger;

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        while (!stoppingToken.IsCancellationRequested)
        {
            try
            {
                // Cleanup expired products
                await _cache.RemoveByTagAsync("expired-products");
                await Task.Delay(TimeSpan.FromHours(1), stoppingToken);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error during cache maintenance");
            }
        }
    }
}

Advanced Scenarios

Distributed Caching

services.AddCacheFlow()
        .AddDistributedCache(options =>
        {
            options.InstanceName = "MyApp";
            options.SyncTimeout = TimeSpan.FromSeconds(5);
        });

Custom Cache Entry Options

var options = new CacheFlowEntryOptions
{
    SlidingExpiration = true,
    Priority = CachePriority.High,
    Duration = TimeSpan.FromHours(1),
    Tags = new[] { "products", "featured" }
};

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

License

This project is licensed under the terms mentioned in the package.

Product Compatible and additional computed target framework versions.
.NET net8.0 is compatible.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 is compatible.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages (1)

Showing the top 1 NuGet packages that depend on CacheFlow:

Package Downloads
CacheFlow.CircuitBreaker

CacheFlow.CircuitBreaker extends CacheFlow with robust circuit breaker capabilities: - Thread-safe circuit breaker implementation - Configurable failure thresholds - Adjustable sampling windows - Automatic recovery mechanisms - Sliding window failure counting - Comprehensive failure tracking - Intelligent state management - Exception-based circuit breaking - Decorator pattern integration - Detailed failure logging Perfect for applications requiring resilient caching with failure protection.

GitHub repositories

This package is not used by any popular GitHub repositories.