Spanner Omni 和 Spanner 以类似方式使用 Go 客户端库。本文档介绍了如何通过配置 Go 客户端库来建立与 Spanner Omni 的安全连接。您可以在创建数据库管理客户端或数据库客户端时配置 spanner.ClientConfig 来建立这些连接。
Go 客户端库支持纯文本、TLS、带凭据的 TLS 和 mTLS 连接。
如需了解详情,请参阅 Spanner 文档中的 Spanner 使用入门 (Go)。
准备工作
如需将 Go 客户端库与 Spanner Omni 搭配使用,请使用 v1.94.0 版或更高版本的 Go 客户端库以及 Go 发布版本 1.25 或更高版本。
如需将 Spanner Go 模块添加到 go.mod 文件,请运行以下命令:
go get cloud.google.com/go/spanner@v1.94.0
配置 ClientConfig 对象
如需使用 Go 客户端库创建 Client 或 DatabaseAdminClient,请通过指定 Type: spanner.OMNI 来配置 ClientConfig 对象,并使用 option.WithEndpoint() 提供端点。
以下示例展示了如何为每种受支持的安全配置配置 ClientConfig 对象:
纯文本
如需建立纯文本连接,请在 spanner.ClientConfig 中将 UsePlainText 设置为 true:
clientConfig := spanner.ClientConfig{
Type: spanner.OMNI,
UsePlainText: true,
}
adminClient, err := database.NewDatabaseAdminClientWithConfig(ctx, clientConfig,
option.WithEndpoint("ENDPOINT"),
)
if err != nil {
// Handle error.
}
defer adminClient.Close()
databaseClient, err := spanner.NewClientWithConfig(ctx, "DATABASE_NAME", clientConfig,
option.WithEndpoint("ENDPOINT"),
)
if err != nil {
// Handle error.
}
defer databaseClient.Close()
TLS
如需建立 TLS 连接,请使用 CaCertificateFile 指定 CA 证书的路径:
clientConfig := spanner.ClientConfig{
Type: spanner.OMNI,
CaCertificateFile: "PATH_TO_CA_CERT",
}
adminClient, err := database.NewDatabaseAdminClientWithConfig(ctx, clientConfig,
option.WithEndpoint("ENDPOINT"),
)
if err != nil {
// Handle error.
}
defer adminClient.Close()
databaseClient, err := spanner.NewClientWithConfig(ctx, "DATABASE_NAME", clientConfig,
option.WithEndpoint("ENDPOINT"),
)
if err != nil {
// Handle error.
}
defer databaseClient.Close()
使用凭据的 TLS
如需建立使用用户名和密码进行身份验证的 TLS 连接,请指定 CaCertificateFile、Username 和 Password:
clientConfig := spanner.ClientConfig{
Type: spanner.OMNI,
CaCertificateFile: "PATH_TO_CA_CERT",
Username: "USERNAME",
Password: []byte("PASSWORD"),
}
adminClient, err := database.NewDatabaseAdminClientWithConfig(ctx, clientConfig,
option.WithEndpoint("ENDPOINT"),
)
if err != nil {
// Handle error.
}
defer adminClient.Close()
databaseClient, err := spanner.NewClientWithConfig(ctx, "DATABASE_NAME", clientConfig,
option.WithEndpoint("ENDPOINT"),
)
if err != nil {
// Handle error.
}
defer databaseClient.Close()
mTLS
如需建立双向 TLS (mTLS) 连接,请指定 CaCertificateFile、ClientCertificateFile 和 ClientKeyFile:
clientConfig := spanner.ClientConfig{
Type: spanner.OMNI,
CaCertificateFile: "PATH_TO_CA_CERT",
ClientCertificateFile: "PATH_TO_CLIENT_CERT",
ClientKeyFile: "PATH_TO_CLIENT_KEY",
}
adminClient, err := database.NewDatabaseAdminClientWithConfig(ctx, clientConfig,
option.WithEndpoint("ENDPOINT"),
)
if err != nil {
// Handle error.
}
defer adminClient.Close()
databaseClient, err := spanner.NewClientWithConfig(ctx, "DATABASE_NAME", clientConfig,
option.WithEndpoint("ENDPOINT"),
)
if err != nil {
// Handle error.
}
defer databaseClient.Close()
替换以下内容:
PATH_TO_CA_CERT:CA 证书文件的路径。PATH_TO_CLIENT_CERT:客户端证书文件的路径。PATH_TO_CLIENT_KEY:客户端密钥文件的路径。