【问题标题】:Connect to AWS DocumentDB from Java Program via SSH Tunnel通过 SSH 隧道从 Java 程序连接到 AWS DocumentDB
【发布时间】:2021-10-24 22:13:44
【问题描述】:

是否有人设法将 java 程序连接到 AWS DocumentDB,其中 java 程序在 AWS 之外运行并且 DocumentDB 启用了 tls?提供的任何示例或指导将不胜感激。

这是我目前所做的 =>

我一直在关注 AWS 的开发人员指南,并且我知道要做到这一点,我需要一个 SSH 隧道设置到跳转盒(EC2 实例),然后设置到数据库集群。我已经这样做了,并通过我的笔记本电脑进行了连接。

然后,我从 AWS 的 rds-combined-ca-bundle.pem 文件创建了所需的 .jks 文件,并在基本的 java 主类中引用了它。在 java 主类中,我将集群引用为 localhost:27017,因为这是我设置 SSH 隧道的地方。

我的测试代码遵循 Java 的 AWS 示例,运行程序时出现以下错误 =>

原因:javax.net.ssl.SSLHandshakeException:找不到与 localhost 匹配的主题备用 DNS 名称。

公共类 CertsTestMain {

public static void main(String[] args) {

    String template = "mongodb://%s:%s@%s/test?ssl=true&replicaSet=rs0&readpreference=%s";
    String username = "dummy";
    String password = "dummy";
    String clusterEndpoint = "localhost:27017";
    String readPreference = "secondaryPreferred";
    String connectionString = String.format(template, username, password, clusterEndpoint, readPreference);

    String truststore = "C:/Users/eclipse-workspace/certs/certs/rds-truststore.jks";
    String truststorePassword = "test!";

    System.setProperty("javax.net.ssl.trustStore", truststore);
    System.setProperty("javax.net.ssl.trustStorePassword", truststorePassword);

    MongoClient mongoClient = MongoClients.create(connectionString);

    MongoDatabase testDB = mongoClient.getDatabase("test");
    MongoCollection<Document> bookingCollection = testDB.getCollection("booking");


    MongoCursor<Document> cursor = bookingCollection.find().iterator();
    try {
        while (cursor.hasNext()) {
            System.out.println(cursor.next().toJson());
        }
    } finally {
        cursor.close();
    }

}

}

【问题讨论】:

标签: java ssh-tunnel aws-documentdb


【解决方案1】:

所以,对我来说,要完成这项工作,我只需将模板更改为:

字符串模板 = "mongodb://%s:%s@%s/test?sl=true&tlsAllowInvalidHostnames&readpreference=%s";

只要您正确创建了 .jks 文件 (我通过使用 linux env 并在第 2 点的以下链接中运行 AWS 为 Java 提供的脚本简单地做到了这一点 => https://docs.aws.amazon.com/documentdb/latest/developerguide/connect_programmatically.html) 并且您有一个完整的 ssh 隧道,如https://docs.aws.amazon.com/documentdb/latest/developerguide/connect-from-outside-a-vpc.html 中所述 那么上面的代码就可以工作了。

【讨论】:

    猜你喜欢
    • 2021-05-02
    • 2023-02-10
    • 1970-01-01
    • 2021-05-03
    • 2021-11-13
    • 1970-01-01
    • 2021-02-15
    • 2018-10-06
    • 2016-02-04
    相关资源
    最近更新 更多