Elenchi di controllo dell'archiviazione Anywhere Cache

Elenchi di controllo dell'archiviazione Anywhere Cache

Per saperne di più

Per la documentazione dettagliata che include questo esempio di codice, vedi quanto segue:

Esempio di codice

C++

Per saperne di più, consulta la documentazione di riferimento dell'API Cloud Storage C++.

Per eseguire l'autenticazione in Cloud Storage, configura le Credenziali predefinite dell'applicazione. Per saperne di più, vedi Configura l'autenticazione per le librerie client.

namespace storagecontrol = google::cloud::storagecontrol_v2;
[](storagecontrol::StorageControlClient client,
   std::string const& bucket_name) {
  auto const parent = std::string{"projects/_/buckets/"} + bucket_name;
  for (auto anywhere_cache : client.ListAnywhereCaches(parent)) {
    if (!anywhere_cache) throw std::move(anywhere_cache).status();
    std::cout << anywhere_cache->name() << "\n";
  }
}

Java

Per saperne di più, consulta la documentazione di riferimento dell'API Cloud Storage Java.

Per eseguire l'autenticazione in Cloud Storage, configura le Credenziali predefinite dell'applicazione. Per saperne di più, vedi Configura l'autenticazione per le librerie client.


import com.google.storage.control.v2.AnywhereCache;
import com.google.storage.control.v2.BucketName;
import com.google.storage.control.v2.ListAnywhereCachesRequest;
import com.google.storage.control.v2.StorageControlClient;
import com.google.storage.control.v2.StorageControlClient.ListAnywhereCachesPagedResponse;
import java.io.IOException;

public final class AnywhereCacheList {

  public static void anywhereCacheList(String bucketName) throws IOException {
    try (StorageControlClient storageControl = StorageControlClient.create()) {

      ListAnywhereCachesRequest request =
          ListAnywhereCachesRequest.newBuilder()
              .setParent(BucketName.format("_", bucketName))
              .build();

      ListAnywhereCachesPagedResponse page = storageControl.listAnywhereCaches(request);
      for (AnywhereCache anywhereCache : page.iterateAll()) {
        System.out.println(anywhereCache.getName());
      }
    }
  }
}

Node.js

Per saperne di più, consulta la documentazione di riferimento dell'API Cloud Storage Node.js.

Per eseguire l'autenticazione in Cloud Storage, configura le Credenziali predefinite dell'applicazione. Per saperne di più, vedi Configura l'autenticazione per le librerie client.

const {StorageControlClient} = require('@google-cloud/storage-control');
const {status} = require('@grpc/grpc-js');

const client = new StorageControlClient();

/**
 * Lists all Anywhere Cache instances for a given bucket.
 *
 * Anywhere Cache provides a way to cache frequently accessed objects closer to
 * your applications, reducing latency and egress costs.
 *
 * @param {string} bucketName The name of the bucket to list Anywhere Caches for.
 */
async function listAnywhereCaches(bucketName) {
  const parent = `projects/_/buckets/${bucketName}`;

  const request = {
    parent: parent,
  };

  try {
    const [anywhereCaches] = await client.listAnywhereCaches(request);

    if (anywhereCaches.length === 0) {
      console.log(`No Anywhere Caches found for bucket ${bucketName}.`);
      return;
    }

    console.log('Anywhere Caches:');
    for (const cache of anywhereCaches) {
      console.log(`- Name: ${cache.name}`);
      console.log(`  Zone: ${cache.zone}`);
      console.log(`  State: ${cache.state}`);
      console.log(`  TTL: ${cache.ttl ? cache.ttl.seconds + 's' : 'N/A'}`);
      console.log(`  Admission Policy: ${cache.admissionPolicy || 'N/A'}`);
      if (cache.createTime) {
        const createTime = new Date(
          cache.createTime.seconds * 1000 + cache.createTime.nanos / 1000000,
        );
        console.log(`  Create Time: ${createTime}`);
      }
    }
  } catch (err) {
    if (err.code === status.NOT_FOUND) {
      console.error(
        `Error: The specified bucket '${bucketName}' was not found.`,
      );
      console.error(
        'Please ensure the bucket exists and is accessible within the project.',
      );
    } else if (err.code === status.PERMISSION_DENIED) {
      console.error(
        `Error: Permission denied. Ensure the service account has the necessary permissions (e.g., storage.anywhereCaches.list) for bucket '${bucketName}'.`,
      );
    } else {
      console.error('Error listing Anywhere Caches:', err);
    }
  }
}

PHP

Per saperne di più, consulta la documentazione di riferimento dell'API Cloud Storage PHP.

Per eseguire l'autenticazione in Cloud Storage, configura le Credenziali predefinite dell'applicazione. Per saperne di più, vedi Configura l'autenticazione per le librerie client.

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

/**
 * Lists Anywhere Cache instances for a given bucket.
 *
 * @param string $bucketName The name of your Cloud Storage bucket.
 *        (e.g. 'my-bucket')
 */
function list_anywhere_caches(string $bucketName): void
{
    $storageControlClient = new StorageControlClient();

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

    $request = new ListAnywhereCachesRequest([
        'parent' => $formattedName,
    ]);

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

    foreach ($response as $anywhereCache) {
        printf('Anywhere cache name: %s' . PHP_EOL, $anywhereCache->getName());
    }
}

Python

Per saperne di più, consulta la documentazione di riferimento dell'API Cloud Storage Python.

Per eseguire l'autenticazione in Cloud Storage, configura le Credenziali predefinite dell'applicazione. Per saperne di più, vedi Configura l'autenticazione per le librerie client.

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


def list_anywhere_caches(
    bucket_name: str,
) -> None:
    """Lists Anywhere Cache instances for a given bucket.

    Args:
        bucket_name: The name of the bucket to list Anywhere Caches for.
    """
    client = storage_control_v2.StorageControlClient()

    parent = f"projects/_/buckets/{bucket_name}"

    try:
        anywhere_caches = client.list_anywhere_caches(parent=parent)

        found_caches = False
        print(f"Anywhere Caches for bucket '{bucket_name}':")
        for cache in anywhere_caches:
            found_caches = True
            print(f"  Name: {cache.name}")
            print(f"  Zone: {cache.zone}")
            print(f"  State: {cache.state}")
            print(f"  TTL: {cache.ttl.seconds} seconds")
            print(f"  Admission Policy: {cache.admission_policy}")
            print("----------------------------------------")

        if not found_caches:
            print("  No Anywhere Cache instances found for this bucket.")

    except google.api_core.exceptions.NotFound:
        print(f"Error: Bucket '{bucket_name}' not found.")
        print("Please ensure the bucket name is correct and the bucket exists.")
    except google.api_core.exceptions.PermissionDenied:
        print(
            f"Error: Permission denied to list Anywhere Caches for bucket '{bucket_name}'."
        )
        print(
            "Please ensure the authenticated service account has 'storage.anywhereCaches.list' permission."
        )
    except google.api_core.exceptions.GoogleAPIError as e:
        print(f"An unexpected API error occurred: {e}")
        print("Please check the error details and your project/bucket configuration.")

Ruby

Per saperne di più, consulta la documentazione di riferimento dell'API Cloud Storage Ruby.

Per eseguire l'autenticazione in Cloud Storage, configura le Credenziali predefinite dell'applicazione. Per saperne di più, vedi Configura l'autenticazione per le librerie client.

require "google/cloud/storage/control"

def list_anywhere_caches bucket_name:
  # The Name of your GCS bucket
  # bucket_name = "your-unique-bucket-name"

  # 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}"

  # Create a request.
  request = Google::Cloud::Storage::Control::V2::ListAnywhereCachesRequest.new(
    parent: parent
  )
  # The request lists all caches in the specified bucket.
  # The caches are identified by the specified bucket name.
  begin
    result = storage_control_client.list_anywhere_caches request
    result.response.anywhere_caches.each do |item|
      puts "AnywhereCache #{item.name} found in list."
    end
  rescue Google::Cloud::Error => e
    puts "Failed to list AnywhereCaches. Error: #{e.message}"
  end
end

Passaggi successivi

Per cercare e filtrare gli esempi di codice per altri prodotti Google Cloud , consulta il browser degli esempi diGoogle Cloud .