Computer >> 컴퓨터 >  >> 프로그래밍 >> Redis

C#으로 Azure Redis Cache 마스터하기:실용 가이드

소개

Azure Redis Cache는 웹 앱이 백엔드 데이터 원본의 데이터를 캐시로 가져오고 캐시에서 서버 웹 페이지를 가져와 앱 성능을 향상시킬 수 있는 오픈 소스, 메모리 내 Redis Cache를 기반으로 합니다. 이 단계별 자습서에서는 웹 앱에서 Azure Redis Cache를 사용하는 방법을 알아봅니다.

Azure Redis Cache란 무엇인가요?

최신 애플리케이션은 대부분 대량의 데이터를 처리합니다. 이 시나리오에서는 데이터베이스에서 데이터를 검색할 때 일반적으로 테이블을 찾아 사용자에게 다시 보내는 결과를 가져옵니다. 이 경우 여러 요청으로 인해 성능이 저하됩니다. 따라서 요청 수를 어느 정도 줄이기 위해 자주 변경되지 않는 캐시 데이터를 사용할 수 있습니다.

Redis Cache는 키-값 형식을 사용하여 캐시 메모리에서 데이터를 검색하고 저장하여 애플리케이션 성능을 향상시키는 데 사용되는 오픈 소스 인 메모리 데이터베이스입니다. Azure Redis Cache는 안전하고 대기 시간이 짧은 고성능 처리량에 대한 액세스를 제공하는 다양한 기능을 제공합니다.

C#으로 Redis Cache 구현을 시작해 보겠습니다.

1단계.  Azure 포트에 로그인하고 데이터베이스>> Redis 캐시로 이동하세요.

2단계.  뉴스 Redis Cache를 생성하세요.

3단계.  새로 생성된 Redis Cache에 연결하기 위한 액세스 키를 받으세요.

C#으로 Azure Redis Cache 마스터하기:실용 가이드

StackExchange.Redis 설치

4단계.  다음 명령을 사용하여 StackExchange.Redis NuGet 패키지를 설치합니다.

설치 패키지 StackExchange.Redis

Redis Cache에 데이터를 저장하고 Redis Cache에서 데이터를 검색하는 코딩을 시작해 보겠습니다. 우리는 최근 Azure Document DB CRUD 작업 코드를 보았습니다. 아직 읽지 않으셨다면 Azure Document DB CRUD Operation을 클릭해서 읽어보세요. Document DB에 CRUD 작업 코드가 있습니다. 이제 여기서 Redis Cache를 구현하겠습니다.

5단계.  이전 기사와 마찬가지로 appsettings.dev.json 파일에 Redis Cache 연결 문자열을 추가해야 합니다.

C#으로 Azure Redis Cache 마스터하기:실용 가이드

6단계.  이제 appsettings.dev.json에서 Redis Cache 연결 문자열 값을 가져오는 RedisCache 속성을 Config.cs에 하나 더 추가하세요.

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 파일로 이동하여 Redis Cache용 ConnectionMultiplexer를 추가해 보겠습니다.

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

이제 Document DB에 문서를 생성하면서 Key를 기준으로 Redis Cache에 문서를 저장하고, 이 문서를 읽으면서 해당 문서가 Redis Cache에 존재하는지 여부를 Key를 이용하여 확인하겠습니다. 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;
 }
 }
}

이 글이 도움이 되길 바랍니다.