AuxiliaryLibraries.CacheManager
1.0.6
See the version list below for details.
dotnet add package AuxiliaryLibraries.CacheManager --version 1.0.6
NuGet\Install-Package AuxiliaryLibraries.CacheManager -Version 1.0.6
<PackageReference Include="AuxiliaryLibraries.CacheManager" Version="1.0.6" />
paket add AuxiliaryLibraries.CacheManager --version 1.0.6
#r "nuget: AuxiliaryLibraries.CacheManager, 1.0.6"
// Install AuxiliaryLibraries.CacheManager as a Cake Addin #addin nuget:?package=AuxiliaryLibraries.CacheManager&version=1.0.6 // Install AuxiliaryLibraries.CacheManager as a Cake Tool #tool nuget:?package=AuxiliaryLibraries.CacheManager&version=1.0.6
This library is a wrapper over Redis and uses the StackExchange library for dealing with Redis. The interesting part here is the way of creating cache keys and working easier with Redis.
Table of Contents
- How it works
- Naming convestions
- What does ICacheService have for us
- Configuration
How it works
The instruction for using this library is pretty straightforward. You need to inject an interface called ICacheService into your classes and set some configurations.
Naming convestions
The exciting feature of the library is, there is no need to set the cache key, the naming convention is generated according to the Entity Name and the parameters you passed. There is a very powerful naming convention manager here that reduces lots of time for us to manage our cache keys. The mechanism for creating cache keys is hidden (Encapsulated) in CacheConventions class. It decides what is the cache key based on the information you pass to it. Every key is based on the model you are using. This is the base of every key. Besides, cache keys have other parts as well. The where clause you have when you querying to the database is very important. The order by clause, page number and page size, id, and there are some other arguments for covering every demand.
// The cache key is generated according to the passed parameters to functions.
// Cache key for People
// Example function: GetAllPeople()
var cacheKey = CacheConventions.Cachekey<Person>();
// Cache key for a person with Id number 1
// Example function: GetPersonById(long id)
var cacheKey = CacheConventions.Cachekey<Person>(id: 1);
// Cache key for a people who are Students. To be specific, there is an argument named baseKey for distingushing the keys.
// Example function:
// GetStudents() => _context.People.Where(x => x.Type == PersonType.Student).ToList();
var cacheKey = CacheConventions.Cachekey<Person>(baseKey: "Students");
// Cache key for People who creates after a specific time and sorted descendingly.
// Example function:
// GetValidPeople() => _context.People.Where(x => x.CreateDate > DateTime.Today.AddMonths(2)).OrderByDescending(o => o.CreateDate).ToList();
var cacheKey = CacheConventions.Cachekey<Person>(predicate: x => x.CreateDate > DateTime.Today.AddMonths(2),
orderBy: x => x.OrderByDescending(o => o.CreateDate));
// Cache key for the second 10th page of People who creates after a specific time and sorted descendingly.
// Example function:
// GetValidPeople(int page, int pageSize)
// {
// page = page > 0 ? page - 1 ? 0;
// return _context.People.Where(x => x.CreateDate > DateTime.Today.AddMonths(2))
// .OrderByDescending(o => o.CreateDate).Skip(page * pageSize).Take(pageSize).ToList();
// }
var cacheKey = CacheConventions.Cachekey<Person>(predicate: x => DateTime.Today.AddMonths(2),
orderBy: x => x.OrderByDescending(o => o.CreateDate)
page: 2, pageSize: 10);
// Cache key for People based on the passed query string in http requests
// Example function:
// public IActionResult GetPeople()
// {
// var queryString = Request.QueryString.Value;
// return Ok(_personService.GetPeople(queryString));
// }
var cacheKey = CacheConventions.Cachekey<Person>(queryString: queryString);
// Cache key for People based on the passed request body in http requests
// Example function:
// public IActionResult GetPeople()
// {
// string rawRequestBody = await Request.Content.ReadAsStringAsync();
// return Ok(_personService.GetPeople(rawRequestBody));
// }
var cacheKey = CacheConventions.Cachekey<Person>(raw: requestBody);
// Cache key for People based on ActionExecutingContext or ActionExecutedContext
// This is used inside Action filters
var cacheKey = CacheConventions.Cachekey<Person>(context);
What does ICacheService have for us
Now we have the caceh key. With the help of AuxiliaryLibraries.CacheManager we have a easy access to cashing our data here. Let's dive into caching a little bit deeper.
public class PersonService : IPersonService
{
private readonly ICacheService _cacheService;
public async Task Caching()
{
// Removing value of the cacheKey
_cacheService.Remove(cacheKey);
await _cacheService.RemoveAsync(cacheKey);
_cacheService.RemoveByPattern(cacheKey);
await _cacheService.RemoveByPatternAsync(cacheKey);
// Erease everything we have in our Redis
_cacheService.FlushDatabase();
await _cacheService.FlushDatabaseAsync();
// Caching an object
var _absoluteExpiration = DateTime.Now.AddHours(1);
var _slidingExpiration = DateTime.Now.AddMinutes(10);
_cacheService.Set<Person>(cacheKey, person);
// The AbsoluteExpiration and SlidingExpirationis are setting up based on the configuration you set on appsettings.json. But you can
// change either of them for any reason.
await _cacheService.SetAsync<Person>(cacheKey, person, absoluteExpiration: _absoluteExpiration, slidingExpiration: _slidingExpiration);
_cacheService.Set<Person>(cacheKey, person, absoluteExpiration: _absoluteExpiration, slidingExpiration: _slidingExpiration);
// Try to get a value from cache
if (_cacheService.TryGet<Person>(cacheKey, out var person))
{
person.ToString();
}
// Getting a cached data
var person = _cacheService.Get(cacheKey);
var person = await _cacheService.GetAsync(cacheKey);
}
}
Configuration
Now what we do for the last part is the Configuration. The onlt thing here left to do is to call use caching function in Startup.cs file.
service.UseCache(configuration);
//add this to appsettings.json
"CacheConfiguration": {
"AbsoluteExpirationInHours": 1,
"SlidingExpirationInMinutes": 30,
"Host": "111.111.111.111",
"Port": "80",
"Password": "redis",
"DatabaseID": 1
}
Product | Versions 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. |
-
net8.0
- Microsoft.AspNetCore.Mvc.Core (>= 2.2.5)
- Microsoft.EntityFrameworkCore (>= 7.0.2)
- Microsoft.Extensions.Options.ConfigurationExtensions (>= 7.0.0)
- Newtonsoft.Json (>= 13.0.2)
- StackExchange.Redis (>= 2.6.90)
- System.Linq.Async (>= 6.0.1)
NuGet packages (1)
Showing the top 1 NuGet packages that depend on AuxiliaryLibraries.CacheManager:
Package | Downloads |
---|---|
AuxiliaryLibraries.GenericRepository.Core
Generic Repository and Unit of Work Pattern including Cache Handling. With the help of this library you implement your projects faster. You can get rid of implementing CRUD operations for all of your entities and focus on implementing logic of your projec. |
GitHub repositories
This package is not used by any popular GitHub repositories.