Membuat instance secara batch

Contoh ini menunjukkan cara membuat beberapa instance dalam cluster dalam satu permintaan. Gunakan metode ini untuk menambahkan beberapa replika baca ke cluster sekaligus secara efisien.

Contoh kode

C#

Untuk melakukan autentikasi ke AlloyDB, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, lihat Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

using Google.Cloud.AlloyDb.V1;
using Google.LongRunning;

public sealed partial class GeneratedAlloyDBAdminClientSnippets
{
    /// <summary>Snippet for BatchCreateInstances</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 BatchCreateInstancesRequestObject()
    {
        // Create client
        AlloyDBAdminClient alloyDBAdminClient = AlloyDBAdminClient.Create();
        // Initialize request argument(s)
        BatchCreateInstancesRequest request = new BatchCreateInstancesRequest
        {
            ParentAsClusterName = ClusterName.FromProjectLocationCluster("[PROJECT]", "[LOCATION]", "[CLUSTER]"),
            Requests = new CreateInstanceRequests(),
            RequestId = "",
        };
        // Make the request
        Operation<BatchCreateInstancesResponse, OperationMetadata> response = alloyDBAdminClient.BatchCreateInstances(request);

        // Poll until the returned long-running operation is complete
        Operation<BatchCreateInstancesResponse, OperationMetadata> completedResponse = response.PollUntilCompleted();
        // Retrieve the operation result
        BatchCreateInstancesResponse 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<BatchCreateInstancesResponse, OperationMetadata> retrievedResponse = alloyDBAdminClient.PollOnceBatchCreateInstances(operationName);
        // Check if the retrieved long-running operation has completed
        if (retrievedResponse.IsCompleted)
        {
            // If it has completed, then access the result
            BatchCreateInstancesResponse retrievedResult = retrievedResponse.Result;
        }
    }
}

Go

Untuk melakukan autentikasi ke AlloyDB, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, lihat Menyiapkan autentikasi untuk lingkungan pengembangan lokal.


//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.BatchCreateInstancesRequest{
		// TODO: Fill request struct fields.
		// See https://pkg.go.dev/cloud.google.com/go/alloydb/apiv1/alloydbpb#BatchCreateInstancesRequest.
	}
	op, err := c.BatchCreateInstances(ctx, req)
	if err != nil {
		// TODO: Handle error.
	}

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

Java

Untuk melakukan autentikasi ke AlloyDB, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, lihat Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

import com.google.cloud.alloydb.v1.AlloyDBAdminClient;
import com.google.cloud.alloydb.v1.BatchCreateInstancesRequest;
import com.google.cloud.alloydb.v1.BatchCreateInstancesResponse;
import com.google.cloud.alloydb.v1.ClusterName;
import com.google.cloud.alloydb.v1.CreateInstanceRequests;

public class SyncBatchCreateInstances {

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

  public static void syncBatchCreateInstances() 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()) {
      BatchCreateInstancesRequest request =
          BatchCreateInstancesRequest.newBuilder()
              .setParent(ClusterName.of("[PROJECT]", "[LOCATION]", "[CLUSTER]").toString())
              .setRequests(CreateInstanceRequests.newBuilder().build())
              .setRequestId("requestId693933066")
              .build();
      BatchCreateInstancesResponse response =
          alloyDBAdminClient.batchCreateInstancesAsync(request).get();
    }
  }
}

Python

Untuk melakukan autentikasi ke AlloyDB, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, lihat Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

# 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_batch_create_instances():
    # Create a client
    client = alloydb_v1.AlloyDBAdminClient()

    # Initialize request argument(s)
    requests = alloydb_v1.CreateInstanceRequests()
    requests.create_instance_requests.parent = "parent_value"
    requests.create_instance_requests.instance_id = "instance_id_value"
    requests.create_instance_requests.instance.instance_type = "SECONDARY"

    request = alloydb_v1.BatchCreateInstancesRequest(
        parent="parent_value",
        requests=requests,
    )

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

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

    response = operation.result()

    # Handle the response
    print(response)

Ruby

Untuk melakukan autentikasi ke AlloyDB, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, lihat Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

require "google/cloud/alloy_db/v1"

##
# Snippet for the batch_create_instances 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#batch_create_instances.
#
def batch_create_instances
  # 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::BatchCreateInstancesRequest.new

  # Call the batch_create_instances method.
  result = client.batch_create_instances 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

Langkah berikutnya

Untuk menelusuri dan memfilter contoh kode untuk produk Google Cloud lainnya, lihat browser contohGoogle Cloud .