初始化用戶端

Rust 適用的 Cloud 用戶端程式庫使用用戶端結構體做為Google Cloud 服務的主要介面,並提供與服務提供的各個 RPC 對應的方法。呼叫服務前,請先初始化用戶端。

本文說明如何使用預設設定初始化 Secret Manager 用戶端,並呼叫 RPC。其他所有 Google Cloud 服務也適用相同模式。

事前準備

執行本文件中的程式碼前,請先完成下列必要條件:

依附元件

在 Cargo.toml 檔案中新增必要的 crate:

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
}