Contrôle du stockage - Mettre en pause Anywhere Cache

Contrôle du stockage - Mettre en pause Anywhere Cache

Exemple de code

C++

Pour en savoir plus, consultez la documentation de référence de l'API Cloud Storage en langage C++.

Pour vous authentifier auprès de Cloud Storage, configurez le service Identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour les bibliothèques clientes.

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

C#

Pour en savoir plus, consultez la documentation de référence de l'API Cloud Storage en langage C#.

Pour vous authentifier auprès de Cloud Storage, configurez le service Identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour les bibliothèques clientes.


using Google.Cloud.Storage.Control.V2;
using System;

public class StorageControlPauseAnywhereCacheSample
{
    /// <summary>Pauses an anywhere cache instance in the specified bucket.</summary>
    /// <param name="bucketName">The name of the bucket that owns the anywhere cache instance.</param>
    /// <param name="anywhereCacheId">The unique identifier of the cache instance to pause.</param>
    public AnywhereCache StorageControlPauseAnywhereCache(string bucketName = "your-unique-bucket-name",
        string anywhereCacheId = "us-east1-b")
    {
        StorageControlClient storageControlClient = StorageControlClient.Create();

        // Set project to "_" to signify globally scoped bucket.
        string anywhereCacheName = $"projects/_/buckets/{bucketName}/anywhereCaches/{anywhereCacheId}";

        var request = new PauseAnywhereCacheRequest
        {
            Name = anywhereCacheName
        };

        AnywhereCache pausedCache = storageControlClient.PauseAnywhereCache(request);

        Console.WriteLine($"Paused Anywhere Cache Instance: {pausedCache.Name}");

        return pausedCache;
    }
}

Java

Pour en savoir plus, consultez la documentation de référence de l'API Cloud Storage en langage Java.

Pour vous authentifier auprès de Cloud Storage, configurez le service Identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour les bibliothèques clientes.


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

public final class AnywhereCachePause {

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

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

      AnywhereCache anywhereCache = storageControl.pauseAnywhereCache(request);

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

Node.js

Pour en savoir plus, consultez la documentation de référence de l'API Cloud Storage en langage Node.js.

Pour vous authentifier auprès de Cloud Storage, configurez le service Identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour les bibliothèques clientes.

/**
 * Pauses an Anywhere Cache instance.
 *
 * This synchronous function stops the ingestion of new data for a cache that's in a RUNNING state.
 * While PAUSED, you can still read existing data (which resets the TTL), but no new data is ingested.
 * The cache can be returned to the RUNNING state by calling the resume function.
 *
 * @param {string} bucketName The name of the bucket where the cache resides.
 * Example: 'your-gcp-bucket-name'
 * @param {string} cacheName The unique identifier of the cache instance.
 * Example: 'my-anywhere-cache-id'
 */

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

// Instantiates a client
const controlClient = new StorageControlClient();

async function callPauseAnywhereCache() {
  const anywhereCachePath = controlClient.anywhereCachePath(
    '_',
    bucketName,
    cacheName
  );

  // Create the request
  const request = {
    name: anywhereCachePath,
  };

  try {
    // Run request
    const [response] = await controlClient.pauseAnywhereCache(request);

    console.log(`Successfully paused anywhere cache: ${response.name}.`);
    console.log(`  Current State: ${response.state}`);
  } catch (error) {
    // Catch and handle potential API errors.
    console.error(
      `Error pausing Anywhere Cache '${cacheName}': ${error.message}`
    );

    if (error.code === 5) {
      // NOT_FOUND (gRPC code 5)
      console.error(
        `Please ensure the cache '${cacheName}' exists in bucket '${bucketName}'.`
      );
    } else if (error.code === 9) {
      // FAILED_PRECONDITION (gRPC code 9)
      console.error(
        `Cache '${cacheName}' may not be in a state that allows pausing (e.g., must be RUNNING).`
      );
    }
    throw error;
  }
}

callPauseAnywhereCache();

PHP

Pour en savoir plus, consultez la documentation de référence de l'API Cloud Storage en langage PHP.

Pour vous authentifier auprès de Cloud Storage, configurez le service Identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour les bibliothèques clientes.

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

/**
 * Pauses 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 pause_anywhere_cache(string $bucketName, string $anywhereCacheId): void
{
    $storageControlClient = new StorageControlClient();

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

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

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

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

Ruby

Pour en savoir plus, consultez la documentation de référence de l'API Cloud Storage en langage Ruby.

Pour vous authentifier auprès de Cloud Storage, configurez le service Identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour les bibliothèques clientes.

require "google/cloud/storage/control"

# Pauses a specific Anywhere Cache instance in a Cloud Storage bucket.
# This operation does not delete the cache; it can be resumed later using
# the `resume_anywhere_cache` method.
#
# @param bucket_name [String] The name of the Cloud Storage bucket.
# @param anywhere_cache_id [String] The ID of the Anywhere Cache instance to pause.
#   This is often the zone where the cache is located, e.g., "us-east1-b".
#
# @example
#   pause_anywhere_cache(
#     bucket_name: "your-unique-bucket-name",
#     anywhere_cache_id: "us-east1-b"
#   )
#
def pause_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::PauseAnywhereCacheRequest.new(
    name: name
  )
  # The request pauses the cache, but does not delete it.
  # The cache can be resumed later.
  # The cache is paused in the specified bucket.
  begin
    result = storage_control_client.pause_anywhere_cache request
    puts "Successfully #{result.state&.downcase} anywhereCache - #{result.name}."
  rescue Google::Cloud::Error => e
    puts "Failed to pause AnywhereCache. Error: #{e.message}"
  end
end

Rust

use google_cloud_storage::client::StorageControl;

pub async fn sample(
    client: &StorageControl,
    bucket_id: &str,
    cache_id: &str,
) -> anyhow::Result<()> {
    let cache = client
        .pause_anywhere_cache()
        .set_name(format!(
            "projects/_/buckets/{bucket_id}/anywhereCaches/{cache_id}"
        ))
        .send()
        .await?;
    println!("Paused anywhere cache: {:?}", cache);
    Ok(())
}

Étapes suivantes

Pour rechercher et filtrer des exemples de code pour d'autres produits Google Cloud , consultez l'explorateur d'exemplesGoogle Cloud .