Criar realm

Crie um realm para o Game Servers.

Páginas de documentação que incluem esta amostra de código

Para visualizar o exemplo de código usado em contexto, consulte a seguinte documentação:

Exemplo de código

Go

Para saber como instalar e usar a biblioteca de clientes para Game Servers, consulte Bibliotecas de cliente do Game Servers.


import (
	"context"
	"fmt"
	"io"

	gaming "cloud.google.com/go/gaming/apiv1"
	gamingpb "google.golang.org/genproto/googleapis/cloud/gaming/v1"
)

// createRealm creates a game server realm.
func createRealm(w io.Writer, projectID, location, realmID string) error {
	// projectID := "my-project"
	// location := "global"
	// realmID := "myrealm"
	ctx := context.Background()
	client, err := gaming.NewRealmsClient(ctx)
	if err != nil {
		return fmt.Errorf("NewRealmsClient: %v", err)
	}
	defer client.Close()

	req := &gamingpb.CreateRealmRequest{
		Parent:  fmt.Sprintf("projects/%s/locations/%s", projectID, location),
		RealmId: realmID,
		Realm: &gamingpb.Realm{
			TimeZone:    "US/Pacific",
			Description: "My Game Server Realm",
		},
	}

	op, err := client.CreateRealm(ctx, req)
	if err != nil {
		return fmt.Errorf("CreateRealm: %v", err)
	}
	resp, err := op.Wait(ctx)
	if err != nil {
		return fmt.Errorf("Wait: %v", err)
	}

	fmt.Fprintf(w, "Realm created: %v", resp.Name)
	return nil
}

Java

Para saber como instalar e usar a biblioteca de clientes para Game Servers, consulte Bibliotecas de cliente do Game Servers.


import com.google.api.gax.longrunning.OperationFuture;
import com.google.cloud.gaming.v1.CreateRealmRequest;
import com.google.cloud.gaming.v1.OperationMetadata;
import com.google.cloud.gaming.v1.Realm;
import com.google.cloud.gaming.v1.RealmsServiceClient;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class CreateRealm {
  public static void createRealm(String projectId, String regionId, String realmId)
      throws InterruptedException, ExecutionException, TimeoutException, IOException {
    // String projectId = "your-project-id";
    // String regionId = "us-central1-f";
    // String realmId = "your-realm-id";
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the "close" method on the client to safely clean up any remaining background resources.
    try (RealmsServiceClient client = RealmsServiceClient.create()) {
      String parent = String.format("projects/%s/locations/%s", projectId, regionId);
      String realmName = String.format("%s/realms/%s", parent, realmId);

      Realm realm =
          Realm.newBuilder().setName(realmName).setTimeZone("America/Los_Angeles").build();

      CreateRealmRequest request =
          CreateRealmRequest.newBuilder()
              .setParent(parent)
              .setRealmId(realmId)
              .setRealm(realm)
              .build();

      OperationFuture<Realm, OperationMetadata> call = client.createRealmAsync(request);
      Realm result = call.get(1, TimeUnit.MINUTES);

      System.out.println("Realm created: " + result.getName());
    }
  }
}

Node.js

Para saber como instalar e usar a biblioteca de clientes para Game Servers, consulte Bibliotecas de cliente do Game Servers.

const {RealmsServiceClient} = require('@google-cloud/game-servers');

const client = new RealmsServiceClient();

async function createRealm() {
  /**
   * TODO(developer): Uncomment these variables before running the sample.
   */
  // const projectId = 'Your Google Cloud Project ID';
  // const location = 'A Compute Engine region, e.g. "us-central1"';
  // const realmId = 'A unique identifier for the realm';
  const request = {
    parent: `projects/${projectId}/locations/${location}`,
    realmId: realmId,
    realm: {
      // Must use a supported time zone name.
      // See https://cloud.google.com/dataprep/docs/html/Supported-Time-Zone-Values_66194188
      timeZone: 'US/Pacific',
      description: 'My Game Server realm',
    },
  };

  const [operation] = await client.createRealm(request);
  const results = await operation.promise();
  const [realm] = results;

  console.log('Realm created:');

  console.log(`\tRealm name: ${realm.name}`);
  console.log(`\tRealm description: ${realm.description}`);
  console.log(`\tRealm time zone: ${realm.timeZone}`);
}

createRealm();

Python

Para saber como instalar e usar a biblioteca de clientes para Game Servers, consulte Bibliotecas de cliente do Game Servers.

def create_realm(project_id, location, realm_id):
    """Creates a realm."""

    client = gaming.RealmsServiceClient()

    request = realms.CreateRealmRequest(
        parent=f"projects/{project_id}/locations/{location}",
        realm_id=realm_id,
        realm=realms.Realm(
            description="My Realm",
            time_zone="US/Pacific",
        ),
    )

    operation = client.create_realm(request)
    print(f"Create realm operation: {operation.operation.name}")
    operation.result(timeout=120)

A seguir

Para pesquisar e filtrar exemplos de código de outros produtos do Google Cloud, consulte o navegador de exemplos do Google Cloud.