소개
오늘날 빠르게 변화하는 디지털 세계에서 애플리케이션은 높은 성능과 응답성을 제공할 것으로 기대됩니다. 이를 달성하는 한 가지 방법은 자주 액세스하는 데이터를 저장하는 캐싱 메커니즘을 구현하여 데이터베이스에서 해당 데이터를 반복적으로 가져올 필요성을 줄이는 것입니다. 널리 사용되는 인메모리 데이터 저장소인 Redis는 .NET Core 애플리케이션을 위한 강력한 캐싱 솔루션을 제공합니다. 이 문서에서는 실제 예제와 함께 Redis 캐시를 .NET Core 6 애플리케이션에 통합하는 방법을 살펴보겠습니다.
전제조건
시작하기 전에 시스템에 다음 필수 구성 요소가 설치되어 있는지 확인하세요.
- .NET Core 6 SDK: .NET Core 6 SDK 이상이 설치되어 있는지 확인하세요. .NET 공식 웹사이트에서 다운로드할 수 있습니다.
- Redis 서버: Redis 서버를 로컬에 설치 및 실행하거나 Redis 클라우드 서비스를 사용하세요.
Window에 Radis 서버 설치
Redis 다운로드
다음 GitHub 페이지에서 다소 오래된 64비트 Windows용 미리 컴파일된 Redis 버전을 다운로드할 수 있습니다:https://github.com/MicrosoftArchive/redis/releases/download/win-3.0.504/Redis-x64-3.0.504.msi
이 링크 를 클릭하면 .msi 파일을 받게 됩니다. 이는 Windows 설치 프로그램입니다. . 이제 다운로드로 이동하세요. 폴더를 찾아서 이 파일을 찾으세요.
이제 해당 파일을 클릭하고 Redis를 설치하세요.
Redis 서버는 C:\Program Files\Redis에 설치되어 있어야 합니다. . 거기에서 redis-server.라는 .exe 파일을 찾을 수 있습니다.

이제 명령줄을 열고 다음 명령을 입력하세요.
redis-server

Redis 서버가 실행되기 시작했습니다.
이제 이 명령을 사용하여 Redis 서버의 업데이트 및 변경 사항을 모니터링할 수 있습니다.
redis-cli monitor

.NET Core 6 콘솔 애플리케이션 생성
dotnet new console -n RedisCacheDemo 프로젝트 폴더로 이동
cd RedisCacheDemo 필수 패키지 설치
dotnet add package StackExchange.Redis Redis 연결 구성
Program.cs에서 파일에 필요한 명령문을 추가하고 Main에서 Redis 연결을 구성합니다. 방법:
static void Main(string[] args)
{
var configuration = ConfigurationOptions.Parse("localhost:6379");
var redisConnection = ConnectionMultiplexer.Connect(configuration);
var redisCache = redisConnection.GetDatabase();
Console.WriteLine("Fetching data with caching:");
var cachedData = GetDataWithCaching(redisCache);
Console.WriteLine($"Result: {cachedData}");
Console.WriteLine("Fetching data without caching:");
var uncachedData = GetDataFromDatabase();
Console.WriteLine($"Result: {uncachedData}");
redisConnection.Close(); //It is important to close the connection
}
static string GetDataFromDatabase()
{
// Simulate fetching data from the database
// Replace this with your actual database fetching logic
Thread.Sleep(2000); // Simulating latency
return "Start";
}
static string GetDataWithCaching(IDatabase redisCache)
{
// redisCache.KeyDelete("cachedData"); // For Delete the Cache
// redisCache.StringSet("cachedData", "Test", TimeSpan.FromMinutes(1)); // For Update the Cache
string cachedData = redisCache.StringGet("cachedData");
if (string.IsNullOrEmpty(cachedData))
{
cachedData = GetDataFromDatabase();
redisCache.StringSet("cachedData", cachedData, TimeSpan.FromMinutes(1));
}
return cachedData;
} 이 프로그램을 계속 실행하시기 바랍니다.
이 출력에서 캐시가 있는 경우와 없는 경우의 결과는 동일합니다. 이는 출력이 처음 생성될 때 캐시에 저장되기 때문입니다. 하지만 코드가 변경되면 결과는 달라집니다.
static string GetDataFromDatabase()
{
// Simulate fetching data from the database
// Replace this with your actual database fetching logic
Thread.Sleep(2000); // Simulating latency
return "Last";
} 코드 값을 업데이트하고 다시 실행하겠습니다.
이 출력에서 첫 번째 값은 캐시에서 검색되고, 두 번째 값은 캐시를 사용하지 않고 검색됩니다.
결론
축하합니다! Redis 캐시를 .NET Core 6 애플리케이션에 성공적으로 통합했습니다. 캐싱을 구현함으로써 애플리케이션의 성능과 응답성이 향상되어 자주 액세스하는 데이터를 더 효율적으로 처리할 수 있게 되었습니다.