Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Redis

Xây dựng Hybrid Cache trong .NET 9 với Redis: Unified In-Memory và Distributed Caching

Hybrid cache

Hybrid cache là một unified library cho caching data in-memory và external sources, cũng có thể gọi là multi-tier caching. Nói cách khác, multi-tier caching này là replacement cho IDistributedCache và IMemoryCache. Nó cũng intended to simplify việc sử dụng caching trong .NET. Cách tiếp cận cũ cho Distributed Caching yêu cầu viết additional code để ensure things are cached và retrieved properly. Package này là một addition tuyệt vời để simplify caching trong .NET để làm robust caching solution. Chúng ta dùng Microsoft.Extensions.Caching.Hybrid nuget package. Trong bài này, chúng ta sẽ cover all features của Hybrid cache package.

Package Features

  • Extensible code: Code viết cho in-memory cache có thể dùng as-is without modification cho integration với external caching servers như Redis, SQL Server, etc.
  • Concurrency Management: Để dùng hybrid cache, ta dùng HybridCache class as a dependency service. Class này ensure chỉ một instance được dùng để get data cho bất kỳ key nào và no concurrent requests được made cho same entry. Tất cả concurrent requests wait cho request này complete.
  • Multi-source caching/Primary-secondary source caching: Nếu application configured multiple sources of data cho caching, data được stored at all locations.

Để get data, nó first checked in primary source. Nếu data không available, request được forward to secondary source, như diagram dưới, scenario 1 in blue và scenario 2 in red.

Code setup

Để bắt đầu, chúng ta first install Microsoft.Extensions.Caching.Hybrid package.

Trong Program.cs, chúng ta viết code dưới để add Hybrid cache.

builder.Services.AddHybridCache();

Để configure hybrid cache, chúng ta viết code dưới inside AddHybridCache as a setup action. Ví dụ dưới.

builder.Services.AddHybridCache(options => {
    options.ReportTagMetrics = true;
    options.DefaultEntryOptions = new Microsoft.Extensions.Caching.Hybrid.HybridCacheEntryOptions {
        Expiration = TimeSpan.FromSeconds(30),
        LocalCacheExpiration = TimeSpan.FromSeconds(30),
    };
});

Implement In-memory cache

Dependency service configuration trên đủ cho chúng ta perform in-memory caching. Dưới là sample code trong API controller để set và get key và value trong application memory.

using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Hybrid;
namespace HybridCacheDemoApplication.Controllers {
    [ApiController]
    [Route("[controller]")]
    public class CacheController : ControllerBase {
        private readonly HybridCache _cache;
        const string cacheKey = "ping";
        public CacheController(HybridCache cache) {
            _cache = cache;
        }
        [HttpGet(Name = "GetPingKey")]
        public async Task<IActionResult> Get() {
            var keydata = await _cache.GetOrCreateAsync<string>(
                cacheKey, // Unique key to the cache entry
                async cancel => await Task.FromResult("pong from get")
            );
            return Ok(new {message = $"{cacheKey} data: {keydata}"});
        }
        [HttpGet("set",Name = "SetPingKey")]
        public async Task<IActionResult> Set() {
            await _cache.SetAsync<string>(cacheKey, "ping");
            return Ok(new { message = $"{cacheKey} is set" });
        }
    }
}

Để hiểu code này hoạt động như thế nào, xem bảng dưới theo sequence.

Cache execution demo table

SequenceEndpointOutputExplanation
1https://localhost:5154/cache/
{ "message": "ping data: pong from get" }
Endpoint này set cache value as "pong from get" khi value chưa set; do đó in "pong from get"
2https://localhost:5154/cache/set
{ "message": "ping is set" }
Endpoint này sẽ set value trong cache.
3https://localhost:5154/cache/
{ "message": "ping data: ping" }
Same endpoint invoked in step 1, nhưng lần này value đã tồn tại trong cache.

Delete Cache Key: Để remove cache keys, chúng ta dùng implementation dưới,

[HttpGet("del",Name="DeletePingKey")]
public async Task<IActionResult> RemoveKey() {
    await _cache.RemoveAsync(cacheKey); //Removes data
    return Ok(new {message=$"{cacheKey} removed"});
}

Distributed Caching using Redis Server

Để implement distributed caching, chúng ta cần perform additional dependency service configurations. Cho ví dụ này, chúng ta dùng Redis cache as an external caching source.

Bây giờ, chúng ta sẽ configure Redis package dùng Microsoft.Extensions.Caching.StackExchangeRedis

Sau khi installed, chúng ta cần add code dưới để add Redis. Connection string sẽ ở format {HOST_NAME}:{PORT_NUMBER},password={PASSWORD}

builder.Services.AddStackExchangeRedisCache(options => {
    options.Configuration = builder.Configuration.GetConnectionString("RedisConnectionString");
});

Bây giờ, chúng ta invoke https://localhost:5154/cache/set, và data sẽ được set in Redis cache seamlessly. Dưới là how it looks in Redis

Xây dựng Hybrid Cache trong .NET 9 với Redis: Unified In-Memory và Distributed Caching

Notice how seamlessly our code worked just by adding a dependency for a distributed caching server, i.e., Redis, in our scenario.

Serialization

Để send data to external caching server, package này dùng byte[], string, và System.Text.Json. Điều này further customizable dùng .AddSerializer() hoặc AddSerializerFactory() methods additionally với AddHybridCache dependency service. Khi chúng ta dùng more optimized serializer, họ improve performance của application.

More customizations

Chúng ta có thể further customize behavior của cache services bằng cách setting flags khi configuring dependencies. Dưới là sample flag để disable compression cho caching.

Note. Đây không phải best practice, nhưng có thể vary based on scenario khi compression không needed hoặc used.

builder.Services.AddHybridCache(options => {
    options.ReportTagMetrics = true;
    options.DefaultEntryOptions = new Microsoft.Extensions.Caching.Hybrid.HybridCacheEntryOptions {
        Flags = Microsoft.Extensions.Caching.Hybrid.HybridCacheEntryFlags.DisableCompression
    };
});

Experimental feature: Tags - Working with inter-related keys

Đôi khi, chúng ta deal với nhiều keys interrelated. Example: Trong e-commerce application, chúng ta cached nhiều fields correspond to a cart item to a user. Cho này, chúng ta có thể create tags.

Dưới là code, cho working with inter-related keys chúng ta created tag named "testdata", chúng ta có thể add more than one tag depending upon type of grouping applicable cho different scenarios. Code này self-explanatory, nhưng in case of any confusion, mention it in the comments.

using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Hybrid;
namespace HybridCacheDemoApplication.Controllers {
    [ApiController]
    [Route("[controller]")]
    public class CacheController : ControllerBase {
        private readonly HybridCache _cache;
        const string cacheKey = "ping";
        public CacheController(HybridCache cache) {
            _cache = cache;
        }
        [HttpGet(Name = "GetPingKey")]
        public async Task<IActionResult> Get() {
            var keydata = await _cache.GetOrCreateAsync<string>(
                cacheKey, // Unique key to the cache entry
                async cancel => await Task.FromResult("pong from get"),
                tags: ["testdata"]
            );
            return Ok(new {message = $"{cacheKey} data: {keydata}"});
        }
        [HttpGet("set",Name = "SetPingKey")]
        public async Task<IActionResult> Set() {
            await _cache.SetAsync<string>(cacheKey, "ping", tags: ["testdata"] );
            return Ok(new { message = $"{cacheKey} is set" });
        }
        [HttpGet("del",Name="DeletePingKey")]
        public async Task<IActionResult> RemoveKey() {
            await _cache.RemoveAsync(cacheKey);
            return Ok(new {message=$"{cacheKey} removed"});
        }
        [HttpGet("delbytag", Name = "DeleteByTestTags")]
        public async Task<IActionResult> RemoveKeyByTags() {
            await _cache.RemoveByTagAsync(["testdata"]);
            return Ok(new { message = $"{cacheKey} removed" });
        }
    }
}

Cảm ơn bạn đã đọc đến cuối. Hybrid caching này cung cấp amazing benefits, và tôi hy vọng bạn cũng sẽ thấy nó helpful.