Fingent-Redis-Cache 1.0.1

dotnet add package Fingent-Redis-Cache --version 1.0.1
                    
NuGet\Install-Package Fingent-Redis-Cache -Version 1.0.1
                    
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="Fingent-Redis-Cache" Version="1.0.1" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Fingent-Redis-Cache" Version="1.0.1" />
                    
Directory.Packages.props
<PackageReference Include="Fingent-Redis-Cache" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add Fingent-Redis-Cache --version 1.0.1
                    
#r "nuget: Fingent-Redis-Cache, 1.0.1"
                    
#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.
#:package Fingent-Redis-Cache@1.0.1
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=Fingent-Redis-Cache&version=1.0.1
                    
Install as a Cake Addin
#tool nuget:?package=Fingent-Redis-Cache&version=1.0.1
                    
Install as a Cake Tool

Fingent Redis Cache

A lightweight Redis-based caching library for .NET applications. Provides a fast, distributed cache layer to improve application scalability and performance. Built on top of StackExchange.Redis with seamless integration for ASP.NET Core and custom .NET projects.

?? Features

  • Distributed Caching: Share cache across multiple application instances
  • High Performance: Redis-powered fast data access with sub-millisecond latency
  • Scalable: Horizontal scaling support for high-traffic applications
  • JSON Serialization: Automatic object serialization/deserialization
  • Expiration Policies: Flexible TTL and expiration strategies
  • Connection Resilience: Automatic reconnection and error handling
  • Pub/Sub Support: Real-time messaging capabilities
  • Data Types: Support for strings, hashes, lists, sets, and sorted sets

?? Installation

dotnet add package Fingent-Redis-Cache

?? Dependencies

  • .NET 8.0
  • Microsoft.Extensions.Caching.Abstractions 8.0.0
  • Microsoft.Extensions.Caching.StackExchangeRedis 8.0.8
  • Microsoft.Extensions.Logging.Abstractions 8.0.1

?? Usage

Basic Setup

// Program.cs or Startup.cs
services.AddStackExchangeRedisCache(options =>
{
    options.Configuration = "localhost:6379";
    options.InstanceName = "MyApp";
});

services.AddRedisCaching();

Simple Caching

public class ProductService
{
    private readonly IDistributedCache _cache;
    private readonly ILogger<ProductService> _logger;
    
    public ProductService(IDistributedCache cache, ILogger<ProductService> logger)
    {
        _cache = cache;
        _logger = logger;
    }
    
    public async Task<Product> GetProductAsync(int id)
    {
        string cacheKey = $"product_{id}";
        
        var cachedProduct = await _cache.GetStringAsync(cacheKey);
        if (cachedProduct != null)
        {
            _logger.LogInformation("Cache hit for product {ProductId}", id);
            return JsonSerializer.Deserialize<Product>(cachedProduct);
        }
        
        _logger.LogInformation("Cache miss for product {ProductId}", id);
        var product = await GetProductFromDatabaseAsync(id);
        
        var serializedProduct = JsonSerializer.Serialize(product);
        await _cache.SetStringAsync(cacheKey, serializedProduct, new DistributedCacheEntryOptions
        {
            AbsoluteExpirationRelativeToNow = TimeSpan.FromHours(1)
        });
        
        return product;
    }
}

Advanced Redis Operations

public class RedisCacheService
{
    private readonly IDatabase _database;
    private readonly ILogger<RedisCacheService> _logger;
    
    public RedisCacheService(IConnectionMultiplexer connectionMultiplexer, ILogger<RedisCacheService> logger)
    {
        _database = connectionMultiplexer.GetDatabase();
        _logger = logger;
    }
    
    // Generic get/set with automatic serialization
    public async Task<T> GetAsync<T>(string key) where T : class
    {
        var value = await _database.StringGetAsync(key);
        return value.HasValue ? JsonSerializer.Deserialize<T>(value) : null;
    }
    
    public async Task SetAsync<T>(string key, T value, TimeSpan? expiry = null) where T : class
    {
        var serializedValue = JsonSerializer.Serialize(value);
        await _database.StringSetAsync(key, serializedValue, expiry);
    }
    
    // Hash operations
    public async Task SetHashAsync(string key, string field, string value)
    {
        await _database.HashSetAsync(key, field, value);
    }
    
    public async Task<string> GetHashAsync(string key, string field)
    {
        return await _database.HashGetAsync(key, field);
    }
    
    // List operations
    public async Task AddToListAsync(string key, string value)
    {
        await _database.ListRightPushAsync(key, value);
    }
    
    public async Task<string[]> GetListAsync(string key)
    {
        var values = await _database.ListRangeAsync(key);
        return values.Select(v => v.ToString()).ToArray();
    }
    
    // Set operations
    public async Task AddToSetAsync(string key, string value)
    {
        await _database.SetAddAsync(key, value);
    }
    
    public async Task<bool> IsInSetAsync(string key, string value)
    {
        return await _database.SetContainsAsync(key, value);
    }
}

Configuration Options

// Basic configuration
services.AddStackExchangeRedisCache(options =>
{
    options.Configuration = "localhost:6379";
    options.InstanceName = "MyApp";
});

// Advanced configuration
services.AddStackExchangeRedisCache(options =>
{
    options.ConfigurationOptions = new ConfigurationOptions
    {
        EndPoints = { "localhost:6379", "redis-cluster-2:6379" },
        Password = "your-redis-password",
        ConnectTimeout = 5000,
        SyncTimeout = 5000,
        AsyncTimeout = 5000,
        ConnectRetry = 3,
        AbortOnConnectFail = false,
        ReconnectRetryPolicy = new ExponentialRetry(5000),
        DefaultDatabase = 0
    };
    options.InstanceName = "MyApp";
});

// Connection multiplexer registration
services.AddSingleton<IConnectionMultiplexer>(provider =>
{
    var configuration = provider.GetService<IConfiguration>();
    var connectionString = configuration.GetConnectionString("Redis");
    return ConnectionMultiplexer.Connect(connectionString);
});

Cache Patterns

public class CachePatternService
{
    private readonly IDistributedCache _cache;
    private readonly IDatabase _database;
    
    public CachePatternService(IDistributedCache cache, IConnectionMultiplexer connectionMultiplexer)
    {
        _cache = cache;
        _database = connectionMultiplexer.GetDatabase();
    }
    
    // Cache-Aside Pattern
    public async Task<User> GetUserCacheAsideAsync(int userId)
    {
        var cacheKey = $"user:{userId}";
        var cachedUser = await _cache.GetStringAsync(cacheKey);
        
        if (cachedUser != null)
        {
            return JsonSerializer.Deserialize<User>(cachedUser);
        }
        
        var user = await GetUserFromDatabaseAsync(userId);
        if (user != null)
        {
            var serialized = JsonSerializer.Serialize(user);
            await _cache.SetStringAsync(cacheKey, serialized, TimeSpan.FromMinutes(30));
        }
        
        return user;
    }
    
    // Write-Through Pattern
    public async Task UpdateUserWriteThroughAsync(User user)
    {
        // Update database first
        await UpdateUserInDatabaseAsync(user);
        
        // Then update cache
        var cacheKey = $"user:{user.Id}";
        var serialized = JsonSerializer.Serialize(user);
        await _cache.SetStringAsync(cacheKey, serialized, TimeSpan.FromMinutes(30));
    }
    
    // Write-Behind Pattern (with background service)
    public async Task UpdateUserWriteBehindAsync(User user)
    {
        // Update cache immediately
        var cacheKey = $"user:{user.Id}";
        var serialized = JsonSerializer.Serialize(user);
        await _cache.SetStringAsync(cacheKey, serialized, TimeSpan.FromMinutes(30));
        
        // Queue for background database update
        await _database.ListRightPushAsync("user_updates", JsonSerializer.Serialize(user));
    }
}

Session Management

public class SessionService
{
    private readonly IDatabase _database;
    
    public SessionService(IConnectionMultiplexer connectionMultiplexer)
    {
        _database = connectionMultiplexer.GetDatabase();
    }
    
    public async Task CreateSessionAsync(string sessionId, UserSession session, TimeSpan expiry)
    {
        var key = $"session:{sessionId}";
        var sessionData = JsonSerializer.Serialize(session);
        await _database.StringSetAsync(key, sessionData, expiry);
    }
    
    public async Task<UserSession> GetSessionAsync(string sessionId)
    {
        var key = $"session:{sessionId}";
        var sessionData = await _database.StringGetAsync(key);
        
        return sessionData.HasValue 
            ? JsonSerializer.Deserialize<UserSession>(sessionData) 
            : null;
    }
    
    public async Task ExtendSessionAsync(string sessionId, TimeSpan additionalTime)
    {
        var key = $"session:{sessionId}";
        await _database.KeyExpireAsync(key, additionalTime);
    }
    
    public async Task InvalidateSessionAsync(string sessionId)
    {
        var key = $"session:{sessionId}";
        await _database.KeyDeleteAsync(key);
    }
}

Pub/Sub Messaging

public class RedisMessagingService
{
    private readonly ISubscriber _subscriber;
    private readonly ILogger<RedisMessagingService> _logger;
    
    public RedisMessagingService(IConnectionMultiplexer connectionMultiplexer, ILogger<RedisMessagingService> logger)
    {
        _subscriber = connectionMultiplexer.GetSubscriber();
        _logger = logger;
    }
    
    public async Task PublishAsync<T>(string channel, T message)
    {
        var serializedMessage = JsonSerializer.Serialize(message);
        await _subscriber.PublishAsync(channel, serializedMessage);
        _logger.LogInformation("Published message to channel {Channel}", channel);
    }
    
    public async Task SubscribeAsync<T>(string channel, Action<T> onMessage)
    {
        await _subscriber.SubscribeAsync(channel, (ch, message) =>
        {
            try
            {
                var deserializedMessage = JsonSerializer.Deserialize<T>(message);
                onMessage(deserializedMessage);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error processing message from channel {Channel}", channel);
            }
        });
        
        _logger.LogInformation("Subscribed to channel {Channel}", channel);
    }
}

?? Performance Optimization

Connection Pooling

// Singleton connection multiplexer for connection pooling
services.AddSingleton<IConnectionMultiplexer>(provider =>
{
    var configuration = "localhost:6379";
    return ConnectionMultiplexer.Connect(configuration);
});

Batch Operations

public async Task SetMultipleAsync(Dictionary<string, string> keyValuePairs)
{
    var batch = _database.CreateBatch();
    var tasks = new List<Task>();
    
    foreach (var kvp in keyValuePairs)
    {
        tasks.Add(batch.StringSetAsync(kvp.Key, kvp.Value));
    }
    
    batch.Execute();
    await Task.WhenAll(tasks);
}

??? Architecture

The Redis caching system provides:

  • Distributed Architecture: Shared cache across multiple instances
  • High Availability: Master-slave replication and clustering support
  • Persistence: Optional data persistence to disk
  • Memory Efficiency: Optimized memory usage with various data structures

????? Author

Frebin Francis
Fingent Technology Solutions Pvt Ltd

?? License

Copyright � 2025 Fingent Technology Solutions Pvt Ltd

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 was computed.  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.  net10.0 was computed.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
1.0.1 191 9/24/2025