如何初始化客户端

Rust 版 Google Cloud 客户端库使用客户端作为与特定服务交互的主要抽象层。客户端以 Rust 结构体实现,其方法对应于服务提供的每个 RPC。如需使用 Rust 客户端库来使用Google Cloud 服务,您需要先初始化客户端。

在本指南中,您将初始化一个客户端,然后使用该客户端通过 Secret Manager API 发出 RPC。这种结构适用于 Google Cloud中的任何其他服务。

在按照本指南进行操作之前,您应先完成以下事项:

依赖项

对于 Rust,您必须在 Cargo.toml 文件中声明依赖项:

$ cargo add google-cloud-secretmanager-v1

如需初始化客户端,您首先需要调用 Client::builder() 以获取适当的 ClientBuilder,然后对该构建器调用 build() 以创建客户端。

以下代码会创建一个采用默认配置的客户端,该配置旨在满足大多数使用情形的要求。

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

成功初始化客户端后,您可以使用它来发出 RPC:

    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);
        }
    }

此示例展示了对 list_locations 的调用,该调用会返回有关服务(在本例中为 Secret Manager)支持的位置的信息。

示例的输出应如下所示:

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