创建配置

本页面介绍了如何在部署中注册、编辑、列出和查看 Game Servers 配置的详细信息。 此配置定义了 Agones 队列规范,其中包括游戏服务器计数、缓冲区和游戏服务器版本的相关信息。此配置还定义了扩缩配置,用于指定队列自动扩缩以满足需求的方式。

准备工作

开始之前,我们建议您先了解 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。如需了解库和身份验证的使用说明,请参阅客户端库概览

创建配置

确保您已创建 Game Servers 部署

控制台

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

    转到 Game Servers

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

  3. 要为部署创建新配置,请点击创建配置

  4. 配置名称框中,输入此配置的唯一标识符。

  5. (可选)在说明框中,输入此配置的说明。

  6. 队列配置名称框中,输入此队列配置的唯一标识符。

  7. 队列规范框中,输入队列规范

  8. (可选)在扩缩配置下,您可以指定一个或多个会自动纵向扩容或纵向缩容的配置。点击添加以添加扩缩配置。

    1. 扩缩配置名称框中,输入此扩缩配置的唯一标识符。
    2. (可选)在开始时间结束时间框中,安排此扩缩配置将处于活跃状态的时间段。如需了解详情,请参阅创建扩缩时间表
    3. Autoscape 规范框中,输入扩缩规范

gcloud

您可以使用 gcloud 命令行工具在部署中创建 Game Servers 配置。

如需创建游戏服务器配置,请执行以下操作:

  1. 将此队列规范复制到一个文件中。

    - name: fleet-spec-1
      fleetSpec:
       replicas: 10
       scheduling: Packed
       strategy:
         type: RollingUpdate
         rollingUpdate:
           maxSurge: 25%
           maxUnavailable: 25%
       template:
         metadata:
           labels:
             gameName: udp-server
         spec:
           ports:
           - name: default
             portPolicy: Dynamic
             containerPort: 7654
             protocol: UDP
           health:
             initialDelaySeconds: 30
             periodSeconds: 60
           sdkServer:
             logLevel: Info
             grpcPort: 9357
             httpPort: 9358
           template:
             spec:
               containers:
               - name: dedicated
                 image: gcr.io/agones-images/udp-server:0.21
                 imagePullPolicy: Always
                 resources:
                   requests:
                     memory: 200Mi
                     cpu: 500m
                   limits:
                     memory: 200Mi
                     cpu: 500m
    
  2. 运行以下命令并将占位符值(例如 deploymentIDconfigID)替换为适当的值:

    gcloud game servers configs create configID --deployment deploymentID --fleet-configs-file fleetSpecFile
    

    变量占位符对应于以下说明:

  • configID 是您可以为此配置指定的唯一标识符。
  • deploymentID 是部署的唯一标识符。
  • fleetSpecFile 是具有 Agones 队列规范的文件的路径。

REST 和命令行

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

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

请求 JSON 正文:

{
  "fleetConfigs": [
    {
      "name": "fleet-spec-1",
      "fleetSpec": "{
        \"replicas\": 10,
        \"scheduling\": \"Packed\",
        \"template\": {
          \"metadata\": {
            \"labels\": {
              \"gameName\": \"udp-server\"
            }
          },
          \"spec\": {
            \"ports\": [
              {
                \"name\": \"default\",
                \"portPolicy\": \"Dynamic\",
                \"containerPort\": 7654,
                \"protocol\": \"UDP\"
              }
            ],
            \"health\": {
              \"periodSeconds\": 60,
              \"initialDelaySeconds\": 30
            },
            \"sdkServer\": {
              \"logLevel\": \"Info\",
              \"grpcPort\": 9357,
              \"httpPort\": 9358
            },
            \"template\": {
              \"spec\": {
                \"containers\": [
                  {
                    \"name\": \"dedicated\",
                    \"image\": \"gcr.io/agones-images/udp-server:0.21\",
                    \"imagePullPolicy\": \"Always\",
                    \"resources\": {
                      \"requests\": {
                        \"memory\": \"200Mi\",
                        \"cpu\": \"500m\"
                      },
                      \"limits\": {
                        \"memory\": \"200Mi\",
                        \"cpu\": \"500m\"
                      }
                    }
                  }
                ]
              }
            }
          }
        }
      }"
    }
  ]
}

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

您应该收到类似以下内容的 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/configs/CONFIG_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"
)

// fleet is the spec portion of an agones Fleet.  It must be in JSON format.
// See https://agones.dev/site/docs/reference/fleet/ for more on fleets.
const fleet = `
{
   "replicas": 10,
   "scheduling": "Packed",
   "strategy": {
      "type": "RollingUpdate",
      "rollingUpdate": {
         "maxSurge": "25%",
         "maxUnavailable": "25%"
      }
   },
   "template": {
      "metadata": {
         "labels": {
            "gameName": "udp-server"
         }
      },
      "spec": {
         "ports": [
            {
               "name": "default",
               "portPolicy": "Dynamic",
               "containerPort": 2156,
               "protocol": "TCP"
            }
         ],
         "health": {
            "initialDelaySeconds": 30,
            "periodSeconds": 60
         },
         "sdkServer": {
            "logLevel": "Info",
            "grpcPort": 9357,
            "httpPort": 9358
         },
         "template": {
            "spec": {
               "containers": [
                  {
                     "name": "dedicated",
                     "image": "gcr.io/agones-images/udp-server:0.17",
                     "imagePullPolicy": "Always",
                     "resources": {
                        "requests": {
                           "memory": "200Mi",
                           "cpu": "500m"
                        },
                        "limits": {
                           "memory": "200Mi",
                           "cpu": "500m"
                        }
                     }
                  }
               ]
            }
         }
      }
   }
}
`

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

	req := &gamingpb.CreateGameServerConfigRequest{
		Parent:   fmt.Sprintf("projects/%s/locations/global/gameServerDeployments/%s", projectID, deploymentID),
		ConfigId: configID,
		GameServerConfig: &gamingpb.GameServerConfig{
			FleetConfigs: []*gamingpb.FleetConfig{
				&gamingpb.FleetConfig{
					Name:      "fleet-spec-1",
					FleetSpec: fleet,
				},
			},
			Description: "My Game Server Config",
		},
	}

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

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

Node.js

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

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

  const client = new GameServerConfigsServiceClient();

  async function createGameServerConfig() {
    /**
     * 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 configId = 'A unique ID for the Game Server Config';
    // const fleetName = 'The fleet name to be stored in Agones';
    // fleet is the spec portion of an agones Fleet.  It must be in JSON format.
    // See https://agones.dev/site/docs/reference/fleet/ for more on fleets.
    const fleet = `
{
   "replicas": 10,
   "scheduling": "Packed",
   "strategy": {
      "type": "RollingUpdate",
      "rollingUpdate": {
         "maxSurge": "25%",
         "maxUnavailable": "25%"
      }
   },
   "template": {
      "metadata": {
         "labels": {
            "gameName": "udp-server"
         }
      },
      "spec": {
         "ports": [
            {
               "name": "default",
               "portPolicy": "Dynamic",
               "containerPort": 2156,
               "protocol": "TCP"
            }
         ],
         "health": {
            "initialDelaySeconds": 30,
            "periodSeconds": 60
         },
         "sdkServer": {
            "logLevel": "Info",
            "grpcPort": 9357,
            "httpPort": 9358
         },
         "template": {
            "spec": {
               "containers": [
                  {
                     "name": "dedicated",
                     "image": "gcr.io/agones-images/udp-server:0.17",
                     "imagePullPolicy": "Always",
                     "resources": {
                        "requests": {
                           "memory": "200Mi",
                           "cpu": "500m"
                        },
                        "limits": {
                           "memory": "200Mi",
                           "cpu": "500m"
                        }
                     }
                  }
               ]
            }
         }
      }
   }
}
`;
    const request = {
      parent: client.gameServerDeploymentPath(
        projectId,
        'global',
        deploymentId
      ),
      configId: configId,
      gameServerConfig: {
        fleetConfigs: [
          {
            name: fleetName,
            fleetSpec: fleet,
          },
        ],
        description: 'nodejs test config',
      },
    };

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

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

  createGameServerConfig();

Python

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


# FLEET_SPEC is the spec portion of an agones Fleet.  It must be in JSON format.
# See https://agones.dev/site/docs/reference/fleet/ for more on fleets.
FLEET_SPEC = """
{
   "replicas": 10,
   "scheduling": "Packed",
   "strategy": {
      "type": "RollingUpdate",
      "rollingUpdate": {
         "maxSurge": "25%",
         "maxUnavailable": "25%"
      }
   },
   "template": {
      "metadata": {
         "labels": {
            "gameName": "udp-server"
         }
      },
      "spec": {
         "ports": [
            {
               "name": "default",
               "portPolicy": "Dynamic",
               "containerPort": 2156,
               "protocol": "TCP"
            }
         ],
         "health": {
            "initialDelaySeconds": 30,
            "periodSeconds": 60
         },
         "sdkServer": {
            "logLevel": "Info",
            "grpcPort": 9357,
            "httpPort": 9358
         },
         "template": {
            "spec": {
               "containers": [
                  {
                     "name": "dedicated",
                     "image": "gcr.io/agones-images/udp-server:0.17",
                     "imagePullPolicy": "Always",
                     "resources": {
                        "requests": {
                           "memory": "200Mi",
                           "cpu": "500m"
                        },
                        "limits": {
                           "memory": "200Mi",
                           "cpu": "500m"
                        }
                     }
                  }
               ]
            }
         }
      }
   }
}
"""

def create_config(project_id, deployment_id, config_id):
    """Creates a game server config."""

    client = gaming.GameServerConfigsServiceClient()

    fleet_config = game_server_configs.FleetConfig(
        name="my-fleet-spec", fleet_spec=FLEET_SPEC,
    )

    # Location is hard coded as global, as game server configs can
    # only be created in global.  This is done for all operations on
    # game server configs.
    request = game_server_configs.CreateGameServerConfigRequest(
        parent=f"projects/{project_id}/locations/global/gameServerDeployments/{deployment_id}",
        config_id=config_id,
        game_server_config=game_server_configs.GameServerConfig(
            description="My Game Server Config", fleet_configs=[fleet_config],
        ),
    )

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

编辑配置

您无法编辑 Game Servers 配置,因为配置不可变。如果要编辑配置,请复制配置(查看配置详情),在本地修改配置,然后使用更新后的版本来创建新配置。

列出配置

控制台

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

    转到 Game Servers

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

gcloud

您可以使用 gcloud 命令行工具列出配置。

如需列出所有配置,请运行以下命令:

gcloud game servers configs list

如需列出部署中的所有配置,请运行以下命令并将 deploymentID 替换为要在其中列出配置的父级部署

gcloud game servers configs list --deployment=deploymentID

REST 和命令行

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

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

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

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

{
  "gameServerConfigs": [
    {
      "name": "projects/PROJECT_ID/locations/global/gameServerDeployments/DEPLOYMENT_ID/configs/MY-CONFIG-1",
      "createTime": CREATE_TIME,
      "updateTime": UPDATE_TIME,
      "fleetConfigs": [
        {
          "fleetSpec": ...
          "name": "MY-CONFIG-1"
        }
      ],
      "description": "Config 1"
    },
    {
      "name": "projects/PROJECT_ID/locations/global/gameServerDeployments/DEPLOYMENT_ID/configs/MY-CONFIG-2",
      "createTime": CREATE_TIME,
      "updateTime": UPDATE_TIME,
      "fleetConfigs": [
        {
          "fleetSpec": ...
          "name": "MY-CONFIG-2"
        }
      ],
      "description": "Config 2"
    },
  ]
}

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

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

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

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

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

	return nil
}

Node.js

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

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

const client = new GameServerConfigsServiceClient();

async function listGameServerConfigs() {
  /**
   * 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: client.gameServerDeploymentPath(
      projectId,
      'global',
      deploymentId
    ),
  };

  const [results] = await client.listGameServerConfigs(request);
  for (const config of results) {
    console.log(`Config name: ${config.name}`);
    console.log(`Config description: ${config.description}`);

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

listGameServerConfigs();

Python

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

def list_configs(project_id, deployment_id):
    """Lists the existing game server deployments."""

    client = gaming.GameServerConfigsServiceClient()

    # Location is hard coded as global, as game server configs can
    # only be created in global.  This is done for all operations on
    # game server configs.
    response = client.list_game_server_configs(
        parent=f"projects/{project_id}/locations/global/gameServerDeployments/{deployment_id}"
    )

    for config in response.game_server_configs:
        print(f"Name: {config.name}")

    return response.game_server_configs

查看有关配置的详细信息

控制台

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

    转到 Game Servers

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

  3. 在表格中查找配置。在表格的最后一列中,点击省略号 并选择查看配置

gcloud

您可以使用 gcloud 命令行工具查找有关配置的详细信息,例如创建时间:

如需查看配置的详细信息,请运行以下命令,并将占位符值(如 deploymentIDconfigID)替换为适当的值:

gcloud game servers configs describe configID --deployment deploymentID

输出会为您提供配置的详细信息。

变量占位符对应于以下说明:

  • configID 是您为游戏服务器配置指定的唯一标识符。
  • deploymentID 是父级部署的唯一标识符。

REST 和命令行

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

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

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

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

{
  "name": "projects/PROJECT_ID/locations/global/gameServerDeployments/DEPLOYMENT_ID/configs/CONFIG_ID",
  "createTime": CREATE_TIME,
  "updateTime": UPDATE_TIME,
  "fleetConfigs": [
    {
      "fleetSpec": ...
      "name": "CONFIG_ID"
    }
  ],
  "description": "My config"
}

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

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

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

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

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

Node.js

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

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

const client = new GameServerConfigsServiceClient();

async function getGameServerConfig() {
  /**
   * 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 configId = 'A unique ID for the Game Server Config';
  const request = {
    // The full resource name
    name: client.gameServerConfigPath(
      projectId,
      'global',
      deploymentId,
      configId
    ),
  };

  const [config] = await client.getGameServerConfig(request);
  console.log(`Config name: ${config.name}`);
  console.log(`Config description: ${config.description}`);

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

getGameServerConfig();

Python

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

def get_config(project_id, deployment_id, config_id):
    """Gets a game server config."""

    client = gaming.GameServerConfigsServiceClient()

    # Location is hard coded as global, as game server configs can
    # only be created in global.  This is done for all operations on
    # game server configs.
    request = game_server_configs.GetGameServerConfigRequest(
        name=f"projects/{project_id}/locations/global/gameServerDeployments/{deployment_id}/configs/{config_id}",
    )

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

后续步骤