如何获取 Java 应用程序 运行 所在的 GAE 项目的 ID?

How to get the ID of the GAE project that a Java app is running in?

我在 Google App Engine 中有一个 Java 应用 运行。我需要以编程方式在 Java.

中获取项目的 ID,它是 运行 的一部分

This question 解释了如何在 Python 中实现我的目标,但这当然不是 Java。

This documentation 说我可以简单地调用 ApiProxy.getCurrentEnvironment().getAppId(),但是这个方法在我的应用程序中只是 returns null。

解释了如何通过 HTTP 请求获取项目 ID,但我想知道在 Java 中是否有更好的方法来执行此操作而无需手动构建 HTTP 请求?

编辑:Luyi 的回答似乎对大多数人都有效,但对我来说 returns 无效。

也许您正在寻找这个:

import com.google.appengine.api.utils.SystemProperty;
    
String appId = SystemProperty.applicationId.get();

您还可以从 SystemProperty 获取其他信息,例如环境和应用程序版本。

您可以使用 com.google.cloud.ServiceOptions 帮助程序获取默认项目 ID。 它将为您提供一些抽象,以便能够根据您的上下文和当前的应用程序引擎运行时检索 project-id

例如Java11运行时不支持一些旧的api。通过 HTTP 请求元数据获取 project-id 是一种通用的解决方案。

在这种情况下,ServiceOptions.getDefaultProjectId 是让您的代码通用且简单的好方法。

Spring Cloud GCP 正在后台使用此方法检索 project-id

导入google-cloud-core依赖:

<dependency>
  <groupId>com.google.cloud</groupId>
  <artifactId>google-cloud-core</artifactId>
  <version>1.94.0</version>
</dependency>

然后使用ServiceOptions:

import com.google.cloud.ServiceOptions;
...

String projectId = ServiceOptions.getDefaultProjectId();