Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Redis

Redis เป็นที่เก็บข้อมูลหลักใน .NET 8 Web API

บทนำ

ในบทความนี้ ฉันจะพูดถึง Redis และกรณีการใช้งานในการใช้เป็นฐานข้อมูลหลักในการจัดเก็บข้อมูลของเรา

  • ข้อมูลเบื้องต้นเกี่ยวกับ Redis
  • ประเภทข้อมูล Redis
  • ข้อดีและข้อเสียของการใช้ Redis เป็น DB
  • การตั้งค่า Redis ในคอนเทนเนอร์
  • การใช้ Redis เป็นฐานข้อมูลหลักด้วย .NET 8 Web API

ข้อกำหนดเบื้องต้น

  • รหัสภาพ
  • .NET 8 SDK
  • ตัวจัดการเดสก์ท็อป Redis คุณสามารถดาวน์โหลดได้จาก URL (https://redis.io/resources/tools/)
  • นักเทียบท่าเดสก์ท็อป
  • แพ็คเกจ
    • Microsoft.Extensions.Caching.stackExchangeRedis
    • StackExchange.Redis

ข้อมูลเบื้องต้นเกี่ยวกับ Redis

Redis เป็นที่เก็บข้อมูลในหน่วยความจำและที่เก็บข้อมูลคีย์-ค่า และส่วนใหญ่จะใช้สำหรับเลเยอร์แคช เนื่องจาก Redis จัดเก็บข้อมูลไว้ในหน่วยความจำ จึงช่วยให้ดำเนินการอ่านและเขียนได้รวดเร็วมาก ซึ่งเหมาะอย่างยิ่งสำหรับการเข้าถึงข้อมูลที่มีความหน่วงต่ำ คุณจะมีคำถามเช่น Redis จัดเก็บข้อมูลไว้ในหน่วยความจำ แต่เมื่อระบบรีบูต ข้อมูลจะสูญหาย

เพื่อแก้ปัญหาความคงอยู่ของข้อมูล Redis จึงมีกลไกที่แตกต่างกัน เช่น สแนปชอต และ ไฟล์ต่อท้ายเท่านั้น (AOF) กลไกเหล่านี้ช่วยให้คุณสามารถจัดเก็บข้อมูลบนดิสก์ได้อย่างต่อเนื่อง ทำให้มั่นใจได้ว่าสามารถกู้คืนได้แม้ว่าจะรีบูตระบบแล้วก็ตาม คุณสามารถเรียนรู้เพิ่มเติมเกี่ยวกับ Redis Persistence ได้ใน URL

Redis ส่วนใหญ่ใช้เป็นเลเยอร์แคช แต่เรายังสามารถใช้เป็นฐานข้อมูลเพื่อลดการเรียกอื่นไปยังระบบฐานข้อมูลที่ซับซ้อน Redis โดยใช้โมเดลฐานข้อมูล Document ซึ่งจัดเก็บข้อมูลในเอกสารส่วนใหญ่อยู่ในรูปแบบ JSON คุณสามารถทราบข้อมูลเพิ่มเติมได้จาก URL

ประเภทข้อมูล Redis

Redis มีประเภทข้อมูลจำนวนหนึ่งที่ช่วยให้เราสามารถแก้ไขปัญหาตั้งแต่การแคช การเข้าคิว และการประมวลผลเหตุการณ์

  • สตริง: แสดงถึงลำดับของไบต์
  • รายการ - รายการสตริง
  • ชุด - ชุดของสตริงที่ไม่ซ้ำกันแบบไม่เรียงลำดับ
  • แฮช - ประเภทเรคคอร์ดที่จำลองเป็นคอลเลกชันของคู่ค่าฟิลด์

คุณจะได้เรียนรู้เพิ่มเติมเกี่ยวกับประเภทข้อมูลจาก URL

ข้อดีของการใช้ Redis เป็น DB

  • ประสิทธิภาพสูง
  • โครงสร้างข้อมูลอเนกประสงค์
  • ความหน่วงต่ำ
  • ความสามารถในการขยายขนาด

ข้อเสียของการใช้ Redis เป็น DB

  • ความทนทานของข้อมูล
  • ความสามารถในการสืบค้นมีจำกัด
  • ข้อจำกัดของหน่วยความจำ

การตั้งค่า Redis ในคอนเทนเนอร์

ตรวจสอบให้แน่ใจว่า Docker Desktop ทำงานอยู่และเปิด Visual Studio 2022

เลือก "สร้างโครงการใหม่" --> คลิก "ASP.NET Core Web API" จากนั้นคลิก "ถัดไป"

ในหน้ากำหนดค่า ป้อนชื่อโครงการแล้วกด "ถัดไป"

Redis เป็นที่เก็บข้อมูลหลักใน .NET 8 Web API

ในหน้าข้อมูลเพิ่มเติม ให้เลือกข้อมูลตามภาพหน้าจอและเลือก "สร้าง"

Redis เป็นที่เก็บข้อมูลหลักใน .NET 8 Web API

ตอนนี้ ให้สร้างไฟล์ "docker-compose.yaml" เพื่อเก็บการกำหนดค่าสำหรับ Redis ของเราและวางโค้ดด้านล่าง

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

หลังจากนั้น ให้เปิดพรอมต์ Developer Powershell จากเครื่องมือ -> บรรทัดคำสั่ง -> Powershell สำหรับนักพัฒนา

จากนั้นไปที่โฟลเดอร์ Project และป้อนคำสั่งเพื่อเรียกใช้ไฟล์ YAML "docker compose up -d"

เปิดเดสก์ท็อปนักเทียบท่า และนำทางไปยังคอนเทนเนอร์ที่คุณเห็นคอนเทนเนอร์ที่สร้างจากไฟล์ YAML นอกจากนี้ คุณยังสามารถเรียกใช้ 'docker ps' เพื่อดูคอนเทนเนอร์ที่ทำงานอยู่ได้

Redis เป็นที่เก็บข้อมูลหลักใน .NET 8 Web API

หากต้องการโต้ตอบกับเซิร์ฟเวอร์ Redis คุณต้องเรียกใช้คำสั่งด้านล่างด้วยรหัสคอนเทนเนอร์

docker exec -it <container_id> /bin/sh

การตั้งค่าพื้นฐานของ Docker เสร็จสิ้นแล้ว และเราสามารถโต้ตอบกับ Redis ผ่านทางบรรทัดคำสั่งได้

ตอนนี้ เราจะดูเพิ่มเติมเกี่ยวกับประเภทข้อมูลสตริงเนื่องจากเราจะจัดเก็บคีย์และคู่ของค่าเป็นสตริง

สตริง

เป็นประเภทค่าที่ง่ายที่สุดที่จะเชื่อมโยงกับคีย์และการแมปแบบหนึ่งต่อหนึ่งระหว่างคีย์และค่า

เราสามารถตั้งค่าโดยใช้ Set และยังได้รับการใช้ GET

คุณยังสามารถลบคีย์ได้โดยใช้ Del

ตอนนี้ คุณต้องติดตั้งแพ็คเกจที่จำเป็นจาก NuGet Package Manager

Redis เป็นที่เก็บข้อมูลหลักใน .NET 8 Web API

เพิ่มการกำหนดค่าในไฟล์ Program.cs

Programs.cs

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

สร้างโฟลเดอร์ Models และสร้างไฟล์สำหรับ Model Student.cs ของเรา จากนั้นวางโค้ด

นักเรียน.cs

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

จากนั้นคัดลอกและวางโค้ดด้านล่างลงในไฟล์ Respection

StudentRepository.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 คือการนำอินเทอร์เฟซ IStudentRespository.cs ไปใช้และวิธีการทั้งหมด

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();
 }
 }
}

ตอนนี้ ให้เรียกใช้แอปพลิเคชันที่คุณสามารถดูตำแหน่งข้อมูลที่แสดงบนเบราว์เซอร์โดยใช้ Swagger

Redis เป็นที่เก็บข้อมูลหลักใน .NET 8 Web API

นอกจากนี้ยังจะช่วยได้หากคุณเปิด Redis Desktop Manager เพื่อดูข้อมูล ในตอนแรกจะมีฐานข้อมูล 16 ฐานข้อมูลที่ไม่มีข้อมูลใดๆ

เมื่อคุณไปถึงจุดสิ้นสุดการสร้าง มันจะสร้างบันทึกใน DB0 โดยอัตโนมัติ

สร้าง

เพื่อจุดประสงค์ในการทดสอบที่ง่ายดาย ฉันได้ใช้บุรุษไปรษณีย์เพื่อทดสอบจุดสิ้นสุด

ส่งผ่านชื่อเท่านั้น จากนั้นจะสร้าง ID พร้อมชื่อนักเรียนและส่วนต่อท้ายด้วย Guid ใหม่โดยอัตโนมัติ

และเอกสารถูกสร้างขึ้นบน DB0

GetStudentById

ในการดำเนินการนี้ คุณจะต้องคัดลอก ID จากเอกสาร จากนั้นส่งต่อไปยัง URL คำขอ

และส่งคืนค่าตาม ID

รับทั้งหมดนักเรียน

จะส่งคืนเอกสารทั้งหมดที่มีอยู่ในฐานข้อมูล

อัปเดต

คุณต้องส่ง ID และค่าที่อัปเดต เพื่อที่มันจะอัปเดตตาม ID

เมื่อคุณรีเฟรชผู้จัดการแล้วคุณจะเห็นค่าที่อัปเดต

ลบ

สำหรับการลบผู้ใช้ กรุณาส่ง ID จากนั้นระบบจะลบเอกสารออกจาก Student DB

และเอกสารจะถูกลบออกจากไฟล์

ก่อนหน้านี้ ฉันมีเอกสารสองฉบับอยู่บนโต๊ะของนักเรียน แต่ตอนนี้เอกสารแรกถูกลบไปแล้ว

นี่เป็นวิธีง่ายๆ ในการแสดงการใช้ Redis เป็นฐานข้อมูลในแอปพลิเคชันของเรา ที่นี่ เราได้ลดแคชและจัดเก็บข้อมูลโดยตรงไปยัง Redis และยังดึงข้อมูลและทำการเปลี่ยนแปลงในแคชด้วย ในทำนองเดียวกัน คุณยังสามารถนำไปใช้กับใบสมัครของคุณได้