Restablece un clúster a partir de una copia de seguridad

En este fragmento, se muestra cómo restablecer un clúster a partir de una copia de seguridad especificada. Usa esta operación para recuperar un clúster a un momento anterior o para crear un clúster nuevo basado en una copia de seguridad existente.

Muestra de código

C#

Para autenticarte en AlloyDB, configura las credenciales predeterminadas de la aplicación. Para obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

using Google.Api.Gax.ResourceNames;
using Google.Cloud.AlloyDb.V1;
using Google.LongRunning;

public sealed partial class GeneratedAlloyDBAdminClientSnippets
{
    /// <summary>Snippet for RestoreCluster</summary>
    /// <remarks>
    /// This snippet has been automatically generated and should be regarded as a code template only.
    /// It will require modifications to work:
    /// - It may require correct/in-range values for request initialization.
    /// - It may require specifying regional endpoints when creating the service client as shown in
    ///   https://cloud.google.com/dotnet/docs/reference/help/client-configuration#endpoint.
    /// </remarks>
    public void RestoreClusterRequestObject()
    {
        // Create client
        AlloyDBAdminClient alloyDBAdminClient = AlloyDBAdminClient.Create();
        // Initialize request argument(s)
        RestoreClusterRequest request = new RestoreClusterRequest
        {
            ParentAsLocationName = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
            ClusterId = "",
            Cluster = new Cluster(),
            BackupSource = new BackupSource(),
            RequestId = "",
            ValidateOnly = false,
        };
        // Make the request
        Operation<Cluster, OperationMetadata> response = alloyDBAdminClient.RestoreCluster(request);

        // Poll until the returned long-running operation is complete
        Operation<Cluster, OperationMetadata> completedResponse = response.PollUntilCompleted();
        // Retrieve the operation result
        Cluster result = completedResponse.Result;

        // Or get the name of the operation
        string operationName = response.Name;
        // This name can be stored, then the long-running operation retrieved later by name
        Operation<Cluster, OperationMetadata> retrievedResponse = alloyDBAdminClient.PollOnceRestoreCluster(operationName);
        // Check if the retrieved long-running operation has completed
        if (retrievedResponse.IsCompleted)
        {
            // If it has completed, then access the result
            Cluster retrievedResult = retrievedResponse.Result;
        }
    }
}

Go

Para autenticarte en AlloyDB, configura las credenciales predeterminadas de la aplicación. Para obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.


//go:build examples

package main

import (
	"context"

	alloydb "cloud.google.com/go/alloydb/apiv1"
	alloydbpb "cloud.google.com/go/alloydb/apiv1/alloydbpb"
)

func main() {
	ctx := context.Background()
	// This snippet has been automatically generated and should be regarded as a code template only.
	// It will require modifications to work:
	// - It may require correct/in-range values for request initialization.
	// - It may require specifying regional endpoints when creating the service client as shown in:
	//   https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options
	c, err := alloydb.NewAlloyDBAdminClient(ctx)
	if err != nil {
		// TODO: Handle error.
	}
	defer c.Close()

	req := &alloydbpb.RestoreClusterRequest{
		// TODO: Fill request struct fields.
		// See https://pkg.go.dev/cloud.google.com/go/alloydb/apiv1/alloydbpb#RestoreClusterRequest.
	}
	op, err := c.RestoreCluster(ctx, req)
	if err != nil {
		// TODO: Handle error.
	}

	resp, err := op.Wait(ctx)
	if err != nil {
		// TODO: Handle error.
	}
	// TODO: Use resp.
	_ = resp
}

Java

Para autenticarte en AlloyDB, configura las credenciales predeterminadas de la aplicación. Para obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

import com.google.cloud.alloydb.v1.AlloyDBAdminClient;
import com.google.cloud.alloydb.v1.Cluster;
import com.google.cloud.alloydb.v1.LocationName;
import com.google.cloud.alloydb.v1.RestoreClusterRequest;

public class SyncRestoreCluster {

  public static void main(String[] args) throws Exception {
    syncRestoreCluster();
  }

  public static void syncRestoreCluster() throws Exception {
    // This snippet has been automatically generated and should be regarded as a code template only.
    // It will require modifications to work:
    // - It may require correct/in-range values for request initialization.
    // - It may require specifying regional endpoints when creating the service client as shown in
    // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
    try (AlloyDBAdminClient alloyDBAdminClient = AlloyDBAdminClient.create()) {
      RestoreClusterRequest request =
          RestoreClusterRequest.newBuilder()
              .setParent(LocationName.of("[PROJECT]", "[LOCATION]").toString())
              .setClusterId("clusterId561939637")
              .setCluster(Cluster.newBuilder().build())
              .setRequestId("requestId693933066")
              .setValidateOnly(true)
              .build();
      Cluster response = alloyDBAdminClient.restoreClusterAsync(request).get();
    }
  }
}

Python

Para autenticarte en AlloyDB, configura las credenciales predeterminadas de la aplicación. Para obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

# This snippet has been automatically generated and should be regarded as a
# code template only.
# It will require modifications to work:
# - It may require correct/in-range values for request initialization.
# - It may require specifying regional endpoints when creating the service
#   client as shown in:
#   https://googleapis.dev/python/google-api-core/latest/client_options.html
from google.cloud import alloydb_v1


def sample_restore_cluster():
    # Create a client
    client = alloydb_v1.AlloyDBAdminClient()

    # Initialize request argument(s)
    backup_source = alloydb_v1.BackupSource()
    backup_source.backup_name = "backup_name_value"

    cluster = alloydb_v1.Cluster()
    cluster.backup_source.backup_name = "backup_name_value"
    cluster.network = "network_value"

    request = alloydb_v1.RestoreClusterRequest(
        backup_source=backup_source,
        parent="parent_value",
        cluster_id="cluster_id_value",
        cluster=cluster,
    )

    # Make the request
    operation = client.restore_cluster(request=request)

    print("Waiting for operation to complete...")

    response = operation.result()

    # Handle the response
    print(response)

Ruby

Para autenticarte en AlloyDB, configura las credenciales predeterminadas de la aplicación. Para obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

require "google/cloud/alloy_db/v1"

##
# Snippet for the restore_cluster call in the AlloyDBAdmin service
#
# This snippet has been automatically generated and should be regarded as a code
# template only. It will require modifications to work:
# - It may require correct/in-range values for request initialization.
# - It may require specifying regional endpoints when creating the service
# client as shown in https://cloud.google.com/ruby/docs/reference.
#
# This is an auto-generated example demonstrating basic usage of
# Google::Cloud::AlloyDB::V1::AlloyDBAdmin::Client#restore_cluster.
#
def restore_cluster
  # Create a client object. The client can be reused for multiple calls.
  client = Google::Cloud::AlloyDB::V1::AlloyDBAdmin::Client.new

  # Create a request. To set request fields, pass in keyword arguments.
  request = Google::Cloud::AlloyDB::V1::RestoreClusterRequest.new

  # Call the restore_cluster method.
  result = client.restore_cluster request

  # The returned object is of type Gapic::Operation. You can use it to
  # check the status of an operation, cancel it, or wait for results.
  # Here is how to wait for a response.
  result.wait_until_done! timeout: 60
  if result.response?
    p result.response
  else
    puts "No response received."
  end
end

¿Qué sigue?

Si quieres buscar y filtrar muestras de código para otros productos de Google Cloud , consulta el navegador de muestras deGoogle Cloud .