Mostrar lista de clusters

Enumera los clústeres de servidores para videojuegos en un dominio determinado.

Páginas de documentación que incluyen esta muestra de código

Para ver la muestra de código usada en contexto, consulta la siguiente documentación:

Muestra de código

C#

Si deseas obtener información para instalar y usar la biblioteca cliente de Game Servers, consulta las bibliotecas cliente de Game Servers.


using Google.Api.Gax;
using Google.Cloud.Gaming.V1;
using System.Collections.Generic;
using System.Linq;

public class ListClustersSample
{
    public IList<GameServerCluster> ListClusters(
        string projectId, string regionId, string realmId)
    {
        // Create the client.
        GameServerClustersServiceClient client = GameServerClustersServiceClient.Create();

        ListGameServerClustersRequest request = new ListGameServerClustersRequest
        {
            ParentAsRealmName = RealmName.FromProjectLocationRealm(projectId, regionId, realmId),
            View = GameServerClusterView.Full
        };

        // Make the request.
        PagedEnumerable<ListGameServerClustersResponse, GameServerCluster> response = client.ListGameServerClusters(request);

        // You could iterate through response and write the cluster.Name and
        // cluster.ClusterState to the console to see the installed versions of Agones
        // and Kubernetes on each cluster.

        // The returned sequence will lazily perform RPCs as it's being iterated over.
        return response.ToList();
    }
}

Comienza a usarlo

Si deseas obtener información para instalar y usar la biblioteca cliente de Game Servers, consulta las bibliotecas cliente de Game Servers.


import (
	"context"
	"fmt"
	"io"

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

// listGameServerClusters lists the clusters registered with a realm.
func listGameServerClusters(w io.Writer, projectID, location, realmID string) error {
	// projectID := "my-project"
	// location := "global"
	// realmID := "myrealm"
	ctx := context.Background()
	client, err := gaming.NewGameServerClustersClient(ctx)
	if err != nil {
		return fmt.Errorf("NewGameServerClustersClient: %v", err)
	}
	defer client.Close()

	req := &gamingpb.ListGameServerClustersRequest{
		Parent: fmt.Sprintf("projects/%s/locations/%s/realms/%s", projectID, location, realmID),
		View:   gamingpb.GameServerClusterView_FULL,
	}

	it := client.ListGameServerClusters(ctx, req)
	for {
		resp, err := it.Next()
		if err == iterator.Done {
			break
		}
		if err != nil {
			return fmt.Errorf("Next: %v", err)
		}

		fmt.Fprintf(w, "Cluster listed: %v\n", resp.Name)
		fmt.Fprintf(w, "Cluster installed Agones version: %v\n", resp.ClusterState.AgonesVersionInstalled)
		fmt.Fprintf(w, "Cluster installed Kubernetes version: %v\n", resp.ClusterState.KubernetesVersionInstalled)
		fmt.Fprintf(w, "Cluster installation state: %v\n", resp.ClusterState.InstallationState)
	}

	return nil
}

Java

Si deseas obtener información para instalar y usar la biblioteca cliente de Game Servers, consulta las bibliotecas cliente de Game Servers.


import com.google.cloud.gaming.v1.GameServerCluster;
import com.google.cloud.gaming.v1.GameServerClusterView;
import com.google.cloud.gaming.v1.GameServerClustersServiceClient;
import com.google.cloud.gaming.v1.GameServerClustersServiceClient.ListGameServerClustersPagedResponse;
import com.google.cloud.gaming.v1.ListGameServerClustersRequest;
import com.google.cloud.gaming.v1.RealmName;
import com.google.common.base.Strings;
import java.io.IOException;

public class ListClusters {

  public static void listGameServerClusters(String projectId, String regionId, String realmId)
      throws IOException {
    // String projectId = "your-project-id";
    // String regionId = "us-central1-f";
    // 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 (GameServerClustersServiceClient client = GameServerClustersServiceClient.create()) {
      ListGameServerClustersRequest request =
          ListGameServerClustersRequest.newBuilder()
              .setParent(RealmName.of(projectId, regionId, realmId).toString())
              .setView(GameServerClusterView.FULL)
              .build();
      ListGameServerClustersPagedResponse response = client.listGameServerClusters(request);
      for (GameServerCluster cluster : response.iterateAll()) {
        System.out.println("Game Server Cluster found: " + cluster.getName());
        System.out.println(
            "Cluster installed Agones version: "
                + cluster.getClusterState().getAgonesVersionInstalled());
        System.out.println(
            "Cluster installed Kubernetes version: "
                + cluster.getClusterState().getKubernetesVersionInstalled());
        System.out.println(
            "Cluster installation state: " + cluster.getClusterState().getInstallationState());
      }

      while (!Strings.isNullOrEmpty(response.getNextPageToken())) {
        ListGameServerClustersRequest request2 =
            ListGameServerClustersRequest.newBuilder()
                .setParent(RealmName.of(projectId, regionId, realmId).toString())
                .setPageToken(response.getNextPageToken())
                .build();
        response = client.listGameServerClusters(request2);
        for (GameServerCluster cluster : response.iterateAll()) {
          System.out.println("Game Server Cluster found: " + cluster.getName());
          System.out.println(
              "Cluster installed Agones version: "
                  + cluster.getClusterState().getAgonesVersionInstalled());
          System.out.println(
              "Cluster installed Kubernetes version: "
                  + cluster.getClusterState().getKubernetesVersionInstalled());
          System.out.println(
              "Cluster installation state: " + cluster.getClusterState().getInstallationState());
        }
      }
    }
  }
}

Node.js

Si deseas obtener información para instalar y usar la biblioteca cliente de Game Servers, consulta las bibliotecas cliente de Game Servers.

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

const client = new GameServerClustersServiceClient();

async function listGameServerClusters() {
  /**
   * 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 = 'The ID of the realm to locate this cluster in';
  const request = {
    // Provide full resource name of a Game Server Realm
    parent: client.realmPath(projectId, location, realmId),
    view: 'FULL',
  };

  const results = await client.listGameServerClusters(request);
  const [clusters] = results;

  for (const cluster of clusters) {
    console.log('Game Server Cluster:');
    console.log(`\tCluster name: ${cluster.name}`);
    console.log(`\tCluster description: ${cluster.description}`);
    console.log(
      `\tCluster installed Agones version: ${cluster.clusterState.agonesVersionInstalled}`
    );
    console.log(
      `\tCluster installed Kubernetes version: ${cluster.clusterState.kubernetesVersionInstalled}`
    );
    console.log(
      `\tCluster installation state: ${cluster.clusterState.installationState}`
    );
    console.log(
      `\tGKE cluster: ${cluster.connectionInfo.gkeClusterReference.cluster}`
    );
  }
}

listGameServerClusters();

Python

Si deseas obtener información para instalar y usar la biblioteca cliente de Game Servers, consulta las bibliotecas cliente de Game Servers.

def list_clusters(project_id, location, realm_id):
    """Lists the existing game server clusters."""

    client = gaming.GameServerClustersServiceClient()

    response = client.list_game_server_clusters(
        request=game_server_clusters.ListGameServerClustersRequest(
            parent=f"projects/{project_id}/locations/{location}/realms/{realm_id}",
            view=game_server_clusters.GameServerClusterView.FULL,
        )
    )

    for cluster in response.game_server_clusters:
        print(f"Name: {cluster.name}")
        print(f"State:\n{cluster.cluster_state}")

    return response.game_server_clusters

¿Qué sigue?

Para buscar y filtrar muestras de código para otros productos de Google Cloud, consulta el navegador de muestra de Google Cloud.