批量创建实例

此示例演示了如何在单个请求中在集群内创建多个实例。使用此方法可以高效地一次向集群添加多个读取副本。

代码示例

C#

如需向 AlloyDB 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅 为本地开发环境设置身份验证

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

如需向 AlloyDB 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅 为本地开发环境设置身份验证


//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

如需向 AlloyDB 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅 为本地开发环境设置身份验证

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

如需向 AlloyDB 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅 为本地开发环境设置身份验证

# 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

如需向 AlloyDB 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅 为本地开发环境设置身份验证

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

后续步骤

如需搜索和过滤其他 Google Cloud 产品的代码示例,请参阅Google Cloud 示例浏览器