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

Redis làm Primary Data Store trong .NET 8 Web API

Giới thiệu

Bài viết thảo luận về Redis và trường hợp sử dụng nó làm Primary Database (cơ sở dữ liệu chính) để lưu trữ dữ liệu.

  • Giới thiệu Redis
  • Các kiểu dữ liệu Redis
  • Ưu và nhược điểm dùng Redis làm DB
  • Cài đặt Redis trong Container
  • Sử dụng Redis làm Primary Database với .NET 8 Web API

Điều kiện tiên quyết

  • Visual Studio Code
  • .NET 8 SDK
  • Redis Desktop Manager (tải từ https://redis.io/resources/tools/)
  • Docker Desktop
  • Gói NuGet: Microsoft.Extensions.Caching.StackExchangeRedis, StackExchange.Redis

Giới thiệu Redis

Redis là datastore in-memory (bộ nhớ) và key-value store, thường dùng làm lớp caching. Vì lưu dữ liệu trong RAM, Redis cho phép đọc/ghi cực nhanh, phù hợp truy cập dữ liệu độ trễ thấp.

Vấn đề: Redis lưu trong RAM, reboot hệ thống sẽ mất dữ liệu. Giải pháp: Redis cung cấp cơ chế persistence như snapshots (RDB) và append-only files (AOF) để lưu dữ liệu ra disk, đảm bảo khôi phục sau reboot.

Thường Redis dùng làm cache layer, nhưng cũng có thể dùng làm Database để giảm gọi đến hệ thống database phức tạp. Redis dùng mô hình document database, lưu dữ liệu dạng JSON.

Các kiểu dữ liệu Redis

Redis cung cấp các kiểu dữ liệu giải quyết bài toán caching, queuing, event processing:

  • Strings: chuỗi byte
  • Lists: danh sách strings
  • Sets: tập hợp string duy nhất, không thứ tự
  • Hashes: kiểu record dạng field-value pairs

Ưu điểm dùng Redis làm DB

  • Hiệu suất cao
  • Cấu trúc dữ liệu đa dạng
  • Độ trễ thấp
  • Khả năng mở rộng

Nhược điểm dùng Redis làm DB

  • Độ bền dữ liệu (Data Durability)
  • Khả năng truy vấn hạn chế
  • Ràng buộc bộ nhớ (Memory Constraints)

Cài đặt Redis trong Container

Đảm bảo Docker Desktop đang chạy, mở Visual Studio 2022.

Chọn "Create a New Project" → "ASP.NET Core Web API" → Next.

Nhập tên project → Next.

Trang Additional information: chọn cấu hình như hình → Create.

Redis làm Primary Data Store trong .NET 8 Web API Redis làm Primary Data Store trong .NET 8 Web API

Tạo file docker-compose.yaml với cấu hình Redis:

version: '3.8'
services:
  redis:
    image: redis:alpine
    container_name: redisStudentAPI
    ports:
      - 6379:6379

Mở Developer PowerShell (Tools → Command Line → Developer PowerShell), điều hướng vào thư mục project, chạy:

docker compose up -d

Mở Docker Desktop, vào Containers thấy container vừa tạo. Hoặc chạy docker ps xem container đang chạy.

Redis làm Primary Data Store trong .NET 8 Web API

Tương tác với Redis Server:

docker exec -it <container_id> /bin/sh

Setup Docker xong, có thể tương tác Redis qua command line.

Kiểu String

Kiểu đơn giản nhất: mapping 1-1 giữa key và value.

Set giá trị: SET <key> <value>, Get: GET <key>, Xóa: DEL <key>

Cài đặt các gói NuGet cần thiết:

Redis làm Primary Data Store trong .NET 8 Web API

Cấu hình trong Program.cs

builder.Services.AddSingleton<IConnectionMultiplexer>(options => 
    ConnectionMultiplexer.Connect(("127.0.0.1:6379")));
builder.Services.AddScoped<IStudentRepository, StudentRepository>();

Tạo folder Models, file Student.cs:

namespace StudentAPIWithRedisDB.Models {
    public class Student {
        public string Id { get; set; } = $"student:{Guid.NewGuid().ToString()}";
        public required string StudentName { get; set; } = string.Empty;
    }
}

IStudentRepository.cs

using StudentAPIWithRedisDB.Models;
namespace StudentAPIWithRedisDB.Data {
    public interface IStudentRepository {
        IEnumerable<Student> GetAllStudents();
        Student? GetStudentById(string id);
        void AddStudent(Student student);
        Student? UpdateStudent(Student student);
        Student? DeleteStudent(string id);
    }
}

StudentRepository.cs - triển khai interface:

using StackExchange.Redis;
using StudentAPIWithRedisDB.Models;
using System.Text.Json;
namespace StudentAPIWithRedisDB.Data {
    public class StudentRepository : IStudentRepository {
        private readonly IConnectionMultiplexer _redis;
        public StudentRepository(IConnectionMultiplexer redis) { _redis = redis; }

        public void AddStudent(Student student) {
            if(student == null) throw new ArgumentOutOfRangeException(nameof(student));
            var db = _redis.GetDatabase();
            var serializedStudent = JsonSerializer.Serialize(student);
            db.StringSet(student.Id, serializedStudent);
        }

        public Student? DeleteStudent(string id) {
            var db = _redis.GetDatabase();
            var student = db.StringGet(id);
            if (student.IsNullOrEmpty) return null;
            db.KeyDelete(id);
            return JsonSerializer.Deserialize<Student>(student);
        }

        public IEnumerable<Student> GetAllStudents() {
            var db = _redis.GetDatabase();
            var studentKeys = db.Multiplexer.GetServer(_redis.GetEndPoints().First()).Keys(pattern: "student:*");
            var students = new List<Student>();
            foreach (var key in studentKeys) {
                var studentJson = db.StringGet(key);
                if (!studentJson.IsNullOrEmpty) {
                    var student = JsonSerializer.Deserialize<Student>(studentJson);
                    students.Add(student);
                }
            }
            return students;
        }

        public Student? GetStudentById(string id) {
            var db = _redis.GetDatabase();
            var student = db.StringGet(id);
            if(student.IsNullOrEmpty) return null;
            return JsonSerializer.Deserialize<Student>(student);
        }

        public Student UpdateStudent(Student student) {
            var db = _redis.GetDatabase();
            var id = student.Id;
            if (db.KeyExists(id)) {
                var updatedStudentJson = JsonSerializer.Serialize(student);
                db.StringSet(id, updatedStudentJson);
                return student;
            } else { return null; }
        }
    }
}

StudentsController.cs

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using StudentAPIWithRedisDB.Data;
using StudentAPIWithRedisDB.Models;
namespace StudentAPIWithRedisDB.Controllers {
    [Route("api/[controller]")]
    [ApiController]
    public class StudentsController : ControllerBase {
        private readonly IStudentRepository _studentRepository;
        public StudentsController(IStudentRepository studentRepository) { _studentRepository = studentRepository; }

        [HttpGet("{Id}", Name = "GetStudentById")]
        public ActionResult<Student> GetStudentById(string Id) {
            var student = _studentRepository.GetStudentById(Id);
            if(student == null) return NotFound();
            return Ok(student);
        }

        [HttpPost]
        public ActionResult<Student> AddStudent(Student student) {
            _studentRepository.AddStudent(student);
            return CreatedAtRoute(nameof(GetStudentById), new { Id = student.Id }, student);
        }

        [HttpGet(Name = "GetAllStudents")]
        public ActionResult<Student> GetAllStudents() {
            var students = _studentRepository.GetAllStudents();
            return Ok(students);
        }

        [HttpDelete("{id}")]
        public ActionResult<Student> DeleteStudent(string id) {
            var student = _studentRepository.DeleteStudent(id);
            if(student == null) return NotFound();
            return Ok(student);
        }

        [HttpPatch]
        public ActionResult<Student> UpdateStudent(Student student) {
            var studentToUpdate = _studentRepository.GetStudentById(student.Id);
            if(studentToUpdate == null) return NotFound();
            _studentRepository.UpdateStudent(student);
            return NoContent();
        }
    }
}

Chạy ứng dụng, endpoint hiển thị trên Swagger.

Redis làm Primary Data Store trong .NET 8 Web API

Mở Redis Desktop Manager xem dữ liệu. Ban đầu có 16 DB trống.

Gọi endpoint tạo record → tự động tạo record ở DB0.

Test với Postman

CREATE: Chỉ truyền name, ID tự động tạo với suffix Guid.

GetStudentById: Copy ID từ document, truyền vào URL → trả về giá trị.

GetAllStudents: Trả về tất cả document trong Database.

Update: Truyền ID và giá trị mới → cập nhật theo ID. Refresh Manager thấy giá trị mới.

Delete: Truyền ID → xóa document khỏi Student DB.

Đây là cách đơn giản sử dụng Redis làm Database trong ứng dụng. Giảm cache, lưu trực tiếp vào Redis, truy xuất và thao tác dữ liệu. Bạn có thể áp dụng tương tự cho ứng dụng của mình.