ゴール
- Cloud Spanerをローカル環境で立ち上て操作する
前提
- MacOS
- Docker Desctopをインストール済み
- gcloud ツールをインストール済み
準備
gcloudツールの設定にCloud Spannerエミュレータ用の設定を追加する.
gcloud config configurations create emulator
gcloud config set project test-project
gcloud config set auth/disable_credentials true
gcloud config set api_endpoint_overrides/spanner http://localhost:9020/
Cloud Spanner エミュレータサーバーの初期化
エミュレータサーバーの起動
gcloudツールからエミュレータを立ち上げる(別タブでの実行を推奨)
※ DockerDesctopの起動が必要です.
gcloud emulators spanner start
以下の表示がされれば起動に成功しています.
[cloud-spanner-emulator] 2022/09/18 15:26:06 gateway.go:140: Cloud Spanner emulator running.
[cloud-spanner-emulator] 2022/09/18 15:26:06 gateway.go:141: REST server listening at 0.0.0.0:9020
[cloud-spanner-emulator] 2022/09/18 15:26:06 gateway.go:142: gRPC server listening at 0.0.0.0:9010
この時点でサーバーは起動しているもののインスタンスとデータベースはまだ作成されていません.
インスタンスの作成
以下のコマンドでインスタンスを作成します.
(例では test-instance という名前で作られます)
gcloud spanner instances create test-instance \
--config=emulator-config --description="Test Instance" --nodes=1
データベースの作成
gcloudツールを使う場合は以下のようなコマンドを入力します.
作成時にDDLを適用するなどの詳細な使い方は公式のデータベースの作成に紹介されています.
gcloud spanner databases create your-database-name --instance=test-instance
エミュレータサーバーへの手動アクセス
spanner-cliを利用する
mysqlなどの一般的なcliライクで接続したい場合はspanner-cliを使うことを検討するかもしれません.
初期化プロセスで設定したインスタンス名とデータベース名を読み替えて以下のコマンドでアクセスできます.
spanner-cli -p test-project -i test-instance -d test-database
IntelliJ IDEAと統合する
データベースを開く

設定の追加をクリック

データソース → その他 → Google Cloud Spanner を選択

↓の赤字を修正. URLの末尾に ?autoConfigEmulator=true
を追記して,接続のテストがパスすることを確認する.
※ プロジェクト〜データベース名は自分の環境に合わせて修正すること.

アプリケーションとエミュレータサーバーの接続
GCPのCloud Spannerライブラリにはアプリ起動時にエミュレータ用の環境変数を読み込む処理があります.
その環境変数が設定されている場合,通常のエンドポイントではなく環境変数先のエンドポイントに接続が切り替わります.
以下の環境変数が設定された環境でアプリを起動するとエミュレータサーバーに接続されます.
export SPANNER_EMULATOR_HOST=localhost:9010
以上となります.
お読みいただきありがとうございました.