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

Làm chủ Azure Redis Cache với C#: Hướng dẫn thực hành

Giới thiệu

Azure Redis Cache dựa trên Redis Cache mã nguồn mở, in-memory, cho phép ứng dụng web đưa dữ liệu từ backend vào cache và phục vụ trang web từ cache để cải thiện hiệu suất. Trong hướng dẫn từng bước này, chúng ta sẽ học cách sử dụng Azure Redis Cache trong ứng dụng web.

Azure Redis Cache là gì?

Ứng dụng hiện đại thường làm việc với lượng dữ liệu lớn. Khi truy xuất dữ liệu từ database, hiệu suất giảm do nhiều request. Để giảm thiểu, bạn có thể cache dữ liệu ít thay đổi.

Redis Cache là database in-memory mã nguồn mở, lưu trữ dữ liệu dạng key-value để cải thiện hiệu suất. Azure Redis Cache cung cấp tính năng phong phú: bảo mật, độ trễ thấp, throughput cao.

Các bước triển khai

Bước 1. Đăng nhập Azure Portal, vào Databases >> Redis Cache.

Bước 2. Tạo mới Redis Cache.

Bước 3. Lấy Access Keys để kết nối với Redis Cache vừa tạo.

Làm chủ Azure Redis Cache với C#: Hướng dẫn thực hành

Cài đặt StackExchange.Redis

Bước 4. Cài đặt gói NuGet StackExchange.Redis:

Install-Package StackExchange.Redis

Bắt đầu code để lưu và truy xuất dữ liệu từ Redis Cache. Chúng ta đã thấy code CRUD Azure Document DB trước đó. Bây giờ sẽ tích hợp Redis Cache.

Bước 5. Thêm chuỗi kết nối Redis Cache vào appsettings.dev.json.

Làm chủ Azure Redis Cache với C#: Hướng dẫn thực hành

Bước 6. Thêm property RedisCache vào class Config.cs để đọc chuỗi kết nối:

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. Trong Program.cs, 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; } }

Lưu document vào Redis Cache dựa trên Key khi tạo document trong Document DB. Khi đọc, dùng Key kiểm tra xem document có trong Redis Cache không. Nếu có, bỏ qua đọc từ Document DB để tăng hiệu suất.

var collection = UriFactory.CreateDocumentCollectionUri(configs.docDb.Database, configs.docDb.Collection);
try {
    Console.WriteLine("\nCreating document");
    JObject emp = new JObject();
    emp.Add("id", "V003");
    emp.Add("name", "virendra");
    emp.Add("address", "Indore");
    emp.Add("Country", "India");

    var createResponse = await Client.CreateDocumentAsync(collection, emp);
    var createdDocument = createResponse.Resource;
    Console.WriteLine("Document with id {0} created", createdDocument.Id);

    // Lưu vào Redis Cache với 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. Đọc document từ Redis Cache:

// Đọc từ Redis Cache
var empInRedis = await cache.StringGetAsync("redisEmp3");
if (!empInRedis.IsNullOrEmpty) {
    Console.WriteLine("Read Document from RedisCache {0} : ", empInRedis);
}

// Nếu không có trong Redis Cache, đọc từ 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());
}

Bước 10. Toàn bộ code class 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) {
        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();
    }

    private async Task CRUDOperation() {
        var collection = UriFactory.CreateDocumentCollectionUri(configs.docDb.Database, configs.docDb.Collection);
        try {
            Console.WriteLine("\nCreating document");
            JObject emp = new JObject();
            emp.Add("id", "V003");
            emp.Add("name", "virendra");
            emp.Add("address", "Indore");
            emp.Add("Country", "India");

            var createResponse = await Client.CreateDocumentAsync(collection, emp);
            var createdDocument = createResponse.Resource;
            Console.WriteLine("Document with id {0} created", createdDocument.Id);

            var entryInRedis = await cache.StringSetAsync("redisEmp3", emp.ToString());
            Console.WriteLine("Document with key redisEmp3 stored into redis cache");
        } catch (Exception ex) { throw ex; }

        var empInRedis = await cache.StringGetAsync("redisEmp3");
        if (!empInRedis.IsNullOrEmpty) {
            Console.WriteLine("Read Document from RedisCache {0} : ", empInRedis);
        }
        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());
        }
    }

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

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

Hy vọng bài viết giúp ích cho bạn.