연습: Microsoft .NET SDK v3를 사용하여 리소스 만들기

완료됨

이 연습에서는 Azure Cosmos DB에서 다음 작업을 수행하는 콘솔 앱을 만듭니다.

  • Azure Cosmos DB 계정에 연결
  • 데이터베이스 만들기
  • 컨테이너 만들기

사전 요구 사항

설치

연습을 위해 다음 작업을 수행하여 Azure 및 로컬 환경을 준비합니다.

Azure에 연결

  1. Visual Studio Code를 시작하고 위쪽 애플리케이션 표시줄에서 터미널을 선택한 다음, 새 터미널을 선택하여 터미널 창을 엽니다.

  2. 다음 명령을 사용하여 Azure에 로그인합니다. 로그인할 계정을 선택할 수 있는 브라우저 창이 열립니다.

    az login
    

Azure에서 리소스 만들기

  1. 이 연습에 필요한 리소스에 대한 리소스 그룹을 만듭니다. <myLocation>을 가까운 지역으로 바꿉니다.

    az group create --location <myLocation> --name az204-cosmos-rg
    
  2. Azure Cosmos DB 계정을 만듭니다. Azure Cosmos DB 계정을 식별할 수 있는 <myCosmosDBacct>고유한 이름으로 바꿉니다. 이름은 소문자, 숫자 및 하이픈(-) 문자만 포함할 수 있으며, 3~31자여야 합니다. 이 명령은 완료되는 데 몇 분 정도 걸립니다.

    az cosmosdb create --name <myCosmosDBacct> --resource-group az204-cosmos-rg
    

    JSON 응답에 표시된 documentEndpoint를 기록합니다. 연습의 뒷부분에서 사용됩니다.

  3. 다음 명령을 사용하여 계정의 기본 키를 검색합니다. 코드에서 사용할 명령 결과의 primaryMasterKey를 기록합니다.

    # Retrieve the primary key
    az cosmosdb keys list --name <myCosmosDBacct> --resource-group az204-cosmos-rg
    

콘솔 애플리케이션 설정

이제 필요한 리소스가 Azure에 배포되었으므로 다음 단계는 Visual Studio Code에서 동일한 터미널 창을 사용하여 콘솔 애플리케이션을 설정하는 것입니다.

  1. 프로젝트에 대한 폴더를 만들고 폴더로 변경합니다.

    md az204-cosmos
    cd az204-cosmos
    
  2. .NET 콘솔 앱을 만듭니다.

    dotnet new console
    
  3. 다음 명령을 사용하여 Visual Studio Code에서 현재 폴더를 엽니다. -r 옵션은 새 Visual Studio Code 창을 시작하지 않고 폴더를 엽니다.

    code . -r
    
  4. Explorer 창에서 Program.cs 파일을 선택하여 편집기에서 파일을 엽니다.

콘솔 앱 빌드

프로젝트에 패키지와 코드를 추가할 때입니다.

패키지 및 using 문 추가

  1. Visual Studio Code에서 터미널을 열고 다음 명령을 사용하여 프로젝트에 Microsoft.Azure.Cosmos 패키지를 추가합니다.

    dotnet add package Microsoft.Azure.Cosmos
    
  2. Program.cs 파일의 기존 코드를 삭제하고 using Microsoft.Azure.Cosmos 문을 추가합니다.

    using Microsoft.Azure.Cosmos;
    

Azure Cosmos DB 계정에 연결하는 코드 추가

  1. using 문 뒤에 다음 코드 조각을 추가합니다. 코드 조각은 상수 및 변수를 클래스에 추가하고 일부 오류 검사를 추가합니다. 코드 주석의 지침에 따라 EndpointUriPrimaryKey에 대한 자리 표시자 값을 대체해야 합니다.

    public class Program
    {
        // Replace <documentEndpoint> with the information created earlier
        private static readonly string EndpointUri = "<documentEndpoint>";
    
        // Set variable to the Primary Key from earlier.
        private static readonly string PrimaryKey = "<your primary key>";
    
        // The Cosmos client instance
        private CosmosClient cosmosClient;
    
        // The database we will create
        private Database database;
    
        // The container we will create.
        private Container container;
    
        // The names of the database and container we will create
        private string databaseId = "az204Database";
        private string containerId = "az204Container";
    
        public static async Task Main(string[] args)
        {
            try
            {
                Console.WriteLine("Beginning operations...\n");
                Program p = new Program();
                await p.CosmosAsync();
    
            }
            catch (CosmosException de)
            {
                Exception baseException = de.GetBaseException();
                Console.WriteLine("{0} error occurred: {1}", de.StatusCode, de);
            }
            catch (Exception e)
            {
                Console.WriteLine("Error: {0}", e);
            }
            finally
            {
                Console.WriteLine("End of program, press any key to exit.");
                Console.ReadKey();
            }
        }
        //The sample code below gets added below this line
    }
    
  2. Main 메서드 아래에 새 비동기 작업(CosmosAsync)을 추가하여 새 CosmosClient를 인스턴스화하고 나중에 추가할 메서드를 호출하는 코드를 추가하여 데이터베이스와 컨테이너를 만듭니다.

    public async Task CosmosAsync()
    {
        // Create a new instance of the Cosmos Client
        this.cosmosClient = new CosmosClient(EndpointUri, PrimaryKey);
    
        // Runs the CreateDatabaseAsync method
        await this.CreateDatabaseAsync();
    
        // Run the CreateContainerAsync method
        await this.CreateContainerAsync();
    }
    

데이터베이스 만들기

CosmosAsync 메서드 뒤에 CreateDatabaseAsync 메서드를 복사해서 붙여넣습니다. CreateDatabaseAsync는 아직 존재하지 않는 경우 ID az204Database를 사용하여 새 데이터베이스를 만듭니다.

private async Task CreateDatabaseAsync()
{
    // Create a new database using the cosmosClient
    this.database = await this.cosmosClient.CreateDatabaseIfNotExistsAsync(databaseId);
    Console.WriteLine("Created Database: {0}\n", this.database.Id);
}

컨테이너 만들기

CreateDatabaseAsync 메서드 아래에 CreateContainerAsync 메서드를 복사해서 붙여넣습니다.

private async Task CreateContainerAsync()
{
    // Create a new container
    this.container = await this.database.CreateContainerIfNotExistsAsync(containerId, "/LastName");
    Console.WriteLine("Created Container: {0}\n", this.container.Id);
}

애플리케이션 실행

  1. 작업을 저장하고 Visual Studio Code의 터미널에서 dotnet build 명령을 실행하여 오류가 있는지 확인합니다. 빌드가 성공하면 dotnet run 명령을 실행합니다. 콘솔에 다음 메시지가 표시됩니다.

    Beginning operations...
    
    Created Database: az204Database
    
    Created Container: az204Container
    
    End of program, press any key to exit.
    
  2. Azure Portal을 열어 Azure Cosmos DB 리소스로 이동하고 Data Explorer를 사용해 데이터베이스 및 컨테이너를 보고 결과를 확인합니다.

Azure 리소스 정리

이제 다음 명령을 실행하여 계정에서 az204-cosmos-rg 리소스 그룹을 안전하게 삭제할 수 있습니다.

az group delete --name az204-cosmos-rg --no-wait