Voyage AI joins MongoDB to power more accurate and trustworthy AI applications on Atlas.

Explore o novo chatbot do Developer Center! O MongoDB AI chatbot pode ser acessado na parte superior da sua navegação para responder a todas as suas perguntas sobre o MongoDB .

MongoDB 3.6: Aqui para o SRV com conexões de conjunto de réplicas mais fáceis

Joe Drumgoole4 min read • Published Dec 17, 2021 • Updated Sep 23, 2022
Facebook Icontwitter iconlinkedin icon
Classifique este anúncio
star-empty
star-empty
star-empty
star-empty
star-empty
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.
Atlas SRV Address screenshot

Listas de sementes do MongoDB

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:
Atlas screenshot: using driver 3.4 or earlier
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.

Leitura de registros SRV e TXT

Podemos ver como isso funciona na prática em um cluster do MongoDB Atlas com um script Python simples.
1import srvlookup #pip install srvlookup
2import sys
3import dns.resolver #pip install dnspython
4
5host = None
6
7if len(sys.argv) > 1 :
8 host = sys.argv[1]
9
10if 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
17else:
18 print("No host specified")
Podemos executar este script utilizando o nó especificado na string de conexão 3.6 como um parâmetro.
The node is specified in the connection string
1$ python mongodb_srv_records.py
2freeclusterjd-ffp4c.mongodb.net
3freeclusterjd-shard-00-00-ffp4c.mongodb.net:27017
4freeclusterjd-shard-00-01-ffp4c.mongodb.net:27017
5freeclusterjd-shard-00-02-ffp4c.mongodb.net:27017
6freeclusterjd-ffp4c.mongodb.net: "authSource=admin&replicaSet=FreeClusterJD-shard-0"
7$
Você também pode fazer essa pesquisa com o nslookup:
1JD10Gen-old:~ jdrumgoole$ nslookup
2> set type=SRV > \_mongodb._tcp.rs.joedrumgoole.com
3Server: 10.65.141.1
4Address: 10.65.141.1#53
5
6Non-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
11Authoritative answers can be found from:
12> set type=TXT
13> rs.joedrumgoole.com
14Server: 10.65.141.1
15Address: 10.65.141.1#53
16
17Non-authoritative answer:
18rs.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.

Criação de registros SRV e TXT

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
1rs1.joedrumgoole.com
2rs2.joedrumgoole.com
3rs3.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.
Setting DNS names in 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:
Settings page from AWS Route 53 - Name, Type, Alias: TTL and Value
O que leva à seguinte entrada no arquivo de zona para Route 53.
Generated entry in 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:
Editing the record configuration to set 'rs.joedrumgoole.com' as name
Isso criará o seguinte registro TXT.
Updated Route 53 entry
Agora podemos acessar este serviço como :
1mongodb+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:
Setting SRV connection string process
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.
You can sign up for a free MongoDB Atlas tier which is suitable for single user use.
Find out how to use your favorite programming language with MongoDB via our MongoDB drivers.
Please visit MongoDB University for free online training in all aspects of MongoDB.
Seguir Joe Drumgoole on twitter for more news about MongoDB.

Facebook Icontwitter iconlinkedin icon
Classifique este anúncio
star-empty
star-empty
star-empty
star-empty
star-empty
Relacionado
Tutorial

Dados da primavera desbloqueados: queries avançadas com MongoDB


Nov 08, 2024 | 7 min read
Início rápido

Tutorial de fluxos de alterações e triggers com o Node.js


Aug 24, 2023 | 17 min read
Artigo

Construindo APIs REST com API Platform e MongoDB


Jan 14, 2025 | 9 min read
Início rápido

Java - Change Streams


Oct 01, 2024 | 10 min read