The HybridCache API bridges some gaps in the IDistributedCache and IMemoryCache APIs. HybridCache is a abstract class with a standard implementation that manages most tasks of saving and retrieving data from the cache.
HybridCache has the following features:
1. A unified API for both in-process and out-of-process caching
HybridCache is designed to be a drop-in replacement for existing IDistributedCache and IMemoryCache usage, and it provides a simple API for adding new caching code. If the app has an IDistributedCache implementation, the HybridCache service uses it for secondary caching. This two-level caching strategy allows HybridCache to provide the speed of an in-memory cache and the durability of a distributed or persistent cache.
2. Stampede protection
The Cache Stampede protection is a mechanism to prevent several users try to update this cache entry at the same time if a cache entry is no longer hot. This mechanism is very useful if there is a lot of load on the store and a cache entry is expired or invalidated. If there is no cache stampede protection on the system, and several users call a category listing at the same time, which is no longer in the cache, then all users would be let through to the database and the server could collapse under the load.
HybridCache combines concurrent operations, ensuring that all requests for a given response wait for the first request to populate the cache.
3. Configurable serialization
Serialization is set up when you register the service, using the WithSerializer and WithSerializerFactory methods that you chain from the AddHybridCache call. By default, the service manages string and byte[] data internally and uses System.Text.Json for other types. You can also configure it to use other serializers like protobuf or XML.
Get the library
Install the Microsoft.Extensions.Caching.Hybrid package
Register the service
Add the HybridCache service to the dependency injection (DI) container by calling AddHybridCache
Get and store cache entries
GetOrCreateAsync
SetAsync
Remove unexpired cache entries
RemoveKeyAsync
RemoveKeysAsync