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

การเรียนรู้ Azure Redis Cache ด้วย C#:คู่มือปฏิบัติ

บทนำ

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

แคช Azure Redis คืออะไร

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

Redis Cache เป็นฐานข้อมูลโอเพ่นซอร์สในหน่วยความจำที่ใช้สำหรับการปรับปรุงประสิทธิภาพของแอปพลิเคชันโดยการเรียกค้นและจัดเก็บข้อมูลในหน่วยความจำแคชโดยใช้รูปแบบคีย์-ค่า Azure Redis Cache เป็นฟังก์ชันที่มีฟีเจอร์มากมายที่ช่วยให้คุณเข้าถึงทรูพุตที่ปลอดภัย เวลาแฝงต่ำ และประสิทธิภาพสูง

มาเริ่มใช้งาน Redis Cache ด้วย C# กันดีกว่า

ขั้นตอนที่ 1 เข้าสู่ระบบพอร์ต Azure ไปที่ฐานข้อมูล>> Redis Cache

ขั้นตอนที่ 2 สร้างแคช Redis ข่าวสาร

ขั้นตอนที่ 3 รับคีย์การเข้าถึงเพื่อเชื่อมต่อกับแคช Redis ที่สร้างขึ้นใหม่

การเรียนรู้ Azure Redis Cache ด้วย C#:คู่มือปฏิบัติ

ติดตั้ง StackExchange.Redis

ขั้นตอนที่ 4 ติดตั้งแพ็คเกจ StackExchange.Redis NuGet โดยใช้คำสั่งต่อไปนี้

ติดตั้งแพ็คเกจ StackExchange.Redis

มาเริ่มเขียนโค้ดเพื่อจัดเก็บข้อมูลลงใน Redis Cache และดึงข้อมูลจาก Redis Cache เราเพิ่งเห็นโค้ดของการดำเนินการ Azure Document DB CRUD หากคุณยังไม่ได้อ่าน ให้คลิกที่ Azure Document DB CRUD Operation แล้วอ่าน เรามีรหัสการดำเนินการ CRUD ใน Document DB ตอนนี้ เราจะใช้ Redis Cache ที่นี่

ขั้นตอนที่ 5 เช่นเดียวกับบทความก่อนหน้านี้ เราจำเป็นต้องเพิ่มสตริงการเชื่อมต่อ Redis Cache ลงในไฟล์ appsettings.dev.json

การเรียนรู้ Azure Redis Cache ด้วย C#:คู่มือปฏิบัติ

ขั้นตอนที่ 6 ตอนนี้ ให้เพิ่มคุณสมบัติ RedisCache อีกหนึ่งรายการลงใน Config.cs ซึ่งจะได้รับค่าของสตริงการเชื่อมต่อ Redis Cache จาก appsettings.dev.json

public class Config
{
 public DocDbConnectionString docDb { get; set; }
 public string RedisCache { get; set; }
}`
public class DocDbConnectionString
{
 public string EndPoint { get; set; }
 public string AuthKey { get; set; }
 public string Database { get; set; }
 public string Collection { get; set; }
}

ขั้นตอนที่ 7 มาที่ไฟล์ program.cs และเพิ่ม ConnectionMultiplexer สำหรับ Redis Cache

IDatabase cache = lazyConnection.Value.GetDatabase();
private static Lazy<ConnectionMultiplexer> lazyConnection = new Lazy<ConnectionMultiplexer>(() =>
{
 string cacheConnection = configs.RedisCache;
 return ConnectionMultiplexer.Connect(cacheConnection);
});
public static ConnectionMultiplexer Connection
{
 get
 {
 return lazyConnection.Value;
 }
}

ตอนนี้ เราจะจัดเก็บเอกสารลงใน Redis Cache บนพื้นฐานของ Key ในขณะที่สร้างเอกสารลงใน Document DB และในขณะที่อ่านเอกสารนี้ เราจะใช้ Key เพื่อตรวจสอบว่าเอกสารนั้นมีอยู่ใน Redis Cache หรือไม่ เราจะข้ามการอ่านเอกสารเพิ่มเติมจาก Document DB การทำเช่นนี้จะทำให้เราสามารถเพิ่มประสิทธิภาพของแอปพลิเคชันได้

var collection = UriFactory.CreateDocumentCollectionUri(configs.docDb.Database, configs.docDb.Collection);
try
{
 // create JObject which contains the employee details
 Console.WriteLine("\nCreating document");
 JObject emp = new JObject();
 emp.Add("id", "V003");
 emp.Add("name", "virendra");
 emp.Add("address", "Indore");
 emp.Add("Country", "India");
 // create the document into DocumentDb
 var createResponse = await Client.CreateDocumentAsync(collection, emp);
 var createdDocument = createResponse.Resource;
 Console.WriteLine("Document with id {0} created", createdDocument.Id);
 // Set JObject into redis cache with key "redisEmp3"
 var entryInRedis = await cache.StringSetAsync("redisEmp3", emp.ToString());
 Console.WriteLine("Document with key redisEmp3 stored into redis cache");
}
catch (Exception ex)
{
 throw ex;
}

ขั้นตอนที่ 8 ให้เราอ่านเอกสารจาก Redis Cache แทน

// Read document from Redis Cache.
var empInRedis = await cache.StringGetAsync("redisEmp3");
if (!empInRedis.IsNullOrEmpty)
{
 Console.WriteLine("Read Document from RedisCache {0} : ", empInRedis);
}
// If Redis Cache does not have Document, then read the document from Document DB
if (empInRedis.IsNullOrEmpty)
{
 var readResponse = await client.ReadDocumentAsync(UriFactory.CreateDocumentUri(configs.docDb.Database, configs.docDb.Collection, "V001"));
 var readDocument = readResponse.Resource;
 Console.WriteLine("Read Document {0}: ", readResponse.Resource.ToString());
}

สแนปชอตด้านล่างแสดงวิธีที่เราอ่านเอกสารจาก Redis Cache

ขั้นตอนที่ 10 ต่อไปนี้คือโค้ดทั้งหมดของคลาส Program.cs

using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json.Linq;
using StackExchange.Redis;
using Microsoft.Azure.Documents.Client;
public class Program
{
 private static IConfiguration Configuration { get; set; }
 private static Config configs;
 private DocumentClient client;
 private IDatabase cache = lazyConnection.Value.GetDatabase();
 static void Main(string[] args)
 {
 // Set up Configuration
 var builder = new ConfigurationBuilder()
 .SetBasePath(Directory.GetCurrentDirectory())
 .AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")}.json", optional: false, reloadOnChange: true);
 Configuration = builder.Build();
 configs = new Config();
 Configuration.Bind(configs);
 Program obj = new Program();
 obj.CRUDOperation().Wait();
 }
 // CRUD Operation
 private async Task CRUDOperation()
 {
 var collection = UriFactory.CreateDocumentCollectionUri(configs.docDb.Database, configs.docDb.Collection);
 try
 {
 // create JObject which contains the employee details
 Console.WriteLine("\nCreating document");
 JObject emp = new JObject();
 emp.Add("id", "V003");
 emp.Add("name", "virendra");
 emp.Add("address", "Indore");
 emp.Add("Country", "India");
 // create the document
 var createResponse = await Client.CreateDocumentAsync(collection, emp);
 var createdDocument = createResponse.Resource;
 Console.WriteLine("Document with id {0} created", createdDocument.Id);
 // Set JObject into redis cache with key "redisEmp3"
 var entryInRedis = await cache.StringSetAsync("redisEmp3", emp.ToString());
 Console.WriteLine("Document with key redisEmp3 stored into redis cache");
 }
 catch (Exception ex)
 {
 throw ex;
 }
 // read document from redis cache
 var empInRedis = await cache.StringGetAsync("redisEmp3");
 if (!empInRedis.IsNullOrEmpty)
 {
 Console.WriteLine("Read Document from RedisCache {0} : ", empInRedis);
 }
 if (empInRedis.IsNullOrEmpty)
 {
 // Read document from document Db
 var readResponse = await client.ReadDocumentAsync(UriFactory.CreateDocumentUri(configs.docDb.Database, configs.docDb.Collection, "V001"));
 var readDocument = readResponse.Resource;
 Console.WriteLine("Read Document {0}: ", readResponse.Resource.ToString());
 }
 }
 // Get a single instance of Document client and reuse
 public DocumentClient Client
 {
 get
 {
 if (client == null)
 {
 Uri endpointUri = new Uri(configs.docDb.EndPoint);
 client = new DocumentClient(endpointUri, configs.docDb.AuthKey, null, ConsistencyLevel.Session);
 client.OpenAsync();
 }
 return client;
 }
 }
 // To establish Redis Cache connection
 private static Lazy<ConnectionMultiplexer> lazyConnection = new Lazy<ConnectionMultiplexer>(() =>
 {
 string cacheConnection = configs.RedisCache;
 return ConnectionMultiplexer.Connect(cacheConnection);
 });
 public static ConnectionMultiplexer Connection
 {
 get
 {
 return lazyConnection.Value;
 }
 }
}

ฉันหวังว่าบทความนี้จะช่วยคุณได้