使用位置端點設定資料區域

本頁說明如何設定 Firestore 用戶端程式庫,以使用區域端點。

使用 Firestore 用戶端程式庫時,可以採用下列任一端點:

  • 全域端點:根據預設,Firestore 用戶端程式庫會將 API 要求傳送至名為 firestore.googleapis.com 的全域服務端點。全域服務端點會將要求轉送至資料庫。在路由期間,要求可能會通過與資料庫位置不同的位置中的位置服務端點。

  • 位置端點:位置端點會強制執行地區限制,確保資料儲存及處理作業在指定地區進行。 如要確保服務端點會在與資料庫相同的區域中處理應用程式的 Firestore 請求,請在用戶端程式庫中指定位置端點

設定位置端點

以下範例說明如何初始化 Firestore 用戶端時設定位置端點。如果設定的位置端點與資料所在位置不同,可能會導致 PermissionDeniedError 錯誤。

Java

如要向 Firestore 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。


import com.google.auth.oauth2.GoogleCredentials;
import com.google.cloud.firestore.Firestore;
import com.google.cloud.firestore.FirestoreOptions;


/**
 * Demonstrate how to set a regional endpoint.
 */
public class RegionalEndpointSnippets {

  /**
   * Create a client with a regional endpoint.
   **/
  public Firestore regionalEndpoint(String projectId, String endpoint) throws Exception {
    FirestoreOptions firestoreOptions =
        FirestoreOptions.newBuilder()
            .setProjectId(projectId)
            .setCredentials(GoogleCredentials.getApplicationDefault())
            // set endpoint like nam5-firestore.googleapis.com:443
            .setHost(endpoint)
            .build();
    Firestore dbWithEndpoint = firestoreOptions.getService();

    return dbWithEndpoint;
  }

}

Python

如要向 Firestore 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

ENDPOINT = "nam5-firestore.googleapis.com"
client_options = ClientOptions(api_endpoint=ENDPOINT)
db = firestore.Client(client_options=client_options)

cities_query = db.collection("cities").limit(2).get()
for r in cities_query:
    print(r)

位置端點語意

Firestore 支援區域和多區域位置的端點。

請使用下列格式定義地點端點:

Java

  REGION_NAME-firestore.googleapis.com:443

請確認通訊埠號碼已與端點一併定義。

Python

  REGION_NAME-firestore.googleapis.com

Go

  REGION_NAME-firestore.googleapis.com:443

請確認通訊埠號碼已與端點一併定義。

REGION_NAME 替換為區域或多區域主機名稱。

主機名稱範例:

  • eur3-firestore.googleapis.com
  • nam5-firestore.googleapis.com
  • europe-west6-firestore.googleapis.com
  • asia-northeast2-firestore.googleapis.com

如需多地區和地區主機名稱的完整清單,請參閱「Firestore 位置」。

限制全球 API 端點用量

如要強制使用區域端點,請使用constraints/gcp.restrictEndpointUsage機構政策限制,封鎖對全域 API 端點的要求。詳情請參閱「限制端點用量」。

後續步驟