En la página, se describen las operaciones de lectura dirigidas de Spanner y cómo usarlas.
Las lecturas dirigidas en Spanner brindan flexibilidad para enrutar transacciones de solo lectura y las lecturas únicas a una tipo de réplica o región dentro de una configuración de instancia multirregional o una configuración regional con regiones opcionales de solo lectura.
Casos de uso habituales
Estos son algunos casos de uso comunes de las lecturas dirigidas:
- Balanceo de cargas en varias regiones para lograr una utilización de CPU más uniforme.
- Aísla las estadísticas de tu aplicación minimizando el impacto en las transacciones de las cargas de trabajo.
- Proporciona aislamiento parcial para las lecturas de flujos de cambios. Si usas la API de Spanner para transmitir de Google Spanner, puedes ayudar a minimizar el impacto cargas de trabajo transaccionales con lecturas dirigidas.
Operaciones de consulta admitidas
Operaciones de consulta | ¿Se admiten las operaciones de lectura dirigidas? |
---|---|
Lectura inactiva | Sí |
Lectura sólida | Sí |
Transacción de lectura y escritura | No |
Las operaciones de lectura dirigidas no son compatibles con los tipos de transacciones de lectura y escritura ni de DML particionado de las actualizaciones masivas. Esta
es que las transacciones de lectura y escritura
deben procesarse en la región líder. Si se usan lecturas dirigidas en una transacción de lectura y escritura, la transacción falla con un error BAD_REQUEST
.
Limitaciones
Las lecturas dirigidas de Spanner tienen las siguientes limitaciones:
- Solo puedes usar lecturas dirigidas en una instancia de Spanner que esté en una configuración de instancias multirregional o una configuración regional personalizada con regiones opcionales de solo lectura.
- No puedes usar lecturas dirigidas con solicitudes de lectura y escritura porque la escritura la región líder siempre entrega las solicitudes.
- No puedes usar lecturas dirigidas en la consola de Google Cloud ni en Google Cloud CLI. Sí disponibles con REST y APIs de RPC y Spanner bibliotecas cliente.
- Puedes especificar un máximo de 10 réplicas en una sola operación de lectura dirigida.
- Si usas el panel de estadísticas del sistema o el Explorador de métricas, en los gráficos Operaciones por segundo, Operaciones por segundo por base de datos y Operaciones por segundo por método de API, es posible que veas tu solicitud de operaciones de lectura dirigidas en una ubicación diferente de la que designaste. En este caso, la información de los gráficos puede ser incorrecto. Puedes confirmar que tus solicitudes de lectura se enrutan a las regiones que elegiste con las métricas de uso de CPU. Estas métricas muestran la información más precisa sobre dónde se realizaron las lecturas dirigidas cuando se enrute el tráfico.
Antes de comenzar
Ten en cuenta lo siguiente antes de usar las lecturas dirigidas:
- La aplicación podría incurrir en latencia adicional si enrutas las operaciones de lectura a una réplica o región que no sea la más cercana a la aplicación.
- Puedes enrutar el tráfico en función de lo siguiente:
- Nombre de la región (por ejemplo,
us-central1
). - Tipo de réplica (valores posibles:
READ_ONLY
yREAD_WRITE
).
- Nombre de la región (por ejemplo,
- La opción de conmutación por error automática en las operaciones de lectura dirigidas está habilitada de forma predeterminada. Cuando la opción de conmutación por error automática está habilitada y todas las réplicas especificadas no están disponibles o no funcionan correctamente, Spanner enruta las solicitudes a una réplica fuera de la lista
includeReplicas
. Si inhabilitas la opción de conmutación por error automática y las réplicas especificadas no están disponibles o en mal estado, las operaciones de lectura la solicitud falla.
Parámetros de lecturas dirigidas
Si usas la API de REST o RPC para realizar lecturas dirigidas, debes definir
estos campos en el parámetro directedReadOptions
. Solo puedes incluir uno de
includeReplicas
o excludeReplicas
, no ambos.
includeReplicas
: Contiene un conjunto repetido dereplicaSelections
. Esta lista indica el orden en el que se deben considerar las operaciones de lectura dirigidas a regiones o tipos de réplicas específicas. Puedes especificar un máximo de 10includeReplicas
.replicaSelections
: Consiste en la entrega delocation
o la réplica detype
la solicitud de lectura dirigida. Si usasincludeReplicas
, debes proporcionar al menos uno de los siguientes campos:location
: Es la ubicación que entrega la solicitud de lecturas dirigidas. El La ubicación debe ser una de las regiones dentro de la configuración de tu base de datos. Si la ubicación no es una de las regiones dentro de la configuración multirregional de tu base de datos, las solicitudes no se enrutarán como se espera. sino que se entregan desde la región más cercana. Por ejemplo, puedes dirigir las operaciones de lectura a la ubicaciónus-central1
en una base de datos en la configuración de instancia multirregionalnam6
.type
: Es el tipo de réplica que entrega la solicitud de lectura dirigida. Los tipos posibles sonREAD_WRITE
yREAD_ONLY
.
autoFailoverDisabled
: De forma predeterminada, se establece enFalse
, lo que significa que el modo automático. la conmutación por error esté habilitada. Cuando la opción de conmutación por error automática está habilitada y todas las réplicas especificadas no están disponibles o no funcionan correctamente, Spanner enruta las solicitudes a una réplica fuera de la listaincludeReplicas
. Si inhabilitar la opción de conmutación por error automática y todas las réplicas especificadas se disponible o en mal estado, la solicitud de lectura dirigida falla. Entre los valores posibles, se incluyenTRUE
para inhabilitado yFALSE
para habilitado.
excludeReplicas
: Contiene un conjunto repetido dereplicaSelections
que se excluye de las solicitudes de publicación. Spanner no enruta las solicitudes a las réplicas de esta lista.replicaSelections
: Es la ubicación o el tipo de réplica que se excluye de la publicación de la solicitud de operaciones de lectura dirigidas. Si usasexcludeReplicas
, debes proporcionar al menos uno de los siguientes campos:location
: Es la ubicación que se excluye de publicar el de lectura dirigida.type
: Es el tipo de réplica que se excluye de la publicación de la solicitud de lecturas dirigidas. Los tipos posibles incluyenREAD_WRITE
yREAD_ONLY
.
Para ver un ejemplo de cómo se ve el cuerpo de una solicitud REST, haz clic en la pestaña REST en la sección Cómo usar lecturas dirigidas.
Usa lecturas dirigidas
Puedes usar las bibliotecas cliente de Spanner y las APIs de REST y RPC para realizar lecturas dirigidas.
Bibliotecas cliente
C++
C#
Go
Java
Node.js
PHP
Python
Ruby
REST
Puedes usar las siguientes APIs de REST para realizar lecturas dirigidas:
Por ejemplo, para realizar lecturas dirigidas en us-central1
con executeSQL
, sigue estos pasos:
Haz clic en
projects.instances.databases.sessions.executeSql
.En sesión, ingresa lo siguiente:
projects/<VAR>PROJECT-ID</VAR>/instances/<VAR>INSTANCE-ID</VAR>/databases/<VAR>DATABASE-ID</VAR>/sessions/<VAR>SESSION-ID</VAR>
Reemplaza lo siguiente:
- PROJECT-ID: El ID del proyecto.
- INSTANCE-ID: El ID de la instancia.
- DATABASE-ID: El ID de la base de datos.
- SESSION-ID: Es el ID de sesión.
Recibirás el valor
SESSION-ID
cuando crees una sesión.
En el cuerpo de la solicitud, usa lo siguiente:
{ "directedReadOptions": { "includeReplicas": { "replicaSelections": [ { "location": "us-central1", } ] } }, "sql": "SELECT SingerId, AlbumId, AlbumTitle FROM Albums" }
Haz clic en Ejecutar. En la respuesta, se muestran los resultados de la consulta.
RPC
Puedes usar las siguientes APIs de RPC para realizar lecturas dirigidas:
¿Qué sigue?
- Obtén información para realizar lecturas fuera de las transacciones.