Skip to main content
Version: 1.0.1

Caching.Redis

What is Caching?

Caching is a temporary storage mechanism that allows websites to load information faster. Instead of accessing the database directly, the website will access the cached version and pull the necessary information from the server memory. We make use of some solutions for caching operations. One of them and the most popular is Redis. Redis is an open source (BSD licensed), in-memory data structure store used as a database, cache, message broker, and streaming engine. Library use the StackExchange.Redis library to take advantage of Redis.

You can install Redis from here.

Usage

Add necessary components to service collection.


var cacheOptions = new RedisCacheServiceOptions("connectionString");

cacheOptions.ConfigurationOptions.AbortOnConnectFail = false;
cacheOptions.ConfigurationOptions.ConnectTimeout = 10000;
cacheOptions.ConfigurationOptions.SyncTimeout = 10000;
cacheOptions.ConfigurationOptions.ConnectRetry = 1;
cacheOptions.Lifetime = ServiceLifetime.Singleton;
cacheOptions.UseUtcForExpirationDates = false;

services.AddMilvaRedisCaching(cacheOptions);

Now you can use IRedisCacheService interface for caching operations.


...

private readonly IRedisCacheService _cacheService;

public AccountService(IRedisCacheService cacheService) => _cacheService = cacheService;

public async Task SetKeyAsync()
{
var product = new Product
{
Id = 1,
Name = "Tea"
};

await _cacheService.PerformRedisActionAsync(async () =>
{
await _cacheService.SetAsync(product.Id, product);

var cachedProduct = await _cacheService.GetAsync<Product>(product.Id);

}, nameof(LocalizerKey.AnErrorOccured), _milvaLogger);
}

PerformRedisAction Method : It performs the requested redis action in try catch blocks. If redis client not connected, connects. If an error occurs when performing action or connecting to redis, it throws the MilvaUserFriendlyException error along with the message key. Provides logging if logger parameter is not null.

You can see other methods from here.