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

Tích hợp Redis Caching vào .NET Core API cho Hiệu suất và Khả năng mở rộng

Giới thiệu

Chúng ta sẽ thảo luận về Caching trong .NET Core và cách nó hoạt động, lần lượt:

  • Giới thiệu Caching
  • Cache là gì
  • Các loại cache
  • Triển khai Cache

Caching rất phổ biến trong ngành phần mềm vì cải thiện hiệu suất và khả năng mở rộng. Các ứng dụng web như Gmail, Facebook phản hồi rất nhanh nhờ caching. Với lượng user lớn và traffic cao, caching là giải pháp bắt buộc.

Caching là gì?

Cache là bộ nhớ lưu trữ dữ liệu truy cập thường xuyên trong lưu trữ tạm thời, cải thiện hiệu suất đáng kể, tránh hit database không cần thiết và lưu dữ liệu thường dùng vào buffer để lấy khi cần.

Tích hợp Redis Caching vào .NET Core API cho Hiệu suất và Khả năng mở rộng Tích hợp Redis Caching vào .NET Core API cho Hiệu suất và Khả năng mở rộng

Hình ảnh so sánh 2 kịch bản: không dùng cache (mỗi user hit database) vs dùng cache (user đầu tiên hit DB, lưu cache, user sau lấy từ cache).

Các loại Cache

.NET Core hỗ trợ 2 loại caching chính:

  1. In-Memory Caching: dữ liệu lưu trong bộ nhớ application server.
  2. Distributed Caching: dữ liệu lưu và chia sẻ giữa nhiều server (Redis, v.v.).

Distributed Caching

Tích hợp Redis Caching vào .NET Core API cho Hiệu suất và Khả năng mở rộng

  • Dữ liệu lưu và chia sẻ giữa nhiều server.
  • Dễ dàng cải thiện scalability và performance khi quản lý tải giữa nhiều server (multi-tenant).
  • Nếu một server crash/restart, ứng dụng không bị ảnh hưởng vì còn nhiều server khác.

Redis là cache phổ biến nhất hiện nay, nhiều công ty dùng để cải thiện performance và scalability.

Redis Cache

  • Redis là Open Source (BSD Licensed) in-memory Data Structure store, dùng như database.
  • Lưu trữ dữ liệu thường dùng, static data trong cache và dùng theo yêu cầu.
  • Hỗ trợ nhiều cấu trúc dữ liệu: List, Set, Hashing, Stream, v.v.

Cài đặt Redis Cache

Bước 1. Tải Redis Server từ: https://github.com/microsoftarchive/redis/releases/tag/win-3.0.504

Bước 2. Giải nén zip, mở Redis Server và Redis CLI.

Tích hợp Redis Caching vào .NET Core API cho Hiệu suất và Khả năng mở rộng

Redis Server chạy trên port 6379.

Triển khai Redis Cache với .NET Core API

Bước 1. Tạo .NET Core API Web Application.

Bước 2. Cài đặt NuGet Packages:

  • Microsoft.EntityFrameworkCore
  • Microsoft.EntityFrameworkCore.Design
  • Microsoft.EntityFrameworkCore.SqlServer
  • Microsoft.EntityFrameworkCore.Tools
  • Swashbuckle.AspNetCore
  • StackExchange.Redis

Bước 3. Tạo Model Product:

namespace RedisCacheDemo.Model {
    public class Product {
        public int ProductId { get; set; }
        public string ProductName { get; set; }
        public string ProductDescription { get; set; }
        public int Stock { get; set; }
    }
}

Bước 4. Tạo DbContextClass:

using Microsoft.EntityFrameworkCore;
using RedisCacheDemo.Model;
namespace RedisCacheDemo.Data {
    public class DbContextClass: DbContext {
        public DbContextClass(DbContextOptions<DbContextClass> options): base(options) {}
        public DbSet<Product> Products { get; set; }
    }
}

Bước 5. Tạo ICacheService Interface và CacheService Class:

using System;
namespace RedisCacheDemo.Cache {
    public interface ICacheService {
        T GetData<T>(string key);
        bool SetData<T>(string key, T value, DateTimeOffset expirationTime);
        object RemoveData(string key);
    }
}
using Newtonsoft.Json;
using StackExchange.Redis;
using System;
namespace RedisCacheDemo.Cache {
    public class CacheService: ICacheService {
        private IDatabase _db;
        public CacheService() { ConfigureRedis(); }
        private void ConfigureRedis() { _db = ConnectionHelper.Connection.GetDatabase(); }
        public T GetData<T>(string key) {
            var value = _db.StringGet(key);
            if (!string.IsNullOrEmpty(value)) return JsonConvert.DeserializeObject<T>(value);
            return default;
        }
        public bool SetData<T>(string key, T value, DateTimeOffset expirationTime) {
            TimeSpan expiryTime = expirationTime.DateTime.Subtract(DateTime.Now);
            var isSet = _db.StringSet(key, JsonConvert.SerializeObject(value), expiryTime);
            return isSet;
        }
        public object RemoveData(string key) {
            bool _isKeyExist = _db.KeyExists(key);
            if (_isKeyExist) return _db.KeyDelete(key);
            return false;
        }
    }
}

Bước 6. Tạo ProductController:

using Microsoft.AspNetCore.Mvc;
using RedisCacheDemo.Cache;
using RedisCacheDemo.Data;
using RedisCacheDemo.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace RedisCacheDemo.Controllers {
    [Route("api/[controller]")]
    [ApiController]
    public class ProductController: ControllerBase {
        private readonly DbContextClass _dbContext;
        private readonly ICacheService _cacheService;
        public ProductController(DbContextClass dbContext, ICacheService cacheService) {
            _dbContext = dbContext; _cacheService = cacheService;
        }
        [HttpGet("products")]
        public IEnumerable<Product> Get() {
            var cacheData = _cacheService.GetData<IEnumerable<Product>>("product");
            if (cacheData != null) return cacheData;
            var expirationTime = DateTimeOffset.Now.AddMinutes(5.0);
            cacheData = _dbContext.Products.ToList();
            _cacheService.SetData<IEnumerable<Product>>("product", cacheData, expirationTime);
            return cacheData;
        }
        [HttpGet("product")]
        public Product Get(int id) {
            var cacheData = _cacheService.GetData<IEnumerable<Product>>("product");
            if (cacheData != null) {
                var filteredData = cacheData.Where(x => x.ProductId == id).FirstOrDefault();
                return filteredData;
            }
            return _dbContext.Products.Where(x => x.ProductId == id).FirstOrDefault();
        }
        [HttpPost("addproduct")]
        public async Task<Product> Post(Product value) {
            var obj = await _dbContext.Products.AddAsync(value);
            _cacheService.RemoveData("product");
            _dbContext.SaveChanges();
            return obj.Entity;
        }
        [HttpPut("updateproduct")]
        public void Put(Product product) {
            _dbContext.Products.Update(product);
            _cacheService.RemoveData("product");
            _dbContext.SaveChanges();
        }
        [HttpDelete("deleteproduct")]
        public void Delete(int Id) {
            var filteredData = _dbContext.Products.Where(x => x.ProductId == Id).FirstOrDefault();
            _dbContext.Remove(filteredData);
            _cacheService.RemoveData("product");
            _dbContext.SaveChanges();
        }
    }
}

Bước 7. Thêm connection string vào appsettings.json:

{
  "Logging": { "LogLevel": { "Default": "Information", "Microsoft": "Warning", "Microsoft.Hosting.Lifetime": "Information" } },
  "AllowedHosts": "*",
  "RedisURL": "127.0.0.1:6379",
  "ConnectionStrings": { "DefaultConnection": "Data Source=Server;Initial Catalog=RedisCache;User Id=sa;Password=***;" }
}

Bước 8. Đăng ký service trong Startup.cs:

public void ConfigureServices(IServiceCollection services) {
    services.AddControllers();
    services.AddScoped<ICacheService, CacheService>();
    services.AddDbContext<DbContextClass>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
    services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "RedisCacheDemo", Version = "v1" }); });
}

Bước 9. Tạo ConfigurationManager class.

Bước 10. Tạo ConnectionHelper class cho Redis Connection.

using StackExchange.Redis;
using System;
namespace RedisCacheDemo.Cache {
    public class ConnectionHelper {
        static ConnectionHelper() {
            ConnectionHelper.lazyConnection = new Lazy<ConnectionMultiplexer>(() => {
                return ConnectionMultiplexer.Connect(ConfigurationManager.AppSetting["RedisURL"]);
            });
        }
        private static Lazy<ConnectionMultiplexer> lazyConnection;
        public static ConnectionMultiplexer Connection { get { return lazyConnection.Value; } }
    }
}

Bước 11. Migration và Update Database:

add-migration "FirstMigration"
update-database

Bước 12. Chạy ứng dụng, test qua Swagger UI.

Xử lý race condition (tham tranh) với Lock:

private static object _lock = new object();

public IEnumerable<Product> Get() {
    var cacheData = _cacheService.GetData<IEnumerable<Product>>("product");
    if (cacheData != null) return cacheData;
    lock(_lock) {
        var expirationTime = DateTimeOffset.Now.AddMinutes(5.0);
        cacheData = _dbContext.Products.ToList();
        _cacheService.SetData<IEnumerable<Product>>("product", cacheData, expirationTime);
    }
    return cacheData;
}

Kiểm tra key trong Redis CLI:

Tích hợp Redis Caching vào .NET Core API cho Hiệu suất và Khả năng mở rộng

Đây là tất cả về Redis Cache trong .NET Core. Happy Coding!