替换默认端点

Rust 客户端库会自动为每项服务配置端点。某些应用可能需要替换默认端点,原因可能是其网络有特定要求,也可能是需要使用服务的区域版本。本指南将介绍如何替换默认值。

前提条件

本指南使用 Secret Manager API。如需启用此 API,请按照服务快速入门操作。

如需查看 Rust 客户端库的完整设置说明,请参阅 Rust 使用入门

依赖项

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

cargo add google-cloud-secretmanager-v1 google-cloud-gax

默认端点

首先,请查看如何将客户端库与默认端点搭配使用。首先,编写一些 use 声明,以简化示例的其余部分:

  1. 在接收项目 ID 作为参数的函数中编写示例:

    /// # Parameters
    /// - `project_id`: the id of a Google Cloud project, or its numeric ID.
    ///   For example: `my-project`.
    pub async fn sample(project_id: &str) -> anyhow::Result<()> {

  2. 添加一些 use 声明以简化示例代码:

    pub use google_cloud_gax::paginator::ItemPaginator;
    pub use google_cloud_secretmanager_v1::client::SecretManagerService;

  3. 使用默认值初始化客户端:

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

  4. 然后照常使用此客户端:

    let mut items = client
        .list_secrets()
        .set_parent(format!("projects/{project_id}"))
        .by_item();
    println!("listing all secrets in project {project_id}");
    while let Some(secret) = items.next().await.transpose()? {
        println!("  {secret:?}");
    }
    println!("DONE");

替换默认端点

在此示例中,我们将客户端库配置为使用 Secret Manager 的区域端点。同一替换项可用于配置具有某个专用访问选项的端点,或用于支持位置服务端点的服务。

  1. 与之前一样,编写一个接收项目 ID 和区域作为参数的示例:

    /// # Parameters
    /// - `project_id`: the id of a Google Cloud project, or its numeric ID.
    ///   For example: `my-project`.
    /// - `region`: the id of a Gooogle Cloud region. For example `us-central1`.
    pub async fn sample(project_id: &str, region: &str) -> anyhow::Result<()> {

  2. 添加一些 use 声明以简化代码:

    pub use google_cloud_gax::paginator::ItemPaginator;
    pub use google_cloud_secretmanager_v1::client::SecretManagerService;

  3. 使用目标端点初始化客户端:

    let client = SecretManagerService::builder()
        .with_endpoint(format!("https://secretmanager.{region}.rep.googleapis.com"))
        .build()
        .await?;

  4. 然后照常使用此客户端:

    let mut items = client
        .list_secrets()
        .set_parent(format!("projects/{project_id}/locations/{region}"))
        .by_item();
    println!("listing all secrets in project {project_id} and region {region}");
    while let Some(secret) = items.next().await.transpose()? {
        println!("  {secret:?}");
    }
    println!("DONE");