创建配置

本页面介绍了如何在部署中注册、列出和查看 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
    

    客户端库

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

创建配置

确保您已创建 Game Servers 部署

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 队列规范的文件的路径。

Go


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

  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


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

列出配置

gcloud 命令

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

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

gcloud game servers configs list

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

gcloud game servers configs list --deployment=deploymentID

Go


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

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

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

查看有关配置的详细信息

gcloud 命令

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

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

gcloud game servers configs describe configID --deployment deploymentID

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

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

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

Go


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

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

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

后续步骤