Nesta página, descrevemos as leituras direcionadas do Spanner e como usá-las.
As leituras direcionadas no Spanner oferecem a flexibilidade para rotear transações somente leitura e leitura única para um tipo de réplica ou região específico em uma configuração de instância multirregional ou uma configuração regional personalizada com regiões somente leitura opcionais.
Casos de uso comuns
Alguns casos de uso comuns para leituras direcionadas incluem:
- Balanceamento de carga de cargas de trabalho em várias regiões para uma utilização de CPU mais uniforme.
- Isolar a análise no seu aplicativo minimizando o impacto sobre as transações do Google Cloud.
- Fornecer isolamento parcial para leituras de fluxos de alterações. Se você usa a API Spanner para fazer streaming mudanças nos dados do Spanner, você pode ajudar a minimizar o impacto cargas de trabalho transacionais usando leituras direcionadas.
Operações de consulta compatíveis
Operações de consulta | As leituras direcionadas são compatíveis? |
---|---|
Leitura desatualizada | Sim |
Leitura forte | Sim |
Transação de leitura/gravação | Não |
Leituras direcionadas não são compatíveis com transações de leitura/gravação
e DML particionada de atualizações em massa. Isso
acontece porque as transações de leitura e gravação precisam ser processadas na região líder. Se
leituras direcionadas forem usadas em uma transação de leitura e gravação, a transação falhará com
um erro BAD_REQUEST
.
Limitações
As leituras direcionadas do Spanner têm as seguintes limitações:
- Só é possível usar leituras direcionadas em uma instância do Spanner que seja em uma configuração de instância multirregional ou uma configuração regional personalizada com regiões somente leitura opcionais.
- Não é possível usar leituras direcionadas com solicitações de leitura/gravação porque as solicitações de gravação são sempre atendidas pela região líder.
- Não é possível usar leituras direcionadas no console do Google Cloud ou na Google Cloud CLI. É disponíveis usando REST e APIs RPC e o Spanner bibliotecas de cliente.
- É possível especificar no máximo 10 réplicas em uma única leitura direcionada.
- Se você usar o painel de insights do sistema ou o Metrics Explorer, nos gráficos "Operações por segundo", "Operações por segundo por banco de dados" e "Operações por segundo por método da API", talvez você encontre a solicitação de leituras direcionadas em um local diferente daquele que você designou. Nesse caso, as informações dos gráficos podem estar incorretas. É possível confirmar que suas solicitações de leitura são encaminhados para as regiões escolhidas usando as métricas de utilização da CPU. Essas métricas mostram as informações mais precisas sobre para onde as leituras direcionadas são o tráfego é roteado.
Antes de começar
Considere o seguinte antes de usar leituras direcionadas:
- O aplicativo pode ter latência adicional se você estiver roteando leituras para uma réplica ou região diferente da mais próxima ao aplicativo.
- É possível encaminhar o tráfego com base em:
- Nome da região (por exemplo,
us-central1
). - Tipo de réplica (valores possíveis:
READ_ONLY
eREAD_WRITE
).
- Nome da região (por exemplo,
- A opção de failover automático em leituras direcionadas é ativada por padrão. Quando o modo automático
opção de failover está ativada e todas as réplicas especificadas estão indisponíveis
ou não íntegros, o Spanner encaminha solicitações para uma réplica fora da
Lista
includeReplicas
. Se você desativar a opção de failover automático e todas as réplicas especificadas estiverem indisponíveis ou com problemas, a solicitação de leituras direcionadas vai falhar.
Parâmetros de leituras direcionadas
Se você estiver usando a API REST ou RPC para realizar leituras direcionadas, defina
esses campos no parâmetro directedReadOptions
. Só é possível incluir um dos
includeReplicas
ou excludeReplicas
, não os dois.
includeReplicas
: contém um conjunto repetido dereplicaSelections
. Esta lista indica a ordem em que as leituras foram direcionadas para regiões ou réplicas específicas. precisam ser considerados. É possível especificar no máximo 10includeReplicas
.replicaSelections
: consiste nolocation
ou na réplica detype
que veicula a solicitação de leitura direcionada. Se você usarincludeReplicas
, será necessário fornecer pelo menos um dos seguintes campos:location
: o local que atende à solicitação de leituras direcionadas. O local precisa ser uma das regiões na configuração multirregional do banco de dados. Se o local não for uma das regiões na configuração multirregional do seu banco de dados, as solicitações não serão roteadas conforme o esperado. Em vez disso, eles são atendidos pela região mais próxima. Por exemplo, é possível direcionar leituras para o localus-central1
em um banco de dados na configuração da instância multirregionalnam6
.type
: o tipo de réplica que atende à solicitação de leituras direcionadas. Possível incluemREAD_WRITE
eREAD_ONLY
.
autoFailoverDisabled
: por padrão, é definido comoFalse
, o que significa que quando o failover está ativado. Quando a opção de failover automático está ativada e todas as réplicas especificadas estão indisponíveis ou inoperantes, o Spanner encaminha solicitações para uma réplica fora da listaincludeReplicas
. Se você desativar a opção de failover automático e todas as réplicas especificadas indisponível ou não íntegro, a solicitação de leitura direcionada falhará. Valores possíveis incluirTRUE
para desativado eFALSE
para ativado.
excludeReplicas
: contém um conjunto repetido dereplicaSelections
que é excluído das solicitações de serviço. O Spanner não faz o roteamento solicitações para as réplicas da lista.replicaSelections
: o local ou o tipo de réplica que é excluído da veiculação da solicitação de leituras direcionadas. Se você usarexcludeReplicas
, é necessário informar pelo menos um dos seguintes campos:location
: o local excluído da veiculação do solicitação de leitura direcionada.type
: o tipo de réplica que é excluída da veiculação do direcionado lê a solicitação. Os tipos possíveis incluemREAD_WRITE
eREAD_ONLY
.
Para conferir um exemplo de como é um corpo de solicitação REST, clique na guia REST na seção Usar leituras direcionadas.
Usar leituras direcionadas
É possível usar as bibliotecas de cliente do Spanner e as APIs REST e RPC para realizar leituras direcionadas.
Bibliotecas de cliente
C++
C#
Go
Java
Node.js
PHP
Python
Ruby
REST
É possível usar as seguintes APIs REST para executar leituras direcionadas:
Por exemplo, para realizar leituras direcionadas em us-central1
usando executeSQL
:
Para a sessão, digite:
projects/<VAR>PROJECT-ID</VAR>/instances/<VAR>INSTANCE-ID</VAR>/databases/<VAR>DATABASE-ID</VAR>/sessions/<VAR>SESSION-ID</VAR>
Substitua:
- PROJECT-ID: o ID do projeto;
- INSTANCE-ID: o ID da instância
- DATABASE-ID: o ID do banco de dados.
- SESSION-ID: o ID da sessão.
Você recebe o valor
SESSION-ID
ao criar uma sessão.
Para o Corpo de solicitação, use o seguinte:
{ "directedReadOptions": { "includeReplicas": { "replicaSelections": [ { "location": "us-central1", } ] } }, "sql": "SELECT SingerId, AlbumId, AlbumTitle FROM Albums" }
Clique em Executar. A resposta exibe os resultados da consulta.
RPC
Você pode usar as seguintes APIs RPC para realizar leituras direcionadas:
A seguir
- Saiba como realizar Leituras fora das transações.