HybridRedisCache 3.0.0
See the version list below for details.
dotnet add package HybridRedisCache --version 3.0.0
NuGet\Install-Package HybridRedisCache -Version 3.0.0
<PackageReference Include="HybridRedisCache" Version="3.0.0" />
paket add HybridRedisCache --version 3.0.0
#r "nuget: HybridRedisCache, 3.0.0"
// Install HybridRedisCache as a Cake Addin #addin nuget:?package=HybridRedisCache&version=3.0.0 // Install HybridRedisCache as a Cake Tool #tool nuget:?package=HybridRedisCache&version=3.0.0
HybridRedisCache
HybridRedisCache
is a simple in-memory and Redis hybrid caching solution for .NET applications.
It provides a way to cache frequently accessed data in memory for fast access and automatically falls back to using Redis as a persistent cache when memory cache capacity is exceeded.
Types of Cache
Basically, there are two types of caching .NET Core supports
- In-Memory Caching
- Distributed Caching
When we use In-Memory Cache then in that case data is stored in the application server memory and whenever we need then we fetch data from that and use it wherever we need it. And in Distributed Caching there are many third-party mechanisms like Redis and many others. But in this section, we work with the Redis Cache in the .NET Core.
Distributed Caching
Basically, in distributed caching data are stored and shared between multiple servers Also, it’s easy to improve the scalability and performance of the application after managing the load between multiple servers when we use a multi-tenant application Suppose, In the future, if one server crashes and restarts then the application does not have any impact because multiple servers are as per our need if we want Redis is the most popular cache which is used by many companies nowadays to improve the performance and scalability of the application. So, we are going to discuss Redis and its usage one by one.
Redis Cache
Redis is an Open Source (BSD Licensed) in-memory Data Structure store used as a database. Basically, it is used to store the frequently used and some static data inside the cache and use and reserve that as per user requirement. There are many data structures present in the Redis that we are able to use like List, Set, Hashing, Stream, and many more to store the data.
Redis vs. In-Memory caching in single instance benchmark
Installation
You can install the HybridRedisCache
package using NuGet:
PM> Install-Package HybridRedisCache
Installing via the .NET Core command line interface:
dotnet add package HybridRedisCache
Usage
Simple usage in console applications
To use HybridCache
, you can create an instance of the HybridCache
class and then call its Set
and Get
methods to cache and retrieve data, respectively.
Here's an example:
using HybridRedisCache;
...
// Create a new instance of HybridCache with cache options
var options = new HybridCachingOptions()
{
DefaultLocalExpirationTime = TimeSpan.FromMinutes(1),
DefaultDistributedExpirationTime = TimeSpan.FromDays(1),
InstancesSharedName = "SampleApp",
ThrowIfDistributedCacheError = true,
RedisConnectString = "localhost",
BusRetryCount = 10,
EnableLogging = true,
EnableTracing = true,
ThreadPoolSocketManagerEnable = true,
FlushLocalCacheOnBusReconnection = true,
TracingActivitySourceName = nameof(HybridRedisCache),
// just set SupportOldInvalidateBus true, if you have old version of HybridRedisCache
// to keep consistency between old and new versions
SupportOldInvalidateBus = false
};
var cache = new HybridCache(options);
// Cache a string value with the key "mykey" for 1 minute
cache.Set("mykey", "myvalue", TimeSpan.FromMinutes(1));
// Retrieve the cached value with the key "mykey"
var value = cache.Get<string>("mykey");
// Retrieve the cached value with the key "mykey"
// If not exist create one by dataRetriever method
var value = await cache.GetAsync("mykey",
dataRetriever: async key => await CreateValueTaskAsync(key, ...),
localExpiry: TimeSpan.FromMinutes(1),
redisExpiry: TimeSpan.FromHours(6),
fireAndForget: true);
Configure Startup class for Web APIs
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddHybridRedisCaching(options =>
{
options.AbortOnConnectFail = false;
options.InstancesSharedName = "RedisCacheSystem.Demo";
options.DefaultLocalExpirationTime = TimeSpan.FromMinutes(1);
options.DefaultDistributedExpirationTime = TimeSpan.FromDays(10);
options.ThrowIfDistributedCacheError = true;
options.RedisConnectionString = "localhost:6379,redis0:6380,redis1:6380,allowAdmin=true,keepAlive=180";
options.BusRetryCount = 10;
options.EnableLogging = true;
options.EnableTracing = true,
ThreadPoolSocketManagerEnable = true,
TracingActivitySourceName = nameof(HybridRedisCache),
options.FlushLocalCacheOnBusReconnection = true;
});
Write code in your controller
[Route("api/[controller]")]
public class WeatherForecastController : Controller
{
private readonly IHybridCache _cacheService;
public VWeatherForecastController(IHybridCache cacheService)
{
this._cacheService = cacheService;
}
[HttpGet]
public string Handle()
{
//Set
_cacheService.Set("demo", "123", TimeSpan.FromMinutes(1));
//Set Async
await _cacheService.SetAsync("demo", "123", TimeSpan.FromMinutes(1));
}
[HttpGet)]
public async Task<WeatherForecast> Get(int id)
{
var data = await _cacheService.GetAsync<WeatherForecast>(id);
return data;
}
[HttpGet)]
public IEnumerable<WeatherForecast> Get()
{
var data = _cacheService.Get<IEnumerable<WeatherForecast>>("demo");
return data;
}
}
Features
HybridCache
is a caching library that provides a number of advantages over traditional in-memory
caching solutions.
One of its key features is the ability to persist caches between instances and sync data for all instances.
With HybridCache
, you can create multiple instances of the cache that share the same Redis
cache,
allowing you to scale out your application and distribute caching across multiple instances.
This ensures that all instances of your application have access to the same cached data,
regardless of which instance originally created the cache.
When a value is set in the cache using one instance, the cache invalidation message is sent to all other instances, ensuring that the cached data is synchronized across all instances. This allows you to take advantage of the benefits of caching, such as reduced latency and improved performance, while ensuring that the cached data is consistent across all instances.
Other features of HybridCache
include:
- Multiple cache layers: Supports both in-memory and Redis caching layers, allowing for flexible caching strategies.
- Automatic expiration: Cached data can automatically expire based on time-to-live (TTL) or sliding expiration policies.
- Fire-and-forget caching: Enables quickly setting a value in the cache without waiting for a response, improving performance for non-critical cache operations.
- Asynchronous caching operations: Provides asynchronous cache operations to enhance application responsiveness and scalability.
- Distributed key locking: Ensures control over race conditions across multiple services, preventing conflicts with shared resources.
- Client synchronization with Redis messages: Keeps all clients in sync through Redis bus messages. For example, if a key is updated or removed by one client, other clients will automatically clear the key from their local cache, ensuring consistency across instances.
Overall, HybridCache
provides a powerful and flexible caching solution that helps enhance the performance and scalability of your applications while ensuring that cached data remains consistent across all instances.
When should I enable caching?
Each time the value of a cached key is modified in the database, Redis pushes an invalidation message to all the clients that are caching the key. This tells the clients to flush the key’s locally cached value, which is invalid. This behavior implies a trade-off between local cache hits and invalidation messages: keys that show a local cache hit rate greater than the invalidation message rate are the best candidates for local tracking and caching.
Installation of Redis Cache with docker
Step 1
Install docker on your OS.
Step 2
Open bash and type below commands:
$ docker pull redis:latest
$ docker run --name redis -p 6379:6379 -d redis:latest
Test is redis running:
$ docker exec -it redis redis-cli
$ ping
Contributing
Contributions are welcome! If you find a bug or have a feature request, please open an issue or submit a pull request.
If you'd like to contribute to HybridRedisCache
, please follow these steps:
- Fork the repository.
- Create a new branch for your changes.
- Make your changes and commit them.
- Push your changes to your fork.
- Submit a pull request.
License
HybridRedisCache
is licensed under the Apache License, Version 2.0. See the LICENSE file for more information.
Product | Versions Compatible and additional computed target framework versions. |
---|---|
.NET | net6.0 is compatible. net6.0-android was computed. net6.0-ios was computed. net6.0-maccatalyst was computed. net6.0-macos was computed. net6.0-tvos was computed. net6.0-windows was computed. net7.0 was computed. net7.0-android was computed. net7.0-ios was computed. net7.0-maccatalyst was computed. net7.0-macos was computed. net7.0-tvos was computed. net7.0-windows was computed. 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. |
-
net6.0
- Microsoft.Extensions.Caching.Memory (>= 8.0.1)
- Newtonsoft.Json (>= 13.0.3)
- StackExchange.Redis (>= 2.8.16)
-
net8.0
- Microsoft.Extensions.Caching.Memory (>= 8.0.1)
- Newtonsoft.Json (>= 13.0.3)
- StackExchange.Redis (>= 2.8.16)
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 |
---|---|---|
3.0.4 | 102 | 12/1/2024 |
3.0.3 | 100 | 12/1/2024 |
3.0.2 | 141 | 11/9/2024 |
3.0.1 | 91 | 11/9/2024 |
3.0.0 | 87 | 11/9/2024 |
2.4.3 | 170 | 11/2/2024 |
2.4.2 | 94 | 10/31/2024 |
2.4.1 | 89 | 10/30/2024 |
2.4.0 | 83 | 10/30/2024 |
2.3.1 | 14,457 | 4/27/2024 |
2.2.4 | 1,976 | 1/15/2024 |
2.2.3 | 166 | 1/3/2024 |
2.2.2 | 138 | 1/3/2024 |
2.2.1 | 139 | 1/3/2024 |
2.2.0 | 144 | 1/3/2024 |
2.1.0 | 149 | 12/31/2023 |
2.0.2 | 158 | 12/18/2023 |
2.0.1 | 149 | 12/12/2023 |
2.0.0 | 142 | 12/9/2023 |
1.9.0 | 154 | 12/8/2023 |
1.8.0 | 124 | 12/6/2023 |
1.6.0 | 145 | 12/4/2023 |
1.5.0 | 177 | 10/31/2023 |
1.4.0 | 161 | 10/15/2023 |
1.3.1 | 132 | 10/8/2023 |
1.3.0 | 140 | 9/10/2023 |
1.2.4 | 237 | 5/7/2023 |
1.2.3 | 149 | 5/5/2023 |
1.2.2 | 143 | 5/5/2023 |
1.2.1 | 133 | 5/5/2023 |
1.2.0 | 139 | 5/5/2023 |
1.1.1 | 146 | 5/4/2023 |
1.1.0 | 164 | 5/3/2023 |
1.0.9 | 151 | 5/1/2023 |
1.0.8 | 169 | 5/1/2023 |
1.0.7 | 161 | 4/30/2023 |
1.0.6 | 158 | 4/29/2023 |
1.0.5 | 163 | 4/29/2023 |
1.0.4 | 163 | 4/28/2023 |
1.0.3 | 167 | 4/28/2023 |
1.0.2 | 183 | 4/17/2023 |
1.0.1 | 170 | 4/16/2023 |
1.0.0 | 174 | 4/16/2023 |
* Major update to invalidate expired and removed and change keys
* Use KeySpace bus feature to sync and track local caches
* Add SupportOldInvalidateBus option to keep consistency between this and older versions
* fixed remove by pattern issue with Lua scripts on Redis server-side
* improve set performance with keyspace