클라이언트 초기화

Rust용 Cloud 클라이언트 라이브러리는 클라이언트 구조체를Google Cloud 서비스의 기본 인터페이스로 사용하며, 서비스에서 제공하는 각 RPC에 해당하는 메서드를 사용합니다. 서비스를 호출하기 전에 클라이언트를 초기화합니다.

이 문서에서는 기본 구성으로 Secret Manager 클라이언트를 초기화하고 RPC를 호출하는 방법을 보여줍니다. 다른 모든 Google Cloud 서비스에도 동일한 패턴이 적용됩니다.

시작하기 전에

이 문서의 코드를 실행하기 전에 다음 기본 요건을 완료하세요.

종속 항목

Cargo.toml 파일에 필요한 크레이트를 추가합니다.

cargo add google-cloud-secretmanager-v1 google-cloud-gax anyhow
cargo add tokio --features macros,rt-multi-thread

클라이언트 초기화 및 RPC 실행

클라이언트를 초기화하려면 클라이언트 구조체에서 builder를 호출하여 ClientBuilder를 가져온 다음 build를 호출합니다. 다음 단계를 완료하여 기본 설정으로 클라이언트를 초기화하고 RPC를 호출합니다.

  1. SecretManagerService 클라이언트 유형을 가져옵니다.

    use google_cloud_secretmanager_v1::client::SecretManagerService;

  2. 기본 구성으로 클라이언트를 빌드합니다.

    let client = SecretManagerService::builder().build().await?;

  3. 초기화된 클라이언트를 사용하여 list_locations를 호출합니다. 그러면 프로젝트에 대해 Secret Manager에서 지원하는 위치가 나열됩니다.

    use google_cloud_gax::paginator::Paginator as _;
    let mut items = client
        .list_locations()
        .set_name(format!("projects/{project_id}"))
        .by_page();
    while let Some(page) = items.next().await {
        let page = page?;
        for location in page.locations {
            println!("{}", location.name);
        }
    }

다음과 유사한 결과가 출력됩니다.

projects/PROJECT_NUMBER/locations/europe-west8
projects/PROJECT_NUMBER/locations/europe-west9
projects/PROJECT_NUMBER/locations/us-east5

이 출력에서 PROJECT_NUMBER는 Google Cloud 프로젝트의 숫자 프로젝트 번호입니다.

코드 완성

다음 예시에서는 클라이언트 초기화와 list_locations 호출을 실행 가능한 프로그램으로 결합합니다.

pub async fn initialize_client(project_id: &str) -> anyhow::Result<()> {
    use google_cloud_secretmanager_v1::client::SecretManagerService;

    // Initialize a client with the default configuration. This is an
    // asynchronous operation that may fail, as it requires acquiring an an
    // access token.
    let client = SecretManagerService::builder().build().await?;

    // Once initialized, use the client to make requests.
    use google_cloud_gax::paginator::Paginator as _;
    let mut items = client
        .list_locations()
        .set_name(format!("projects/{project_id}"))
        .by_page();
    while let Some(page) = items.next().await {
        let page = page?;
        for location in page.locations {
            println!("{}", location.name);
        }
    }

    Ok(())
}

#[tokio::main]
async fn main() -> anyhow::Result<()> {
    let project_id = std::env::args().nth(1).unwrap();

    initialize_client(&project_id).await
}