Mettre à jour le domaine

Mettez à jour les détails du domaine de Game Servers.

Pages de documentation incluant cet exemple de code

Pour afficher l'exemple de code utilisé en contexte, consultez la documentation suivante :

Exemple de code

C#

Pour apprendre à installer et à utiliser la bibliothèque cliente pour Game Servers, consultez la page Bibliothèques clientes de Game Servers.


using Google.Cloud.Gaming.V1;
using Google.LongRunning;
using Google.Protobuf.WellKnownTypes;
using System.Threading.Tasks;

public class UpdateRealmSample
{
    public async Task<Realm> UpdateRealmAsync(
        string projectId, string regionId, string realmId)
    {
        // Create the client.
        RealmsServiceClient client = await RealmsServiceClient.CreateAsync();

        Realm realm = new Realm
        {
            RealmName = RealmName.FromProjectLocationRealm(projectId, regionId, realmId),
        };
        realm.Labels.Add("label-key-1", "label-value-1");
        realm.Labels.Add("label-key-2", "label-value-2");

        UpdateRealmRequest request = new UpdateRealmRequest
        {
            Realm = realm,
            UpdateMask = new FieldMask { Paths = { "labels" } }
        };

        // Make the request.
        Operation<Realm, OperationMetadata> response = await client.UpdateRealmAsync(request);
        Operation<Realm, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync();

        // Retrieve the operation result. This result will NOT contain the updated labels.
        // If you want to get the updated resource, use a GET request on the resource.
        return completedResponse.Result;
    }
}

Go

Pour apprendre à installer et à utiliser la bibliothèque cliente pour Game Servers, consultez la page Bibliothèques clientes de Game Servers.


import (
	"context"
	"fmt"
	"io"

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

// updateRealm updates a realm.
func updateRealm(w io.Writer, projectID, location, realmID string) error {
	// projectID := "my-project"
	// location := "global"
	// realmID := "myrealm"
	ctx := context.Background()
	client, err := gaming.NewRealmsClient(ctx)
	if err != nil {
		return fmt.Errorf("NewRealmsClient: %v", err)
	}
	defer client.Close()

	req := &gamingpb.UpdateRealmRequest{
		Realm: &gamingpb.Realm{
			Name:        fmt.Sprintf("projects/%s/locations/%s/realms/%s", projectID, location, realmID),
			Description: "My Updated Game Server Realm",
			Labels: map[string]string{
				"label-key-1": "label-value-1",
			},
		},
		UpdateMask: &fieldmaskpb.FieldMask{
			Paths: []string{
				"description", "labels",
			},
		},
	}

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

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

Java

Pour apprendre à installer et à utiliser la bibliothèque cliente pour Game Servers, consultez la page Bibliothèques clientes de Game Servers.


import com.google.api.gax.longrunning.OperationFuture;
import com.google.cloud.gaming.v1.OperationMetadata;
import com.google.cloud.gaming.v1.Realm;
import com.google.cloud.gaming.v1.RealmsServiceClient;
import com.google.protobuf.FieldMask;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class UpdateRealm {
  public static void updateRealm(String projectId, String regionId, String realmId)
      throws IOException, InterruptedException, ExecutionException, TimeoutException {
    // String projectId = "your-project-id";
    // String regionId = "us-central1-f";
    // String realmId = "your-realm-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 (RealmsServiceClient client = RealmsServiceClient.create()) {
      String parent = String.format("projects/%s/locations/%s", projectId, regionId);
      String realmName = String.format("%s/realms/%s", parent, realmId);

      Realm realm = Realm.newBuilder().setName(realmName).setTimeZone("America/New_York").build();

      FieldMask fieldMask = FieldMask.newBuilder().addPaths("time_zone").build();

      OperationFuture<Realm, OperationMetadata> call = client.updateRealmAsync(realm, fieldMask);

      Realm updated = call.get(1, TimeUnit.MINUTES);
      System.out.println("Realm updated: " + updated.getName());
    }
  }
}

Node.js

Pour apprendre à installer et à utiliser la bibliothèque cliente pour Game Servers, consultez la page Bibliothèques clientes de Game Servers.

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

const client = new RealmsServiceClient();

async function updateRealm() {
  /**
   * 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 unique identifier for the realm';
  const request = {
    realm: {
      name: client.realmPath(projectId, location, realmId),
      labels: {
        'label-key-1': 'label-value-1',
      },
      timeZone: 'US/Pacific',
      description: 'My updated Game Server realm',
    },
    updateMask: {
      paths: ['labels', 'time_zone', 'description'],
    },
  };

  const [operation] = await client.updateRealm(request);
  const results = await operation.promise();
  const [realm] = results;

  console.log(`Realm updated: ${realm.name}`);
}

updateRealm();

Python

Pour apprendre à installer et à utiliser la bibliothèque cliente pour Game Servers, consultez la page Bibliothèques clientes de Game Servers.

def update_realm(project_id, location, realm_id):
    """Updates a realm."""

    client = gaming.RealmsServiceClient()

    request = realms.UpdateRealmRequest(
        realm=realms.Realm(
            name=f"projects/{project_id}/locations/{location}/realms/{realm_id}",
            labels={"label-key-1": "label-value-1", "label-key-2": "label-value-2"},
        ),
        update_mask=field_mask.FieldMask(paths=["labels"]),
    )

    operation = client.update_realm(request)
    print(f"Update realm operation: {operation.operation.name}")
    operation.result(timeout=120)

Étape suivante

Pour rechercher et filtrer des exemples de code pour d'autres produits Google Cloud, consultez l'explorateur d'exemples Google Cloud.