Giới thiệu
Azure Redis Cache dựa trên Redis Cache trong bộ nhớ, mã nguồn mở, cho phép các ứng dụng Web đưa dữ liệu từ nguồn dữ liệu phụ trợ vào bộ nhớ đệm và các trang Web của máy chủ từ bộ nhớ đệm để cải thiện hiệu suất ứng dụng. Trong hướng dẫn từng bước này, chúng ta sẽ tìm hiểu cách sử dụng Azure Redis Cache trong ứng dụng Web của mình.
Bộ nhớ đệm Azure Redis là gì?
Các ứng dụng hiện đại chủ yếu hoạt động với lượng lớn dữ liệu. Trong trường hợp này, khi bạn truy xuất dữ liệu từ cơ sở dữ liệu, nó thường tìm thấy bảng và nhận kết quả mà nó gửi lại cho người dùng. Trong trường hợp đó, hiệu suất sẽ giảm do có nhiều yêu cầu. Vì vậy, để giảm số lượng yêu cầu, bạn có thể sử dụng dữ liệu bộ đệm không thay đổi thường xuyên.
Redis Cache là cơ sở dữ liệu trong bộ nhớ, mã nguồn mở, được sử dụng để cải thiện hiệu suất của ứng dụng bằng cách truy xuất và lưu trữ dữ liệu trong bộ nhớ đệm bằng định dạng Khóa-giá trị. Azure Redis Cache là một chức năng giàu tính năng cung cấp cho bạn quyền truy cập vào thông lượng an toàn, độ trễ thấp, hiệu suất cao.
Hãy bắt đầu triển khai Redis Cache bằng C#.
Bước 1. Đăng nhập vào cổng Azure, vào Cơ sở dữ liệu>> Redis Cache.
Bước 2. Tạo một tin tức Redis Cache.
Bước 3. Nhận Khóa truy cập để kết nối với Redis Cache mới được tạo.

Cài đặt StackExchange.Redis
Bước 4. Cài đặt gói NuGet StackExchange.Redis bằng lệnh sau.
Gói cài đặt StackExchange.Redis
Hãy bắt đầu mã hóa để lưu trữ dữ liệu vào Redis Cache và lấy dữ liệu từ Redis Cache. Gần đây chúng tôi đã thấy mã của các hoạt động CRUD Azure Document DB. Nếu bạn chưa đọc hãy nhấp vào Azure Document DB CRUD Operation và đọc. Chúng tôi có mã hoạt động CRUD trong Tài liệu DB. Bây giờ, chúng ta sẽ triển khai Redis Cache tại đây.
Bước 5. Tương tự như bài viết trước, chúng ta cần thêm chuỗi kết nối Redis Cache vào file appsinstall.dev.json.

Bước 6. Bây giờ, hãy thêm một thuộc tính RedisCache nữa vào Config.cs để nhận giá trị của chuỗi kết nối Redis Cache từ appsinstall.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; }
}
Bước 7. Hãy đến với tệp chương trình.cs và thêm ConnectionMultiplexer cho 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;
}
}
Bây giờ, chúng ta sẽ lưu trữ tài liệu vào Redis Cache trên cơ sở Key trong khi tạo tài liệu vào Document DB và trong khi đọc tài liệu này, chúng ta sẽ sử dụng Key để kiểm tra xem tài liệu có trong Redis Cache hay không. Chúng ta sẽ bỏ qua việc đọc thêm tài liệu từ Document DB. Bằng cách này, chúng tôi có thể tăng hiệu suất của ứng dụng.
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;
}
Bước 8. Thay vào đó, chúng ta hãy đọc tài liệu từ 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());
}
Ảnh chụp nhanh bên dưới cho thấy cách chúng tôi đọc tài liệu từ Redis Cache.
Bước 10. Sau đây là toàn bộ mã của lớp 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;
}
}
}
Tôi hy vọng bài viết này sẽ giúp ích cho bạn.