创建部署

本页面介绍了如何创建、列出和描述 Game Servers 部署。部署管理您可以部署到任何或所有大区的一个或多个软件版本。如需查看创建部署,添加配置然后发布部署的端到端示例,请参阅配置集群扩缩行为

准备工作

开始之前,我们建议您先了解 Game Servers 概览中的关键概念。请确保您已执行以下任务:

  • 确保您已启用 Game Services API。
  • 启用 Game Services API
  • 选择安装了 Cloud SDK 的 shell,或使用 API 客户端:
  • Cloud Shell

    如需启动 Cloud Shell,请执行以下步骤:

    1. 转到 Google Cloud Console。

      Google Cloud Console

    2. 在控制台的右上角,点击激活 Cloud Shell 按钮:

    控制台下方的框架内会打开一个 Cloud Shell 会话。您可以使用此 shell 运行 gcloud 命令。

    本地 shell

    如需安装 gcloud,请安装 Cloud SDK,其中包含 gcloud 命令行工具。

    确认您已为 gcloud 命令行工具设置所需的默认项目(否则,您需要以后为每个命令明确指定标志 --project):

    gcloud config list project
    

    如果无法运行以下命令来设置默认项目,请将 PROJECT_ID 替换为所需的项目 ID:

    gcloud config set project PROJECT_ID
    

    运行以下命令以验证 Google Cloud SDK 的版本。Game Servers 需要 306.0.0 或更高版本的 SDK。

    gcloud version
    

    如需更新安装,请运行以下命令:

    gcloud components update
    

    curl / PowerShell

    如需将 REST API 与 curl 或 Windows PowerShell 搭配使用,请执行以下操作:

    1. 创建服务帐号。
    2. 以 JSON 文件的格式下载私钥。
    3. 将环境变量 GOOGLE_APPLICATION_CREDENTIALS 设置为包含您的服务帐号密钥的 JSON 文件的路径。 此变量仅适用于当前的 shell 会话,因此,如果您打开新的会话,请重新设置该变量。

    客户端库

    您可以使用客户端库以编程方式控制 Google Cloud Game Servers。如需了解库和身份验证的使用说明,请参阅客户端库概览

创建部署

控制台

  1. 在 Cloud Console 中,转到 Game Servers 部署页面。

    转到 Game Servers

  2. 点击创建部署

  3. 名称框中,输入此部署的唯一标识符。

  4. (可选)在说明框中,输入此部署的说明。

  5. 点击创建

gcloud

您可以使用 gcloud 命令行工具创建部署。

如需创建部署,请运行以下命令并将 deploymentID 替换为适当的值:

gcloud game servers deployments create deploymentID

REST 和命令行

在使用任何请求数据之前,请先进行以下替换:

  • PROJECT_IDIAM 设置中列出的 Google Cloud 项目 ID
  • DEPLOYMENT_ID:用户定义的部署标识符

请求 JSON 正文:

{
  "name": "projects/PROJECT_ID/locations/global/gameServerDeployments/DEPLOYMENT_ID",
}

如需发送您的请求,请展开以下选项之一:

您应该收到类似以下内容的 JSON 响应:

{
  "name": "projects/PROJECT_ID/locations/global/operations/OPERATION_ID",
  "metadata": {
    "@type": "type.googleapis.com/google.cloud.gaming.v1.OperationMetadata",
    "createTime": CREATE_TIME,
    "target": "projects/PROJECT_ID/locations/global/gameServerDeployments/DEPLOYMENT_ID",
    "verb": "create",
    "requestedCancellation": false,
    "apiVersion": "v1"
  },
  "done": false
}

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"
)

// createGameServerDeployment creates a game server deployment.
func createGameServerDeployment(w io.Writer, projectID, deploymentID string) error {
	// projectID := "my-project"
	// deploymentID := "mydeployment"
	ctx := context.Background()
	client, err := gaming.NewGameServerDeploymentsClient(ctx)
	if err != nil {
		return fmt.Errorf("NewGameServerDeploymentsClient: %v", err)
	}
	defer client.Close()

	// Location is hard coded as global, as Game Server Deployments can only be
	// created in global.  This is done for all operations on Game Server
	// Deployments, as well as for its child resource types.
	req := &gamingpb.CreateGameServerDeploymentRequest{
		Parent:       fmt.Sprintf("projects/%s/locations/global", projectID),
		DeploymentId: deploymentID,
		GameServerDeployment: &gamingpb.GameServerDeployment{
			Description: "My Game Server Deployment",
		},
	}

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

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

Java

如需了解如何安装和使用 Game Servers 客户端库,请参阅 Game Servers 客户端库


import com.google.api.gax.longrunning.OperationFuture;
import com.google.cloud.gaming.v1.CreateGameServerDeploymentRequest;
import com.google.cloud.gaming.v1.GameServerDeployment;
import com.google.cloud.gaming.v1.GameServerDeploymentsServiceClient;
import com.google.cloud.gaming.v1.OperationMetadata;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class CreateDeployment {
  public static void createGameServerDeployment(String projectId, String deploymentId)
      throws IOException, InterruptedException, ExecutionException, TimeoutException {
    // String projectId = "your-project-id";
    // String deploymentId = "your-game-server-deployment-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 (GameServerDeploymentsServiceClient client = GameServerDeploymentsServiceClient.create()) {

      // Build a spec as shown at https://agones.dev/site/docs/reference/gameserver/
      JsonObject container = new JsonObject();
      container.addProperty("name", "default");
      container.addProperty("image", "gcr.io/agones-images/default:1.0");

      JsonArray containers = new JsonArray();
      containers.add(container);

      JsonObject spec = new JsonObject();
      spec.add("containers", containers);

      JsonObject template = new JsonObject();
      template.add("spec", spec);

      JsonObject port = new JsonObject();
      port.addProperty("name", "default");

      JsonArray ports = new JsonArray();
      ports.add(port);

      JsonObject specObject = new JsonObject();
      specObject.add("ports", ports);
      specObject.add("template", template);

      String parent = String.format("projects/%s/locations/global", projectId);
      String deploymentName = String.format("%s/gameServerDeployments/%s", parent, deploymentId);

      GameServerDeployment gameServerDeployment =
          GameServerDeployment.newBuilder().setName(deploymentName).build();

      CreateGameServerDeploymentRequest request =
          CreateGameServerDeploymentRequest.newBuilder()
              .setParent(parent)
              .setDeploymentId(deploymentId)
              .setGameServerDeployment(gameServerDeployment)
              .build();

      OperationFuture<GameServerDeployment, OperationMetadata> call =
          client.createGameServerDeploymentAsync(request);

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

Node.js

如需了解如何安装和使用 Game Servers 客户端库,请参阅 Game Servers 客户端库

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

const client = new GameServerDeploymentsServiceClient();

async function createGameServerDeployment() {
  /**
   * TODO(developer): Uncomment these variables before running the sample.
   */
  // const projectId = 'Your Google Cloud Project ID';
  // const deploymentId = 'A unique ID for the Game Server Deployment';
  const request = {
    parent: `projects/${projectId}/locations/global`,
    deploymentId: deploymentId,
    gameServerDeployment: {
      description: 'nodejs test deployment',
    },
  };

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

  console.log('Game Server Deployment created:');
  console.log(`\t Deployment name: ${result.name}`);
  console.log(`\t Deployment description: ${result.description}`);
}

createGameServerDeployment();

Python

如需了解如何安装和使用 Game Servers 客户端库,请参阅 Game Servers 客户端库

def create_deployment(project_id, deployment_id):
    """Creates a game server deployment."""

    client = gaming.GameServerDeploymentsServiceClient()

    # Location is hard coded as global, as game server deployments can
    # only be created in global.  This is done for all operations on
    # game server deployments, as well as for its child resource types.
    request = game_server_deployments.CreateGameServerDeploymentRequest(
        parent=f"projects/{project_id}/locations/global",
        deployment_id=deployment_id,
        game_server_deployment=game_server_deployments.GameServerDeployment(
            description="My Game Server Deployment"
        ),
    )

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

列出部署

控制台

  1. 在 Cloud Console 中,转到 Game Servers 部署页面。

    转到 Game Servers

  2. 您可以使用过滤条件框,按不同属性过滤部署列表。

gcloud

您可以使用 gcloud 命令行工具列出部署。

如需列出部署,请运行以下命令:

gcloud game servers deployments list

REST 和命令行

在使用任何请求数据之前,请先进行以下替换:

  • PROJECT_IDIAM 设置中列出的 Google Cloud 项目 ID

根据您发送的请求,请展开以下选项之一:

您应该收到类似以下内容的 JSON 响应:

{
  "gameServerDeployments": [
    {
      "name": "projects/PROJECT_ID/locations/global/gameServerDeployments/my-deployment-1",
      "createTime": CREATE_TIME,
      "updateTime": UPDATE_TIME,
      "etag": "RI8hTm3ZaMNZ3qRVeKVcxcN3W26_oR559JYofnFi69A"
    },
    {
      "name": "projects/PROJECT_ID/locations/global/gameServerDeployments/my-deployment-2",
      "createTime": CREATE_TIME,
      "updateTime": UPDATE_TIME,
      "etag": "az38kwIY4X3WdP2SA0fkTGib9hwVj7iXLFXAtIzMLpc"
    }
  ]
}

Go

如需了解如何安装和使用 Game Servers 客户端库,请参阅 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"
)

// listGameServerDeployments lists the game server deployments.
func listGameServerDeployments(w io.Writer, projectID string) error {
	// projectID := "my-project"
	// realmID := "myrealm"
	ctx := context.Background()
	client, err := gaming.NewGameServerDeploymentsClient(ctx)
	if err != nil {
		return fmt.Errorf("NewGameServerDeploymentsClient: %v", err)
	}
	defer client.Close()

	req := &gamingpb.ListGameServerDeploymentsRequest{
		Parent: fmt.Sprintf("projects/%s/locations/global", projectID),
	}

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

		fmt.Fprintf(w, "Deployment listed: %v\n", resp.Name)
	}

	return nil
}

Java

如需了解如何安装和使用 Game Servers 客户端库,请参阅 Game Servers 客户端库


import com.google.cloud.gaming.v1.GameServerDeployment;
import com.google.cloud.gaming.v1.GameServerDeploymentsServiceClient;
import com.google.cloud.gaming.v1.GameServerDeploymentsServiceClient.ListGameServerDeploymentsPagedResponse;
import com.google.cloud.gaming.v1.ListGameServerDeploymentsRequest;
import com.google.common.base.Strings;
import java.io.IOException;

public class ListDeployments {
  public static void listGameServerDeployments(String projectId) throws IOException {
    // String projectId = "your-project-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 (GameServerDeploymentsServiceClient client = GameServerDeploymentsServiceClient.create()) {
      String parent = String.format("projects/%s/locations/global", projectId);

      ListGameServerDeploymentsPagedResponse response = client.listGameServerDeployments(parent);
      for (GameServerDeployment deployment : response.iterateAll()) {
        System.out.println("Game Server Deployment found: " + deployment.getName());
      }

      while (!Strings.isNullOrEmpty(response.getNextPageToken())) {
        ListGameServerDeploymentsRequest request =
            ListGameServerDeploymentsRequest.newBuilder()
                .setParent(parent)
                .setPageToken(response.getNextPageToken())
                .build();
        response = client.listGameServerDeployments(request);
        for (GameServerDeployment deployment : response.iterateAll()) {
          System.out.println("Game Server Deployment found: " + deployment.getName());
        }
      }
    }
  }
}

Node.js

如需了解如何安装和使用 Game Servers 客户端库,请参阅 Game Servers 客户端库

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

const client = new GameServerDeploymentsServiceClient();

async function listGameServerDeployments() {
  /**
   * TODO(developer): Uncomment these variables before running the sample.
   */
  // const projectId = 'Your Google Cloud Project ID';
  const request = {
    parent: `projects/${projectId}/locations/global`,
  };

  const [results] = await client.listGameServerDeployments(request);
  for (const deployment of results) {
    console.log(`Deployment name: ${deployment.name}`);
    console.log(`Deployment description: ${deployment.description}`);

    const createTime = deployment.createTime;
    const createDate = new Date(createTime.seconds * 1000);
    console.log(
      `Deployment created on: ${createDate.toLocaleDateString()}\n`
    );
  }
}

listGameServerDeployments();

Python

如需了解如何安装和使用 Game Servers 客户端库,请参阅 Game Servers 客户端库

def list_deployments(project_id):
    """Lists the existing game server deployments."""

    client = gaming.GameServerDeploymentsServiceClient()

    # Location is hard coded as global, as game server deployments can
    # only be created in global.  This is done for all operations on
    # game server deployments, as well as for its child resource types.
    response = client.list_game_server_deployments(
        parent=f"projects/{project_id}/locations/global"
    )

    for deployment in response.game_server_deployments:
        print(f"Name: {deployment.name}")

    return response.game_server_deployments

描述部署

控制台

  1. 在 Cloud Console 中,转到 Game Servers 部署页面。

    转到 Game Servers

  2. 您可以使用过滤条件框,按不同属性过滤部署列表。

  3. 在表格的最后一列中,点击省略号 并选择列出配置。您可以通过此页面查看部署的活跃配置和无效配置。

  4. 要为部署创建新配置,请点击创建配置。如需更新发布,请点击管理发布

gcloud

您可以使用 gcloud 命令行工具获取部署的详细信息,例如创建时间或更新时间。

如需描述部署,请运行以下命令,并将 deploymentID 替换为您之前创建的部署的标识符:

gcloud game servers deployments describe deploymentID

REST 和命令行

在使用任何请求数据之前,请先进行以下替换:

  • PROJECT_IDIAM 设置中列出的 Google Cloud 项目 ID
  • DEPLOYMENT_ID:用户定义的部署标识符

根据您发送的请求,请展开以下选项之一:

您应该收到类似以下内容的 JSON 响应:

{
  "name": "projects/PROJECT_ID/locations/global/gameServerDeployments/DEPLOYMENT_ID",
  "createTime": CREATE_TIME,
  "updateTime": UPDATE_TIME,
  "etag": "RI8hTm3ZaMNZ3qRVeKVcxcN3W26_oR559JYofnFi69A"
}

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"
)

// getGameServerDeployment retrieves info on a game server deployment.
func getGameServerDeployment(w io.Writer, projectID, deploymentID string) error {
	// projectID := "my-project"
	// deploymentID := "mydeployment"
	ctx := context.Background()
	client, err := gaming.NewGameServerDeploymentsClient(ctx)
	if err != nil {
		return fmt.Errorf("NewGameServerDeploymentsClient: %v", err)
	}
	defer client.Close()

	req := &gamingpb.GetGameServerDeploymentRequest{
		Name: fmt.Sprintf("projects/%s/locations/global/gameServerDeployments/%s", projectID, deploymentID),
	}

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

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

Java

如需了解如何安装和使用 Game Servers 客户端库,请参阅 Game Servers 客户端库


import com.google.cloud.gaming.v1.GameServerDeployment;
import com.google.cloud.gaming.v1.GameServerDeploymentsServiceClient;
import java.io.IOException;

public class GetDeployment {
  public static void getGameServerDeployment(String projectId, String deploymentId)
      throws IOException {
    // String projectId = "your-project-id";
    // String deploymentId = "your-game-server-deployment-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 (GameServerDeploymentsServiceClient client = GameServerDeploymentsServiceClient.create()) {
      String deploymentName =
          String.format(
              "projects/%s/locations/global/gameServerDeployments/%s", projectId, deploymentId);

      GameServerDeployment deployment = client.getGameServerDeployment(deploymentName);

      System.out.println("Game Server Deployment found: " + deployment.getName());
    }
  }
}

Node.js

如需了解如何安装和使用 Game Servers 客户端库,请参阅 Game Servers 客户端库

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

const client = new GameServerDeploymentsServiceClient();

async function getGameServerDeployment() {
  /**
   * TODO(developer): Uncomment these variables before running the sample.
   */
  // const projectId = 'Your Google Cloud Project ID';
  // const deploymentId = 'A unique ID for the Game Server Deployment';
  const request = {
    // The full resource name
    name: client.gameServerDeploymentPath(projectId, 'global', deploymentId),
  };

  const [deployment] = await client.getGameServerDeployment(request);
  console.log(`Deployment name: ${deployment.name}`);
  console.log(`Deployment description: ${deployment.description}`);

  const createTime = deployment.createTime;
  const createDate = new Date(createTime.seconds * 1000);
  console.log(`Deployment created on: ${createDate.toLocaleDateString()}\n`);
}

getGameServerDeployment();

Python

如需了解如何安装和使用 Game Servers 客户端库,请参阅 Game Servers 客户端库

def get_deployment(project_id, deployment_id):
    """Gets a game server deployment."""

    client = gaming.GameServerDeploymentsServiceClient()

    # Location is hard coded as global, as game server deployments can
    # only be created in global.  This is done for all operations on
    # game server deployments, as well as for its child resource types.
    request = game_server_deployments.GetGameServerDeploymentRequest(
        name=f"projects/{project_id}/locations/global/gameServerDeployments/{deployment_id}",
    )

    response = client.get_game_server_deployment(request)
    print(f"Get deployment response:\n{response}")
    return response

后续步骤