首页 > 解决方案 > 使用 GCP 的数据存储区时如何区分代码是在模拟器中运行还是在 GKE 中运行

问题描述

在遵循https://cloud.google.com/datastore/docs/tools/datastore-emulator中给出的说明后,我不确定我是否遗漏了任何内容

除非我使用 DataStoreClient 显式创建 Datastore,否则我无法连接到本地模拟器。

DatastoreDb db = DatastoreDb.Create(projectId, string.Empty, new DatastoreClientImpl(
                new Datastore.DatastoreClient(
                    new Channel("localhost", 8081, ChannelCredentials.Insecure)), new DatastoreSettings()));

而不仅仅是DatastoreDb.Create(projectId);

如果我们在 GKE 中工作,我们需要连接到实际的 Datastore 而不是模拟器,我们如何区分具有相同代码库的两个版本。

有没有办法检查代码是否正在运行 GKE,或者这是否应该通过环境变量来完成以获得最佳结果。

标签: c#google-cloud-platformgoogle-cloud-datastoregoogle-kubernetes-engine

解决方案


您可以使用命名空间中的PlatformGoogle.Api.Gax(在Google.Api.Gax包中):

Platform platform = Platform.Instance();
switch (platform.Type)
{
    case PlatformType.Gae:
        // Code for AppEngine
        break;
    case PlatformType.Gce:
        // Code for Compute Engine
        break;        
    case PlatformType.Gke:
        // Code for Google Kubernetes Engine
        break;
    default:
        // Code for other contexts
        break;
}

推荐阅读