从 Java 程序连接到 documentdb

问题描述

在 AWS 中,我创建了一个 documentdb 集群。我使用与此处相同的 java 程序,只对连接字符串进行必要的更改。 here 我无法连接。这是错误信息:

Feb 06,2021 9:56:36 PM com.mongodb.diagnostics.logging.JULLogger log
INFO: Cluster created with settings {hosts=[price-manager-prod-new-docdb-clsuter.cluster- 
cduzobvhwuhh.us-east-1.docdb.amazonaws.com:27017],mode=MULTIPLE,requiredClusterType=REPLICA_SET,serverSelectionTimeout='30000 ms',maxWaitQueueSize=500,requiredreplicasetName='rs0'}
Feb 06,2021 9:56:36 PM com.mongodb.diagnostics.logging.JULLogger log
INFO: Adding discovered server price-manager-prod-new-docdb-clsuter.cluster-cduzobvhwuhh.us-east- 
1.docdb.amazonaws.com:27017 to client view of cluster
Feb 06,2021 9:56:36 PM com.mongodb.diagnostics.logging.JULLogger log
INFO: No server chosen by com.mongodb.client.internal.MongoClientDelegate$1@5890e879 from cluster 
description ClusterDescription{type=REPLICA_SET,connectionMode=MULTIPLE,serverDescriptions= 
[ServerDescription{address=price-manager-prod-new-docdb-clsuter.cluster-cduzobvhwuhh.us-east- 
1.docdb.amazonaws.com:27017,type=UNKNowN,state=CONNECTING}]}. Waiting for 30000 ms before timing 
out
Feb 06,2021 9:56:56 PM com.mongodb.diagnostics.logging.JULLogger log
INFO: Exception in monitor thread while connecting to server price-manager-prod-new-docdb- 
clsuter.cluster-cduzobvhwuhh.us-east-1.docdb.amazonaws.com:27017
com.mongodb.MongoSocketopenException: Exception opening socket
at com.mongodb.internal.connection.socketStream.open(SocketStream.java:70)
at com.mongodb.internal.connection.InternalStreamConnection.open(InternalStreamConnection.java:128)
at com.mongodb.internal.connection.DefaultServerMonitor$ServerMonitorRunnable.run(DefaultServerMonitor.java:117)

亚马逊要求使用以下连接字符串。 mongodb://docdbnewbie:@price-manager-prod-new-docdb-clsuter.cluster-cduzobvhwuhh.us-east-1.docdb.amazonaws.com:27017/?ssl=true&ssl_ca_certs=rds-combined-ca-bundle。 pem&replicaset=rs0&readPreference=secondaryPreferred&retryWrites=false

程序中,连接字符串中我没有使用ssl_ca_certs=rds-combined-ca-bundle.pem。 我导入到密钥库的 pem 文件。 创建集群时,它要求提供主用户名和密码。我只是使用 docdbnewbie 作为用户名和一些虚构的密码。我是否必须事先创建一个用户并事先为其提供相关政策?

更新:我已经能够在 java 客户端和 AWS 托管的 documentdb 之间建立连接。但是我的 java 程序也在 EC2 中 - 使用了 cloud9。如果有人可以说明在客户端位于 VPC 之外时是否可以建立这种连接,那将大有帮助。

解决方法

如果您查看共享文档,在 Connecting to an Amazon DocumentDB Cluster from Outside an Amazon VPC 部分下,它清楚地说明您需要通过在 DocumentDB 的 VPC 内运行的 EC2 实例设置 SSH 隧道。准确地说,

要创建 SSH 隧道,您需要一个与 Amazon DocumentDB 集群在同一 Amazon VPC 中运行的 Amazon EC2 实例。您可以在与集群相同的 VPC 中使用现有 EC2 实例,也可以创建一个。

该指南显示您使用以下命令转发 27017(mongodb 的默认端口)。

ssh -i "ec2Access.pem" -L 27017:sample-cluster.node.us-east-1.docdb.amazonaws.com:27017 ubuntu@ec2-34-229-221-164.compute-1.amazonaws.com -N

完成隧道设置后,您将使用 localhost:27017 作为 DocumentDB 的端点,而不是自定义 DNS 名称 price-manager-prod-new-docdb-clsuter.cluster-cduzobvhwuhh.us-east-1.docdb.amazonaws.com:27017。此 DNS 名称不公开可用,只能从您的 VPC 内解析。这就是为什么相同的程序在 VPC 内的 EC2 上运行时正在运行的原因。

如果您不想使用localhost,应该有一种方法可以在 SSH 隧道命令中配置所需的端点,您可以查看它。