本页面介绍了 Spanner 定向读取及其使用方法。
Spanner 中的定向读取可让您灵活地将只读事务和单次读取路由到多区域实例配置或包含可选只读区域的自定义区域配置中的特定副本类型或区域。
常见使用场景
有向读取的一些常见应用场景包括:
- 跨多个区域对工作负载进行负载均衡,以实现更均匀的工作负载 CPU 利用率。
- 最大限度地减少对事务工作负载的影响,从而在应用中隔离分析。
- 为变更数据流读取提供部分隔离。 如果您使用 Spanner API 流式传输 Spanner 数据更改,您可以帮助最大限度地减少对 事务工作负载。
支持的查询操作
查询操作 | 是否支持定向读取? |
---|---|
过时读取 | 是 |
强读取 | 是 |
读写事务 | 否 |
读写事务和分区 DML 类型的批量更新不支持有针对性地读取。这是因为读写事务必须在主区域中处理。如果
有定向读取在读写事务中使用,则事务会失败
BAD_REQUEST
错误。
限制
Spanner 有向读取具有以下限制:
- 您只能在采用多区域实例配置或包含可选只读区域的自定义区域配置的 Spanner 实例中使用定向读取。
- 您不能将定向读取与读写请求搭配使用,因为写入 请求始终由主要区域处理。
- 您无法在 Google Cloud 控制台或 Google Cloud CLI 中使用定向读取。时间是 可使用 REST 和 RPC API 和 Spanner 客户端库。
- 您可以在单个定向读取中最多指定 10 个副本。
- 如果您使用系统数据分析信息中心 或 Metrics Explorer 中找到 每秒操作次数、每秒操作次数(按数据库)以及操作次数 每秒查看次数(按 API 方法图表),您可能会看到您的定向读取请求 不在您指定的位置。在这种情况下,图表中的信息可能会不正确。您可以使用 CPU 利用率指标确认您的读取请求是否已路由到您选择的区域。这些指标显示了有关定向阅读位置的最准确信息 流量进行路由
准备工作
在使用定向读取之前,请考虑以下事项:
- 如果您将读取路由到 副本或区域,而不是距离应用最近的那个副本或区域。
- 您可以根据以下条件路由流量:
- 区域名称(例如:
us-central1
)。 - 副本类型(可能的值:
READ_ONLY
和READ_WRITE
)。
- 区域名称(例如:
- 有选择性读取中的自动故障切换选项默认处于启用状态。自动开启时
已启用故障切换选项,并且所有指定的副本都不可用
Spanner 会将请求路由到
includeReplicas
列表。如果您停用了自动故障转移选项,并且所有指定的副本均不可用或不健康,则定向读取请求会失败。
定向读取参数
如果您使用 REST 或 RPC API 执行定向读取,则必须定义
directedReadOptions
参数中的这些字段。您只能包含 includeReplicas
或 excludeReplicas
之一,不能同时包含这两者。
includeReplicas
:包含一组重复的replicaSelections
。此列表 指示对特定区域或副本的定向读取的顺序 类型。您最多可以指定 10 个includeReplicas
。replicaSelections
:包含服务的location
或副本type
定向读取请求如果您使用的是includeReplicas
,则必须至少提供以下字段之一:location
:传送定向读取请求的位置。该位置必须是数据库的多区域配置中的某个区域。如果该位置不属于 数据库多区域配置内的区域 请求的路由。而是由 最近的区域例如,您可以在多区域实例配置nam6
中将读取操作定向到数据库的位置us-central1
。type
:处理定向读取请求的副本类型。可能的类型包括READ_WRITE
和READ_ONLY
。
autoFailoverDisabled
:默认情况下,此值设为False
,表示自动故障切换处于启用状态。当自动故障切换选项处于启用状态且所有指定的副本均不可用或不健康时,Spanner 会将请求路由到includeReplicas
列表之外的副本。如果您 停用自动故障切换选项,并且所有指定的副本均已 不可用或健康状况不佳,则定向读取请求将失败。可能的值 包含TRUE
(表示已停用),FALSE
(表示已启用)。
excludeReplicas
:包含一组重复的replicaSelections
,这些replicaSelections
会从广告投放请求中排除。Spanner 不进行路由 副本数量请求。replicaSelections
:排除的位置或副本类型 以阻止传送定向读取请求如果您使用的是excludeReplicas
,则必须至少提供以下字段之一:location
:从处理定向读取请求中排除的位置。type
:从处理定向读取请求中排除的副本类型。可能的类型包括READ_WRITE
和READ_ONLY
。
要查看 REST 请求正文示例,请点击 使用定向读取部分中的 REST 标签页。
使用定向读取
您可以使用 Spanner 客户端库以及 REST 和 RPC API 执行有针对性地读取。
客户端库
C++
C#
Go
Java
Node.js
PHP
Python
Ruby
REST
您可以使用以下 REST API 执行定向读取:
例如,如需使用 executeSQL
在 us-central1
中执行有针对性的读取,请执行以下操作:
对于 session,输入:
projects/<VAR>PROJECT-ID</VAR>/instances/<VAR>INSTANCE-ID</VAR>/databases/<VAR>DATABASE-ID</VAR>/sessions/<VAR>SESSION-ID</VAR>
替换以下内容:
- PROJECT-ID:项目 ID。
- INSTANCE-ID:实例 ID。
- DATABASE-ID:数据库 ID。
- SESSION-ID:会话 ID。
您在创建会话时会收到
SESSION-ID
值。
对于 Request body,使用以下内容:
{ "directedReadOptions": { "includeReplicas": { "replicaSelections": [ { "location": "us-central1", } ] } }, "sql": "SELECT SingerId, AlbumId, AlbumTitle FROM Albums" }
点击 Execute。该响应会显示查询结果。
RPC
您可以使用以下 RPC API 执行定向读取:
后续步骤
- 了解如何在事务外部执行读取操作。