Spanner安装与配置 #
一、准备工作 #
1.1 GCP账号要求 #
text
账号准备
├── Google Cloud账号
├── 启用计费
├── 创建项目
└── 启用Spanner API
1.2 权限配置 #
| 角色 | 权限说明 |
|---|---|
| roles/spanner.admin | 完全管理权限 |
| roles/spanner.databaseAdmin | 数据库管理权限 |
| roles/spanner.databaseUser | 数据库读写权限 |
| roles/spanner.viewer | 只读权限 |
1.3 配额限制 #
text
默认配额
├── 实例数: 5个/项目
├── 节点数: 100个/项目
├── 数据库数: 100个/实例
└── 可申请提高配额
二、GCP控制台配置 #
2.1 创建项目 #
text
步骤
1. 访问 console.cloud.google.com
2. 点击"选择项目" → "新建项目"
3. 输入项目名称
4. 选择组织(可选)
5. 点击"创建"
2.2 启用API #
text
步骤
1. 导航到"API和服务" → "库"
2. 搜索"Cloud Spanner API"
3. 点击"启用"
4. 等待API启用完成
2.3 创建实例 #
text
步骤
1. 导航到"Spanner"
2. 点击"创建实例"
3. 选择配置类型:
- 区域配置: 单区域部署
- 多区域配置: 跨区域部署
4. 配置实例信息:
- 实例名称
- 实例ID
- 节点数量
5. 点击"创建"
2.4 创建数据库 #
text
步骤
1. 选择实例
2. 点击"创建数据库"
3. 输入数据库名称
4. 选择数据库方言:
- Google标准SQL
- PostgreSQL
5. 点击"创建"
三、gcloud CLI配置 #
3.1 安装gcloud CLI #
bash
# macOS
brew install google-cloud-sdk
# Linux
curl https://sdk.cloud.google.com | bash
# Windows
# 下载安装包: https://cloud.google.com/sdk/docs/install
3.2 初始化配置 #
bash
# 初始化gcloud
gcloud init
# 登录账号
gcloud auth login
# 设置默认项目
gcloud config set project my-project-id
# 查看当前配置
gcloud config list
3.3 启用Spanner API #
bash
# 启用API
gcloud services enable spanner.googleapis.com
# 查看API状态
gcloud services list --filter="spanner"
3.4 创建实例 #
bash
# 创建区域实例
gcloud spanner instances create my-instance \
--config=regional-us-central1 \
--description="My Spanner Instance" \
--nodes=1
# 创建多区域实例
gcloud spanner instances create my-global-instance \
--config=nam-eur-asia1 \
--description="Global Instance" \
--nodes=3
3.5 创建数据库 #
bash
# 创建数据库(Google标准SQL)
gcloud spanner databases create my-database \
--instance=my-instance
# 创建数据库(PostgreSQL)
gcloud spanner databases create my-pg-database \
--instance=my-instance \
--database-dialect=POSTGRESQL
3.6 常用命令 #
bash
# 列出实例
gcloud spanner instances list
# 列出数据库
gcloud spanner databases list --instance=my-instance
# 执行SQL
gcloud spanner databases execute-sql my-database \
--instance=my-instance \
--sql="SELECT * FROM users LIMIT 10"
# 创建表
gcloud spanner databases ddl update my-database \
--instance=my-instance \
--ddl="CREATE TABLE users (user_id INT64 NOT NULL, name STRING(100)) PRIMARY KEY (user_id)"
四、客户端库配置 #
4.1 Java客户端 #
xml
<!-- Maven依赖 -->
<dependency>
<groupId>com.google.cloud</groupId>
<artifactId>google-cloud-spanner</artifactId>
<version>6.45.0</version>
</dependency>
java
import com.google.cloud.spanner.SpannerOptions;
import com.google.cloud.spanner.Spanner;
import com.google.cloud.spanner.DatabaseId;
import com.google.cloud.spanner.DatabaseClient;
public class SpannerConfig {
public static DatabaseClient createClient(
String projectId,
String instanceId,
String databaseId) {
SpannerOptions options = SpannerOptions.newBuilder().build();
Spanner spanner = options.getService();
DatabaseId dbId = DatabaseId.of(projectId, instanceId, databaseId);
return spanner.getDatabaseClient(dbId);
}
}
4.2 Python客户端 #
bash
# 安装客户端库
pip install google-cloud-spanner
python
from google.cloud import spanner
def create_client(project_id, instance_id, database_id):
spanner_client = spanner.Client(project=project_id)
instance = spanner_client.instance(instance_id)
database = instance.database(database_id)
return database
4.3 Go客户端 #
bash
# 安装客户端库
go get cloud.google.com/go/spanner
go
package main
import (
"context"
"cloud.google.com/go/spanner"
)
func createClient(ctx context.Context, dbPath string) (*spanner.Client, error) {
client, err := spanner.NewClient(ctx, dbPath)
if err != nil {
return nil, err
}
return client, nil
}
// dbPath格式: projects/{project}/instances/{instance}/databases/{database}
4.4 Node.js客户端 #
bash
# 安装客户端库
npm install @google-cloud/spanner
javascript
const { Spanner } = require('@google-cloud/spanner');
async function createClient(projectId, instanceId, databaseId) {
const spanner = new Spanner({
projectId: projectId,
});
const instance = spanner.instance(instanceId);
const database = instance.database(databaseId);
return database;
}
五、服务账号配置 #
5.1 创建服务账号 #
bash
# 创建服务账号
gcloud iam service-accounts create spanner-sa \
--display-name="Spanner Service Account"
# 添加权限
gcloud projects add-iam-policy-binding my-project-id \
--member="serviceAccount:spanner-sa@my-project-id.iam.gserviceaccount.com" \
--role="roles/spanner.databaseUser"
5.2 创建密钥 #
bash
# 创建JSON密钥
gcloud iam service-accounts keys create spanner-key.json \
--iam-account=spanner-sa@my-project-id.iam.gserviceaccount.com
5.3 使用密钥认证 #
bash
# 设置环境变量
export GOOGLE_APPLICATION_CREDENTIALS="/path/to/spanner-key.json"
# 或在代码中指定
python
import os
from google.cloud import spanner
os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = '/path/to/spanner-key.json'
client = spanner.Client()
六、连接池配置 #
6.1 Java连接池 #
java
import com.google.cloud.spanner.SpannerOptions;
import com.google.cloud.spanner.Spanner;
import com.google.cloud.spanner.SessionPoolOptions;
SpannerOptions options = SpannerOptions.newBuilder()
.setSessionPoolOption(
SessionPoolOptions.newBuilder()
.setMinSessions(10)
.setMaxSessions(100)
.setIncStep(5)
.build()
)
.build();
6.2 Python连接池 #
python
from google.cloud import spanner
client = spanner.Client(
project=project_id,
client_options={
'session_pool_options': {
'min_sessions': 10,
'max_sessions': 100,
}
}
)
6.3 Go连接池 #
go
import "cloud.google.com/go/spanner"
config := spanner.ClientConfig{
SessionPoolConfig: spanner.SessionPoolConfig{
MinOpened: 10,
MaxOpened: 100,
},
}
client, err := spanner.NewClientWithConfig(ctx, dbPath, config)
七、模拟器配置 #
7.1 安装模拟器 #
bash
# 使用gcloud安装
gcloud components install cloud-spanner-emulator
# 或使用Docker
docker pull gcr.io/cloud-spanner-emulator/emulator
7.2 启动模拟器 #
bash
# 启动模拟器
gcloud emulators spanner start
# Docker方式
docker run -p 9010:9010 -p 9020:9020 \
gcr.io/cloud-spanner-emulator/emulator
7.3 配置环境变量 #
bash
# 设置模拟器环境变量
export SPANNER_EMULATOR_HOST=localhost:9010
# 或在代码中设置
java
// Java
System.setProperty("SPANNER_EMULATOR_HOST", "localhost:9010");
python
# Python
import os
os.environ['SPANNER_EMULATOR_HOST'] = 'localhost:9010'
7.4 模拟器限制 #
text
限制
├── 不支持多区域配置
├── 不支持TrueTime
├── 性能与生产环境不同
├── 部分功能未实现
└── 仅供开发测试使用
八、网络配置 #
8.1 VPC配置 #
text
私有服务连接
├── 创建私有连接
├── 分配IP范围
└── 配置防火墙规则
8.2 私有IP访问 #
bash
# 创建实例时指定私有网络
gcloud spanner instances create my-instance \
--config=regional-us-central1 \
--network=projects/my-project/global/networks/my-vpc
九、监控配置 #
9.1 启用监控 #
bash
# 启用Cloud Monitoring API
gcloud services enable monitoring.googleapis.com
# 创建告警策略
gcloud alpha monitoring policies create \
--notification-channels=projects/my-project/notificationChannels/channel-id \
--display-name="Spanner CPU Alert" \
--condition-display-name="CPU > 80%" \
--condition-filter='resource.type="spanner_instance" AND metric.type="spanner.googleapis.com/instance/cpu/utilization"' \
--condition-threshold-value=0.8
9.2 关键指标 #
| 指标 | 说明 | 告警阈值 |
|---|---|---|
| CPU利用率 | 节点CPU使用率 | > 80% |
| 存储使用 | 存储空间使用量 | > 90% |
| 会话数 | 活跃会话数量 | > 80% |
| 延迟 | 请求延迟时间 | P99 > 100ms |
十、最佳实践 #
10.1 开发环境配置 #
text
推荐配置
├── 使用模拟器进行本地开发
├── 使用服务账号认证
├── 配置合理的连接池
└── 启用日志记录
10.2 生产环境配置 #
text
推荐配置
├── 使用私有IP访问
├── 配置IAM权限
├── 启用监控告警
├── 配置自动备份
└── 规划节点数量
10.3 安全建议 #
text
安全配置
├── 使用服务账号而非个人账号
├── 遵循最小权限原则
├── 定期轮换密钥
├── 启用审计日志
└── 使用私有网络
十一、总结 #
配置要点:
| 配置项 | 说明 |
|---|---|
| GCP项目 | 创建项目并启用API |
| 实例配置 | 选择区域和节点数 |
| 认证方式 | 服务账号+密钥 |
| 客户端库 | 选择合适的SDK |
| 连接池 | 合理配置会话池 |
| 监控 | 配置关键指标告警 |
下一步,让我们学习Spanner的架构设计!
最后更新:2026-03-27