概要
- ローカルで利用できるCloud Spannerのインメモリのエミュレータ。
- エミュレータを再起動するとスキーマ定義含めてすべての状態がリセットされる。
- GCPのプロジェクト不要で、無料でSpannerを利用した開発を進めることができる。
- Spannerの本番サービスと同じAPIを提供してくれる(制限事項あり)。
- ローカルでの開発とテスト向け。
インストールと起動
gcloud CLIで直接ローカルマシンにインストール・起動する方法と、Dockerイメージからエミュレータのコンテナを起動する方法の2種類がある。
例として、Dockerコンテナとして起動する手順を示す。
# Dockerイメージをpull
docker pull gcr.io/cloud-spanner-emulator/emulator
# Dockerコンテナを起動
docker run -p 9010:9010 -p 9020:9020 gcr.io/cloud-spanner-emulator/emulator
エミュレータには、gRPCリクエスト用のポート9010, RESTリクエスト用のポート9020が用意されているとのこと。
実際に起動すると、以下のようにログが流れ、エミュレータ自身がコンテナでそれぞれの通信を受けるために、9010, 9020のポートをリスンしていることが伺える。
2024/07/22 12:24:38 gateway.go:144: Cloud Spanner emulator running.
2024/07/22 12:24:38 gateway.go:145: REST server listening at 0.0.0.0:9020
2024/07/22 12:24:38 gateway.go:146: gRPC server listening at 0.0.0.0:9010
インスタンスとデータベースの作成
例として、gcloud CLIでSpannerエミュレータ上に以下のデータベースを作成する手順を示す。
- プロジェクトID:
local-project
- インスタンスID:
test-instance
- データベースID:
test-db
# 1. Spannerエミュレータ向けの configuration の設定
## 1.1. 任意の名前(ここではspanner-emulator)のconfigurationを作成して有効化する
gcloud config configurations create spanner-emulator
## 1.2. 現在有効化しているconfigurationに対する設定
### 認証処理をしなくする
gcloud config set auth/disable_credentials true
### GCPプロジェクトIDの設定
gcloud config set project local-project
### gcloud spannerコマンドグループ実行時のエンドポイントを上書きする
gcloud config set api_endpoint_overrides/spanner http://localhost:9020/
# 2. Spannerエミュレータ上にインスタンスを作成
gcloud spanner instances create test-instance --config=emulator-config --description="Test Instance" --nodes=1
# 確認
gcloud spanner instances list
# 3. Spanner エミュレータのインスタンス上にデータベースを作成
gcloud spanner databases create test-db --instance=test-instance
# 確認
gcloud spanner databases list --instance=test-instance
環境変数
GCP公式の各言語のクライアントライブラリ(例. Goだとgoogleapis/google-cloud-go)を使用すると、アプリケーション内で環境変数 SPANNER_EMULATOR_HOST
をチェックして、そのエミュレータが実行されている場合は自動で接続してくれる。
Goの場合、ORMGORM でも、同様の仕組みがあることを確認している。
参考