연습 - .NET Core를 사용하여 앱을 Azure Cache for Redis에 연결
이 연습에서는 다음 작업을 수행하는 방법을 알아봅니다.
- Azure CLI 명령을 사용하여 새 Redis Cache 인스턴스를 만듭니다.
- StackExchange.Redis 패키지를 사용하여 캐시에서 값을 추가하고 검색하는 .NET Core 콘솔 앱을 만듭니다.
필수 조건
- 활성 구독이 있는 Azure 계정. 구독이 아직 없다면 https://azure.com/free에서 평가판을 신청할 수 있습니다.
- 지원되는 플랫폼 중 하나인 Visual Studio Code.
- Visual Studio Code용 C# 확장.
- .NET 8은 이 연습의 대상 프레임워크입니다.
Azure 리소스 만들기
Portal https://portal.azure.com에 로그인하고 Cloud Shell을 연 후 Bash를 셸로 선택합니다.
Azure 리소스에 대한 리소스 그룹을 만듭니다.
<myLocation>
을 가까운 지역으로 바꿉니다.az group create --name az204-redis-rg --location <myLocation>
az redis create
명령을 사용하여 Azure Cache for Redis 인스턴스를 만듭니다. 인스턴스 이름은 고유해야 하며 다음 스크립트는 인스턴스를 생성한 후<myLocation>
을 이전 단계에서 사용했던 지역으로 바꾸려고 합니다. 이 명령은 완료되는 데 몇 분 정도 걸립니다.redisName=az204redis$RANDOM az redis create --location <myLocation> \ --resource-group az204-redis-rg \ --name $redisName \ --sku Basic --vm-size c0
Azure Portal에서 만든 새 Redis Cache로 이동합니다.
탐색 창의 설정/자동화 섹션에서 액세스 키를 선택하고 Portal을 열어 둡니다. 나중에 앱에서 사용할 기본 연결 문자열(StackExchange.Redis) 값을 복사합니다.
콘솔 애플리케이션 만들기
Visual Studio Code 터미널에서 다음 명령을 실행하여 콘솔 앱을 만듭니다.
dotnet new console -o Rediscache
파일 > 폴더 열기를 선택하고 앱의 폴더를 선택하여 Visual Studio Code에서 앱을 엽니다.
프로젝트에
StackExchange.Redis
패키지를 추가합니다.dotnet add package StackExchange.Redis
Program.cs 파일에서 기존 코드를 삭제하고 맨 위에 다음
using
문을 추가합니다.using StackExchange.Redis;
using
문에 다음 변수를 추가하고 Portal에서<REDIS_CONNECTION_STRING>
을 기본 연결 문자열(StackExchange.Redis)로 바꿉니다.// connection string to your Redis Cache string connectionString = "REDIS_CONNECTION_STRING";
Program.cs 파일에 다음 코드를 추가합니다.
using (var cache = ConnectionMultiplexer.Connect(connectionString)) { IDatabase db = cache.GetDatabase(); // Snippet below executes a PING to test the server connection var result = await db.ExecuteAsync("ping"); Console.WriteLine($"PING = {result.Resp2Type} : {result}"); // Call StringSetAsync on the IDatabase object to set the key "test:key" to the value "100" bool setValue = await db.StringSetAsync("test:key", "100"); Console.WriteLine($"SET: {setValue}"); // StringGetAsync retrieves the value for the "test" key string getValue = await db.StringGetAsync("test:key"); Console.WriteLine($"GET: {getValue}"); }
Visual Studio Code 터미널에서 다음 명령을 실행하여 앱을 빌드하고 실행합니다.
dotnet build dotnet run
출력은 다음 예와 유사해야 합니다.
PING = SimpleString : PONG SET: True GET: 100
Portal로 돌아가서 Azure Cache for Redis 블레이드에서 활동 로그를 선택합니다. 로그에서 작업을 볼 수 있습니다.
리소스 정리
리소스가 더 이상 필요하지 않은 경우 az group delete
명령을 사용하여 리소스 그룹을 제거할 수 있습니다.
az group delete -n az204-redis-rg --no-wait