Hybrid cache can use both memory cache and distributed cache, which can improve cache hit rate and reduce access to distributed cache, thereby improving performance.

  • When getting data from the cache, it will first get the data from the memory cache, if there is no data in the memory cache, it will get the data from the distributed cache.
  • When writing data to the cache, it writes data to both the in-memory cache and the distributed cache.

Service 1 ---->  HybridCache  ---->  MemoryCache  ---->  DistributedCache

https://learn.microsoft.com/zh-cn/azure/architecture/best-practices/caching

Installation package

dotnet add package Microsoft.Extensions.Caching.Hybrid

Configuration service

builder.Services.AddHybridCache();

Use the service

public class SomeService(HybridCache cache)
{
    private HybridCache _cache = cache;

    public async Task<string> GetSomeInfoAsync(string name, int id, CancellationToken token = default)
    {
        return await _cache.GetOrCreateAsync( $"{name}-{id}",async cancel => await GetDataFromTheSourceAsync(name, id, cancel),cancellationToken: token );
    }

    public async Task<string> GetDataFromTheSourceAsync(string name, int id, CancellationToken token)
    {
        string someInfo = $"someinfo-{name}-{id}";
        return someInfo;
    }
}

Remove cache entries by tag

public class SomeService(HybridCache cache)
{
    private HybridCache _cache = cache;

    public async Task<string> GetSomeInfoAsync(string name, int id, CancellationToken token = default)
    {
        var tags = new List<string> { "tag1", "tag2", "tag3" };
        var entryOptions = new HybridCacheEntryOptions
        {
            Expiration = TimeSpan.FromMinutes(1),
            LocalCacheExpiration = TimeSpan.FromMinutes(1)
        };
        return await _cache.GetOrCreateAsync(
            $"{name}-{id}", // Unique key to the cache entry
            async cancel => await GetDataFromTheSourceAsync(name, id, cancel),
            entryOptions,
            tags,
            cancellationToken: token
        );
    }
    
    public async Task<string> GetDataFromTheSourceAsync(string name, int id, CancellationToken token)
    {
        string someInfo = $"someinfo-{name}-{id}";
        return someInfo;
    }

    public async Task RemoveByTagAsync(string tag)
    {
        await _cache.RemoveByTagAsync(tag);
    }
}