הפעלת לקוח

ספריות הלקוח של Cloud ל-Rust משתמשות במבני לקוח כממשק הראשי לשירותיGoogle Cloud , עם שיטות שתואמות לכל RPC שהשירות מציע. לפני שקוראים לשירות, צריך להפעיל את הלקוח שלו.

במאמר הזה מוסבר איך להפעיל לקוח של Secret Manager עם הגדרת ברירת המחדל שלו ואיך לבצע קריאה ל-RPC. אותה תבנית חלה על כל שירותי Google Cloud האחרים.

לפני שמתחילים

לפני שמריצים את הקוד שבמסמך הזה, צריך לבצע את הפעולות הבאות:

יחסי תלות

מוסיפים את ה-crates הנדרשים לקובץ 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
}