שליטה באחסון קבלת מטמון מכל מקום

שליטה באחסון קבלת מטמון מכל מקום

המשך למידה

לקבלת הסבר מפורט שכולל את דוגמת הקוד הזו, קראו את המאמר:

דוגמת קוד

C++

למידע נוסף, קראו את מאמרי העזרה של Cloud Storage C++ API.

כדי לבצע אימות ב-Cloud Storage, אתם צריכים להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.

namespace storagecontrol = google::cloud::storagecontrol_v2;
[](storagecontrol::StorageControlClient client,
   std::string const& cache_name) {
  auto anywhere_cache = client.GetAnywhereCache(cache_name);
  if (!anywhere_cache) throw std::move(anywhere_cache).status();
  std::cout << "Got anywhere cache: " << anywhere_cache->name() << "\n";
}

Java

למידע נוסף, קראו את מאמרי העזרה של Cloud Storage Java API.

כדי לבצע אימות ב-Cloud Storage, אתם צריכים להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.


import com.google.storage.control.v2.AnywhereCache;
import com.google.storage.control.v2.GetAnywhereCacheRequest;
import com.google.storage.control.v2.StorageControlClient;
import java.io.IOException;

public final class AnywhereCacheGet {

  public static void anywhereCacheGet(String cacheName) throws IOException {
    try (StorageControlClient storageControl = StorageControlClient.create()) {

      GetAnywhereCacheRequest request =
          GetAnywhereCacheRequest.newBuilder().setName(cacheName).build();

      AnywhereCache anywhereCache = storageControl.getAnywhereCache(request);

      System.out.printf("Got anywhere cache: %s%n", anywhereCache.getName());
    }
  }
}

Node.js

למידע נוסף, קראו את מאמרי העזרה של Cloud Storage Node.js API.

כדי לבצע אימות ב-Cloud Storage, אתם צריכים להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.

const {StorageControlClient} = require('@google-cloud/storage-control').v2;

const client = new StorageControlClient();

/**
 * Gets an Anywhere Cache instance.
 *
 * @param {string} bucketName Name of the bucket (e.g., 'my-bucket')
 * @param {string} anywhereCacheZone The zone of the Anywhere Cache instance (e.g., 'us-central1-a')
 */
async function getAnywhereCacheSample(
  bucketName,
  anywhereCacheZone = 'us-central1-a',
) {
  const name = client.anywhereCachePath('_', bucketName, anywhereCacheZone);

  const request = {
    name,
  };

  try {
    const [anywhereCache] = await client.getAnywhereCache(request);
    console.log(`Anywhere Cache ${anywhereCache.name} retrieved successfully.`);
    console.log(`  State: ${anywhereCache.state}`);
    console.log(`  TTL: ${anywhereCache.ttl?.seconds} seconds`);
    console.log(`  Admission Policy: ${anywhereCache.admissionPolicy}`);
    console.log(`  Zone: ${anywhereCache.zone}`);
  } catch (err) {
    if (err.code === status.NOT_FOUND) {
      console.error(
        `Error: Anywhere Cache in zone '${anywhereCacheZone}' not found in bucket '${bucketName}'.`,
      );
      console.error(
        'Please ensure the Anywhere Cache zone and bucket name are correct and the cache exists.',
      );
    } else {
      console.error(`Error getting Anywhere Cache:`, err);
    }
  }
}

PHP

למידע נוסף, קראו את מאמרי העזרה של Cloud Storage PHP API.

כדי לבצע אימות ב-Cloud Storage, אתם צריכים להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.

use Google\Cloud\Storage\Control\V2\Client\StorageControlClient;
use Google\Cloud\Storage\Control\V2\GetAnywhereCacheRequest;

/**
 * Gets an Anywhere Cache instance.
 *
 * @param string $bucketName The name of your Cloud Storage bucket.
 *        (e.g. 'my-bucket')
 * @param string $anywhereCacheId Uniquely identifies the cache.
 *        (e.g. 'us-east1-b')
 */
function get_anywhere_cache(string $bucketName, string $anywhereCacheId): void
{
    $storageControlClient = new StorageControlClient();

    // Set project to "_" to signify global bucket
    $formattedName = $storageControlClient->anywhereCacheName('_', $bucketName, $anywhereCacheId);

    $request = new GetAnywhereCacheRequest([
        'name' => $formattedName,
    ]);

    $response = $storageControlClient->getAnywhereCache($request);

    printf('Got anywhere cache: %s', $response->getName());
}

Python

למידע נוסף, קראו את מאמרי העזרה של Cloud Storage Python API.

כדי לבצע אימות ב-Cloud Storage, אתם צריכים להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.

import google.api_core.exceptions
from google.cloud import storage_control_v2


def get_anywhere_cache(
    bucket_name: str,
    anywhere_cache_zone: str,
) -> None:
    """Retrieves the metadata for a specific Anywhere Cache instance.

    Args:
        bucket_name: The name of the bucket where the Anywhere Cache is located.
        anywhere_cache_zone: The ID zone of the Anywhere Cache instance to retrieve.
                           Example: "us-central1-a"
    """
    client = storage_control_v2.StorageControlClient()

    anywhere_cache_name = client.anywhere_cache_path(
        project="_",
        bucket=bucket_name,
        anywhere_cache=anywhere_cache_zone,
    )

    try:
        anywhere_cache = client.get_anywhere_cache(name=anywhere_cache_name)

        print(f"Successfully retrieved Anywhere Cache: {anywhere_cache.name}")
        print(f"  Zone: {anywhere_cache.zone}")
        print(f"  State: {anywhere_cache.state}")
        print(f"  TTL: {anywhere_cache.ttl.seconds} seconds")
        print(f"  Admission Policy: {anywhere_cache.admission_policy}")
        print(f"  Create Time: {anywhere_cache.create_time}")
        print(f"  Update Time: {anywhere_cache.update_time}")

    except google.api_core.exceptions.NotFound:
        print(
            f"Error: Anywhere Cache '{anywhere_cache_zone}' not found in bucket "
            f"'{bucket_name}'. "
            "Please ensure the Anywhere Cache ID and bucket name are correct."
        )
    except Exception as e:
        print(f"An unexpected error occurred: {e}")

Ruby

למידע נוסף, קראו את מאמרי העזרה של Cloud Storage Ruby API.

כדי לבצע אימות ב-Cloud Storage, אתם צריכים להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.

require "google/cloud/storage/control"

# Retrieves an Anywhere Cache configuration for a given bucket.
#
# @param bucket_name [String] The name of the bucket.
# @param anywhere_cache_id [String] A value that, along with the bucket's
#   name, uniquely identifies the cache. (e.g. "us-east1-b")
#
# @example
#   get_anywhere_cache(
#     bucket_name: "your-unique-bucket-name",
#     anywhere_cache_id: "us-east1-b"
#   )
#
def get_anywhere_cache bucket_name:, anywhere_cache_id:
  # Create a client object. The client can be reused for multiple calls.
  storage_control_client = Google::Cloud::Storage::Control.storage_control
  # Set project to "_" to signify global bucket
  parent = "projects/_/buckets/#{bucket_name}"
  name = "#{parent}/anywhereCaches/#{anywhere_cache_id}"

  # Create a request.
  request = Google::Cloud::Storage::Control::V2::GetAnywhereCacheRequest.new(
    name: name
  )
  # The request retrieves the cache in the specified bucket.
  # The cache is identified by the specified ID.
  # The cache is in the specified bucket.

  begin
    result = storage_control_client.get_anywhere_cache request
    puts "Successfully fetched anywhereCache - #{result.name}."
  rescue Google::Cloud::Error => e
    puts "Failed to fetch AnywhereCache. Error: #{e.message}"
  end
end

המאמרים הבאים

כדי לחפש ולסנן דוגמאות קוד למוצרים אחרים של Google Cloud , אפשר להיעזר בדפדפן לדוגמאות שלGoogle Cloud .