구성 만들기

컬렉션을 사용해 정리하기 내 환경설정을 기준으로 콘텐츠를 저장하고 분류하세요.

Game Servers 구성을 만듭니다.

더 살펴보기

이 코드 샘플이 포함된 자세한 문서는 다음을 참조하세요.

코드 샘플

C#

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


using Google.Cloud.Gaming.V1;
using Google.LongRunning;
using Newtonsoft.Json;
using System.Threading.Tasks;

public class CreateConfigSample
{
    public async Task<GameServerConfig> CreateConfigAsync(
        string projectId, string regionId, string deploymentId, string configId)
    {
        // Create the client.
        GameServerConfigsServiceClient client = await GameServerConfigsServiceClient.CreateAsync();

        GameServerConfig config = new GameServerConfig
        {
            GameServerConfigName = GameServerConfigName.FromProjectLocationDeploymentConfig(projectId, regionId, deploymentId, configId),
            Description = "My Game Server Config",
            FleetConfigs =
            {
                new FleetConfig
                {

                    Name = "fleet-spec-1",
                    FleetSpec = JsonConvert.SerializeObject(new
                    {
                        replicas = 10,
                        scheduling = "Packed",
                        strategy = new
                        {
                            type = "RollingUpdate",
                            rollingUpdate = new
                            {
                                maxSurge = "25%",
                                maxUnavailable = "25%",
                            }
                        },
                        template = new
                        {
                            metadata = new
                            {
                                labels = new
                                {
                                    gameName = "udp-server",
                                }
                            },
                            spec = new
                            {
                                ports = new [] {
                                    new {
                                        name = "default",
                                        portPolicy = "Dynamic",
                                        containerPort = 7654,
                                        protocol = "UDP",
                                    }
                                },
                                health = new
                                {
                                    initialDelaySeconds = 30,
                                    periodSeconds = 60,
                                },
                                sdkServer = new
                                {
                                    logLevel = "Info",
                                    grpcPort = 9357,
                                    httpPort = 9358,
                                },
                                template = new
                                {
                                    spec = new
                                    {
                                        containers = new [] {
                                            new {
                                                name = "dedicated",
                                                image = "gcr.io/agones-images/udp-server:0.21",
                                                imagePullPolicy = "Always",
                                                resources = new
                                                {
                                                    requests = new
                                                    {
                                                        memory = "200Mi",
                                                        cpu = "500m",
                                                    },
                                                    limits = new
                                                    {
                                                        memory = "200Mi",
                                                        cpu = "500m",
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    })
                }
            }
        };

        CreateGameServerConfigRequest request = new CreateGameServerConfigRequest
        {
            ParentAsGameServerDeploymentName = GameServerDeploymentName.FromProjectLocationDeployment(projectId, regionId, deploymentId),
            ConfigId = configId,
            GameServerConfig = config
        };

        // Make the request.
        Operation<GameServerConfig, OperationMetadata> response = await client.CreateGameServerConfigAsync(request);

        // Poll until the returned long-running operation is complete.
        Operation<GameServerConfig, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync();

        // Retrieve the operation result.
        return completedResponse.Result;
    }
}

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

다음 단계

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