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

Triển khai mẫu Cache-Aside với ASP.NET Core và Azure Redis Cache

Giới thiệu

Trong vòng đời phát triển phần mềm, hiệu suất ứng dụng thường là trọng tâm. Có nhiều cách cải thiện hiệu suất, và một trong những mẫu phổ biến nhất trong ứng dụng đám mây hiện đại là mẫu Cache-Aside (cache bên cạnh). Bài viết này mô tả ngắn gọn về mẫu này và cách triển khai với ASP.NET Core.

Mẫu Cache-Aside là gì?

Mẫu này khá đơn giản với mục đích duy nhất: tải dữ liệu theo yêu cầu vào cache từ nguồn dữ liệu. Điều này giúp duy trì sự nhất quán giữa dữ liệu trong cache và nguồn dữ liệu gốc.

Đặc điểm của mẫu:

  • Khi ứng dụng cần dữ liệu, trước tiên nó tra cứu trong cache.
  • Nếu dữ liệu có trong cache (cache hit), ứng dụng sử dụng dữ liệu đó.
  • Nếu không (cache miss), dữ liệu được truy xuất từ nguồn dữ liệu gốc.

Minh họa sơ đồ:

Triển khai mẫu Cache-Aside với ASP.NET Core và Azure Redis Cache

Đối tượng cache phải được vô hiệu hóa khi giá trị thay đổi bởi ứng dụng.

Triển khai mẫu Cache-Aside với ASP.NET Core và Azure Redis Cache

Thứ tự vô hiệu hóa cache rất quan trọng: Cập nhật nguồn dữ liệu trước, sau đó mới xóa mục khỏi cache. Nếu xóa cache trước, client có thể lấy dữ liệu cũ trước khi nguồn dữ liệu được cập nhật, gây ra sự không nhất quán.

Khi nào nên dùng mẫu này?

  • Khi nhu cầu tài nguyên không thể dự đoán và cần tải dữ liệu theo yêu cầu.
  • Khi cache không cung cấp hoạt động read-through và write-through.

Lưu ý

  • Read-Through: Cache nằm trực tiếp trước database, tự động tải dữ liệu từ database khi cache miss và điền vào cache.
  • Write-Through: Cache nằm trực tiếp trước database, dữ liệu luôn đi qua cache đến database chính.

Tạo tài nguyên Azure

Như minh họa, chúng ta cần database (Azure SQL Server) và Cache (Azure Redis Cache). Bạn có thể chọn database và cache phù hợp.

$resourceGroup="<Resource Group>"
$location="<location>"
$redisCacheName="<Redis cache name>"
$sqlServerName="<Azure SQL Server Name>"
$sqlDBName="<Azure SQL DB Name>"
$adminName="<admin name of SQL server>"
$adminPassword="<admin password of SQL Server>"

# Tạo resource group
az group create --name $resourceGroup --location $location

# Tạo Redis Cache với SKU Basic
az redis create --name $redisCacheName --resource-group $resourceGroup --location $location --sku Basic --vm-size c0

# Tạo SQL Server
az sql server create -l $location -g $resourceGroup -n $sqlServerName -u $adminName -p $adminPassword

# Tạo SQL database với SKU Basic
az sql db create -g $resourceGroup -s $sqlServerName -n $sqlDBName --service-objective Basic

Triển khai

Bắt đầu bằng cách tạo dự án ASP.NET Core Web API và cài đặt các gói NuGet cần thiết cho Redis cache và Entity Framework Core.

dotnet add package Microsoft.EntityFrameworkCore.SqlServer
dotnet add package Microsoft.EntityFrameworkCore.Tools
dotnet add package Microsoft.Extensions.Caching.StackExchangeRedis

Tạo class model Country:

public class Country {
    public int Id { get; set; }
    public string Name { get; set; }
    public bool IsActive { get; set; }
}

Đăng ký dependency EF Core và Redis cache trong phương thức ConfigureServices của class Startup:

public void ConfigureServices(IServiceCollection services) {
    services.AddControllers();
    services.AddDbContext<CountryContext>(options => 
        options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
    services.AddStackExchangeRedisCache(options => {
        options.Configuration = Configuration.GetConnectionString("RedisConnectionString");
    });
}

Cập nhật appsettings.json với chuỗi kết nối:

"ConnectionStrings": {
    "RedisConnectionString": "<Redis Cache ConnectionString>",
    "DefaultConnection": "<SQL Server Connection string>"
}

Thêm class DbContext:

public class CountryContext : DbContext {
    public DbSet<Country> Countries { get; set; }
    public CountryContext(DbContextOptions options) : base(options) { }
}

Phương thức GetCountries thử lấy dữ liệu từ cache theo key. Nếu tìm thấy, trả về. Ngược lại, lấy từ database và lưu vào cache. Mục cache hết hạn sau 5 phút.

[Route("api/[controller]")]
[ApiController]
public class CountryController : ControllerBase {
    private readonly IDistributedCache cache;
    private readonly CountryContext countryContext;

    public CountryController(IDistributedCache cache, CountryContext countryContext) {
        this.cache = cache;
        this.countryContext = countryContext;
    }

    [HttpGet]
    public async Task<IEnumerable<Country>> GetCountries() {
        var countriesCache = await cache.GetStringAsync("countries");
        var value = (countriesCache == null) ? default : JsonConvert.DeserializeObject<IEnumerable<Country>>(countriesCache);
        
        if (value == null) {
            var countries = countryContext.Countries.ToList();
            if (countries != null && countries.Any()) {
                await cache.SetStringAsync("Countries", JsonConvert.SerializeObject(countries), 
                    new DistributedCacheEntryOptions { 
                        AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(5) 
                    });
                return countries;
            }
        }
        return value;
    }
}

Phương thức AddCountries minh họa cách vô hiệu hóa cache khi thêm/cập nhật dữ liệu vào database:

[HttpPost]
public async Task<ActionResult<string>> AddCountries([FromBody] Country country, CancellationToken cancellationToken) {
    if (country == null) return BadRequest("country is null");
    await countryContext.AddAsync(country);
    await countryContext.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
    await cache.RemoveAsync("countries", cancellationToken).ConfigureAwait(false);
    return Ok("cache has been invalidated");
}

Kết luận

Bài viết đã mô tả mẫu Cache-Aside và triển khai chính với ASP.NET Core và Azure Redis Cache. Chúc bạn caching vui vẻ!