Nesta página, descrevemos as leituras direcionadas do Spanner e como usá-las.
As leituras direcionadas no Spanner oferecem a flexibilidade de rotear transações somente leitura e leituras únicas, a uma determinada tipo de réplica ou região em uma configuração de instância multirregional ou um tipo configuração regional 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 streams de alterações; Se você usa a API Spanner para transmitir mudanças de dados do Spanner, pode minimizar o impacto nas cargas de trabalho transacionais usando leituras direcionadas.
Operações de consulta com suporte
Operações de consulta | 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
é porque as transações de leitura/gravação precisam ser processadas na região líder. Se
leituras direcionadas são usadas em uma transação de leitura/gravação, a transação falha 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 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ê usa o painel de insights do sistema ou o Metrics Explorer, na Operações por segundo, operações por segundo por banco de dados e operações por segundo pelos gráficos de método da API, é possível que você veja sua 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 o tráfego de leituras direcionadas é roteado.
Antes de começar
Considere o seguinte antes de usar leituras direcionadas:
- O aplicativo pode gerar mais latência se você estiver roteando leituras para um réplica ou região diferente da mais próxima do aplicativo.
- É possível rotear 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 de
includeReplicas
. Se você desativar a opção de failover automático e as réplicas especificadas não estiverem disponíveis ou não estiverem íntegras, as leituras direcionadas serão falha.
Parâmetros de leitura direta
Se você estiver usando a API REST ou RPC para executar leituras direcionadas, será necessário definir
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
. Essa lista indica a ordem em que as leituras direcionadas para regiões ou tipos de réplica específicos devem ser consideradas. É 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
, você precisa informar 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 como esperado. Em vez disso, eles são veiculados da 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 todos os réplicas especificadas não estiverem disponíveis ou não estiverem íntegras, o Spanner encaminha solicitações para uma réplica fora da lista deincludeReplicas
. Se você desativar a opção de failover automático e todas as réplicas especificadas indisponível ou não estiver í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 atendimento. 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 foi excluído de atender à solicitação de leituras direcionadas. Se você usaexcludeReplicas
, você deve fornecer pelo menos um dos seguintes campos:location
: o local excluído da veiculação da solicitação de leituras direcionadas.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 ver um exemplo de corpo de uma solicitação REST, clique no 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 executar 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
É possível usar as seguintes APIs RPC para executar leituras direcionadas:
A seguir
- Saiba como realizar leitura fora das transações.