클러스터 만들기

Game Server 클러스터를 만듭니다.

이 코드 샘플이 포함된 문서 페이지

컨텍스트에서 사용된 코드 샘플을 보려면 다음 문서를 참조하세요.

코드 샘플

Go

Game Servers용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Game Servers 클라이언트 라이브러리를 참조하세요.


import (
	"context"
	"fmt"
	"io"

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

// createCluster registers a game server cluster.
func createCluster(w io.Writer, projectID, location, realmID, clusterID, gkeClusterName string) error {
	// projectID := "my-project"
	// location := "global"
	// realmID := "myrealm"
	// clusterID := "mycluster"
	// gkeClusterName := "projects/1234/locations/us-central1/clusters/gke-cluster"
	ctx := context.Background()
	client, err := gaming.NewGameServerClustersClient(ctx)
	if err != nil {
		return fmt.Errorf("NewGameServerClustersClient: %v", err)
	}
	defer client.Close()

	req := &gamingpb.CreateGameServerClusterRequest{
		Parent:              fmt.Sprintf("projects/%s/locations/%s/realms/%s", projectID, location, realmID),
		GameServerClusterId: clusterID,
		GameServerCluster: &gamingpb.GameServerCluster{
			ConnectionInfo: &gamingpb.GameServerClusterConnectionInfo{
				Namespace: "default",
				ClusterReference: &gamingpb.GameServerClusterConnectionInfo_GkeClusterReference{
					GkeClusterReference: &gamingpb.GkeClusterReference{
						Cluster: gkeClusterName,
					},
				},
			},
			Description: "My Game Server Cluster",
		},
	}

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

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

자바

Game Servers용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Game Servers 클라이언트 라이브러리를 참조하세요.


import com.google.api.gax.longrunning.OperationFuture;
import com.google.cloud.gaming.v1.CreateGameServerClusterRequest;
import com.google.cloud.gaming.v1.GameServerCluster;
import com.google.cloud.gaming.v1.GameServerClusterConnectionInfo;
import com.google.cloud.gaming.v1.GameServerClustersServiceClient;
import com.google.cloud.gaming.v1.GkeClusterReference;
import com.google.cloud.gaming.v1.OperationMetadata;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class CreateCluster {

  public static void createGameServerCluster(
      String projectId, String regionId, String realmId, String clusterId, String gkeName)
      throws InterruptedException, ExecutionException, TimeoutException, IOException {
    // String projectId = "your-project-id";
    // String regionId = "us-central1-f";
    // String realmId = "your-realm-id";
    // String clusterId = "your-game-server-cluster-id";
    // String gkeName = "projects/your-project-id/locations/us-central1/clusters/test";
    // 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()) {
      String parent =
          String.format("projects/%s/locations/%s/realms/%s", projectId, regionId, realmId);
      String clusterName = String.format("%s/gameServerClusters/%s", parent, clusterId);

      GameServerCluster gameServerCluster =
          GameServerCluster.newBuilder()
              .setName(clusterName)
              .setConnectionInfo(
                  GameServerClusterConnectionInfo.newBuilder()
                      .setGkeClusterReference(
                          GkeClusterReference.newBuilder().setCluster(gkeName).build())
                      .setNamespace("default"))
              .build();

      CreateGameServerClusterRequest request =
          CreateGameServerClusterRequest.newBuilder()
              .setParent(parent)
              .setGameServerClusterId(clusterId)
              .setGameServerCluster(gameServerCluster)
              .build();

      OperationFuture<GameServerCluster, OperationMetadata> call =
          client.createGameServerClusterAsync(request);

      GameServerCluster created = call.get(1, TimeUnit.MINUTES);
      System.out.println("Game Server Cluster created: " + created.getName());
    }
  }
}

Node.js

Game Servers용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Game Servers 클라이언트 라이브러리를 참조하세요.

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

const client = new GameServerClustersServiceClient();

async function createGameServerCluster() {
  /**
   * 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 gameClusterId = 'A unique ID for this Game Server Cluster';
  // const gkeClusterName= 'The full resource name of the GKE cluster to use';
  const request = {
    // Provide full resource name of a Game Server Realm
    parent: client.realmPath(projectId, location, realmId),
    gameServerClusterId: gameClusterId,
    gameServerCluster: {
      description: 'My Game Server Cluster',
      connectionInfo: {
        gkeClusterReference: {
          // Provide full resource name of a Kubernetes Engine cluster
          // In the form of 'projects/<project-id>/locations/<location>/clusters/<gke-cluster-name>'
          cluster: gkeClusterName,
        },
        namespace: 'default',
      },
    },
  };

  const [operation] = await client.createGameServerCluster(request);
  const [result] = await operation.promise();

  console.log('Game Server Cluster created:');
  console.log(`\tCluster name: ${result.name}`);
  console.log(`\tCluster description: ${result.description}`);
  console.log(
    `\tGKE cluster: ${result.connectionInfo.gkeClusterReference.cluster}`
  );
}

createGameServerCluster();

Python

Game Servers용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Game Servers 클라이언트 라이브러리를 참조하세요.

def create_cluster(project_id, location, realm_id, cluster_id, gke_cluster_name):
    """Creates a game server cluster."""

    client = gaming.GameServerClustersServiceClient()

    gke_cluster_reference = game_server_clusters.GkeClusterReference(
        cluster=gke_cluster_name,
    )
    request = game_server_clusters.CreateGameServerClusterRequest(
        parent=f"projects/{project_id}/locations/{location}/realms/{realm_id}",
        game_server_cluster_id=cluster_id,
        game_server_cluster=game_server_clusters.GameServerCluster(
            description="My Game Server Cluster",
            connection_info=game_server_clusters.GameServerClusterConnectionInfo(
                gke_cluster_reference=gke_cluster_reference,
                namespace="default",
            ),
        ),
    )

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

다음 단계

다른 Google Cloud 제품의 코드 샘플을 검색하고 필터링하려면 Google Cloud 샘플 브라우저를 참조하세요.