大多數 Google Cloud 程式庫都需要專案 ID。指定這個專案 ID 的方式有很多種。
從 Compute Engine 或 App Engine 內使用 Google Cloud 程式庫時,系統通常會自動推斷專案 ID。
在其他環境中,請使用下列其中一種方法:
* 建構服務專屬設定物件時,提供專案 ID。
舉例來說,如要從 ID 為 PROJECT_ID 的專案使用 Datastore 模式的 Firestore (Datastore),請編寫下列程式碼:
Datastore datastore = DatastoreOptions.newBuilder().setProjectId("PROJECT_ID").build().getService();
將專案 ID 指定為
GOOGLE_CLOUD_PROJECT環境變數。例如:
none export GOOGLE_CLOUD_PROJECT=PROJECT_ID使用 Google Cloud SDK 設定專案 ID。如要使用 SDK,請下載 SDK,然後從指令列設定專案 ID。
例如:
none gcloud config set project PROJECT_ID
Google Cloud 會依下列來源的列出順序判斷專案 ID,並在找到值後停止:
- 建構服務選項時提供的專案 ID。
- 環境變數
GOOGLE_CLOUD_PROJECT指定的專案 ID。 - App Engine 或 Compute Engine 專案 ID。
GOOGLE_APPLICATION_CREDENTIALS環境變數所指向的 JSON 憑證檔案中指定的專案 ID。- Google Cloud SDK 專案 ID。
如要透過程式存取用戶端程式庫將根據環境使用的專案 ID,可以使用下列輔助方法:
import com.google.cloud.ServiceOptions;
// Additional imports or code here
String projectId = ServiceOptions.getDefaultProjectId();