MongoDB 3.6: Aqui para o SRV com conexões de conjunto de réplicas mais fáceis
Classifique este anúncio
If you have logged into MongoDB Atlas
recently - and you should, the entry-level tier is free! - you may have
noticed a strange new syntax on 3.6 connection strings.

What is this
mongodb+srv
syntax?Well, in MongoDB 3.6 we introduced the concept of a seed
list
that is specified using DNS records, specifically
SRV and
TXT records. You will recall
from using replica sets with MongoDB that the client must specify at
least one replica set member (and may specify several of them) when
connecting. This allows a client to connect to a replica set even if one
of the nodes that the client specifies is unavailable.
Você pode ver um exemplo deste URL em uma string de conexão do cluster 3.4:

Note that without the SRV record configuration we must list several
nodes (in the case of Atlas we always include all the cluster members,
though this is not required). We also have to specify the
ssl
and
replicaSet
options.With the 3.4 or earlier driver, we have to specify all the options on
the command line using the MongoDB URI
syntax.
O uso de registros SRV elimina a necessidade de cada cliente de
passar um conjunto completo de informações de estado para o cluster. Em vez disso, um
único registro SRV identifica todos os nós associados ao cluster
(e seus números de porta) e um registro TXT associado define as
opções para o URI.
Podemos ver como isso funciona na prática em um cluster do MongoDB Atlas com um script Python simples.
1 import srvlookup #pip install srvlookup 2 import sys 3 import dns.resolver #pip install dnspython 4 5 host = None 6 7 if len(sys.argv) > 1 : 8 host = sys.argv[1] 9 10 if host : 11 services = srvlookup.lookup("mongodb", domain=host) 12 for i in services: 13 print("%s:%i" % (i.hostname, i.port)) 14 for txtrecord in dns.resolver.query(host, 'TXT'): 15 print("%s: %s" % ( host, txtrecord)) 16 17 else: 18 print("No host specified")
Podemos executar este script utilizando o nó especificado na string de conexão 3.6 como um parâmetro.

1 python mongodb_srv_records.py 2 freeclusterjd-ffp4c.mongodb.net 3 freeclusterjd-shard-00-00-ffp4c.mongodb.net:27017 4 freeclusterjd-shard-00-01-ffp4c.mongodb.net:27017 5 freeclusterjd-shard-00-02-ffp4c.mongodb.net:27017 6 freeclusterjd-ffp4c.mongodb.net: "authSource=admin&replicaSet=FreeClusterJD-shard-0" 7
Você também pode fazer essa pesquisa com o nslookup:
1 JD10Gen-old:~ jdrumgoole$ nslookup 2 set type=SRV > \_mongodb._tcp.rs.joedrumgoole.com 3 Server: 10.65.141.1 4 Address: 10.65.141.1#53 5 6 Non-authoritative answer: 7 \_mongodb._tcp.rs.joedrumgoole.com service = 0 0 27022 rs1.joedrumgoole.com. 8 \_mongodb._tcp.rs.joedrumgoole.com service = 0 0 27022 rs2.joedrumgoole.com. 9 \_mongodb._tcp.rs.joedrumgoole.com service = 0 0 27022 rs3.joedrumgoole.com. 10 11 Authoritative answers can be found from: 12 set type=TXT 13 rs.joedrumgoole.com 14 Server: 10.65.141.1 15 Address: 10.65.141.1#53 16 17 Non-authoritative answer: 18 rs.joedrumgoole.com text = "authSource=admin&replicaSet=srvdemo"
Você pode ver como isso pode ser usado para criar uma string de conexão de estilo 3.4 comparando-a com a string de conexão 3.4 acima.
Como você pode ver, a complexidade do cluster e seus parâmetros de configuração são armazenados no servidor DNS e ocultados do usuário final. Se o endereço IP ou nome de um nó mudar ou quisermos alterar o nome do conjunto de réplicas, tudo agora pode ser feito de forma totalmente transparente da perspectiva do cliente. Também podemos adicionar e remover nós de um cluster sem impacto nos clientes.
So now whenever you see
mongodb+srv
you know you are expecting a SRV
and TXT record to deliver the client connection string.Of course, SRV and TXT records are not just for Atlas. You can also
create your own SRV and TXT records for your self-hosted MongoDB
clusters. All you need for this is edit access to your DNS server so you
can add SRV and TXT records. In the examples that follow we are using
the AWS Route 53 DNS service.
Configurei um conjunto de réplicas de demonstração no AWS com uma configuração de três nós. Eles
são
1 rs1.joedrumgoole.com 2 rs2.joedrumgoole.com 3 rs3.joedrumgoole.com
Cada um tem um processo mongod em execução na porta 27022. Eu configurei um
grupo de segurança que permite o acesso ao meu laptop local e aos nós
para que possam se ver.
Também configurei os nomes DNS para os nós acima no AWS Route 53.

Podemos iniciar os processos do mongod executando o seguinte comando em cada nó.
1 sudo /usr/local/m/versions/3.6.3/bin/mongod --auth --port 27022 --replSet srvdemo --bind_ip 0.0.0.0 --keyFile mdb_keyfile"
Agora precisamos configurar os registros SRV e TXT para esse cluster.
The SRV record points to the server or servers that will comprise the
members of the replica set. The TXT record defines the options for the
replica set, specifically the database that will be used for
authorization and the name of the replica set. It is important to note
that the mongodb+srv format URI implicitly adds "ssl=true". In our
case SSL is not used for the demo so we have to append "&ssl=false" to
the client connector. Note that the SRV record is specifically designed
to look up the mongodb service referenced at the start of the URL.
As configurações no AWS Route 53 são:

O que leva à seguinte entrada no arquivo de zona para Route 53.

Now we can add the TXT record. By convention, we use the same name as
the SRV record (
rs.joedrumgoole.com
) so that MongoDB knows where to
find the TXT record.Podemos fazer isso no AWS Route 53 da seguinte maneira:

Isso criará o seguinte registro TXT.

Agora podemos acessar este serviço como :
1 mongodb+srv://rs.joedrumgoole.com/test
Isso recuperará um URL completo e uma string de conexão que podem ser usados para entrar em contato com o serviço.
O processo completo é descrito abaixo:

Depois que seus registros forem configurados, você poderá alterar facilmente os números de porta sem afetar os clientes e também adicionar e remover membros do cluster.
Os registros SRV são outra maneira pela qual o MongoDB está facilitando a vida de desenvolvedores de banco de dados em todos os lugares.