文档数据库服务 DDS-连接DDS实例的常用方式:java mongo客户端

时间:2024-05-20 17:43:40

java mongo客户端

  • 前提条件
    1. 连接数据库的弹性云服务器必须和DDS实例之间网络互通,可以使用curl命令连接DDS实例服务端的IP和端口号,测试网络连通性。

      curl ip:port

      返回“It looks like you are trying to access MongoDB over HTTP on the native driver port.”,说明网络互通。

    2. 参考MongoDB兼容性列表,下载兼容数据库实例版本的mongo jar包。
    3. 在弹性云服务器上安装jdk。
    4. 如果开启SSL,需要在界面上下载根证书,并上传到弹性云服务器。
  • 连接代码

    用keytool工具手动生成trustStore:

    // 认证用的用户名和密码直接写到代码中有很大的安全风险,建议在配置文件或者环境变量中存放(密码应密文存放、使用时解密),确保安全;

    // 本示例以用户名和密码保存在环境变量中为例,运行本示例前请先在本地环境中设置环境变量(环境变量名称请根据自身情况进行设置)EXAMPLE_USERNAME_ENV和EXAMPLE_PASSWORD_ENV。

    String password = System.getenv("EXAMPLE_PASSWORD_ENV");

    keytool -import -file /var/chroot/mongodb/CA/ca.crt -keystore /home/Mike/jdk1.8.0_112/jre/lib/security/mongostore -storetype pkcs12 -storepass ${password}

    • “/var/chroot/mongodb/CA/ca.crt”为根证书路径。
    • “/home/Mike/jdk1.8.0_112/jre/lib/security/mongostore”为生成的trustStore的路径。
    • SSL开启
      import java.util.ArrayList;
      import java.util.List;
      import org.bson.Document;
      import com.mongodb.MongoClient;
      import com.mongodb.MongoCredential;
      import com.mongodb.ServerAddress;
      import com.mongodb.client.MongoDatabase;
      import com.mongodb.client.MongoCollection;
      import com.mongodb.MongoClientURI;
      import com.mongodb.MongoClientOptions;
      public class MongoDBJDBC {
      public static void main(String[] args){
            try {
                    System.setProperty("javax.net.ssl.trustStore", "/home/Mike/jdk1.8.0_112/jre/lib/security/mongostore");
                    // 认证用的用户名和密码直接写到代码中有很大的安全风险,建议在配置文件或者环境变量中存放(密码应密文存放、使用时解密),确保安全;
                    // 本示例以用户名和密码保存在环境变量中为例,运行本示例前请先在本地环境中设置环境变量(环境变量名称请根据自身情况进行设置)EXAMPLE_USERNAME_ENV和EXAMPLE_PASSWORD_ENV。
                    String password = System.getenv("EXAMPLE_PASSWORD_ENV");
                    System.setProperty("javax.net.ssl.trustStorePassword", password);
                    ServerAddress serverAddress = new ServerAddress("ip", port);
                    List addrs = new ArrayList();
                    addrs.add(serverAddress);
                    // 认证用的用户名和密码直接写到代码中有很大的安全风险,建议在配置文件或者环境变量中存放(密码应密文存放、使用时解密),确保安全;
                    // 本示例以用户名和密码保存在环境变量中为例,运行本示例前请先在本地环境中设置环境变量(环境变量名称请根据自身情况进行设置)EXAMPLE_USERNAME_ENV和EXAMPLE_PASSWORD_ENV。
                    String userName = System.getenv("EXAMPLE_USERNAME_ENV");
                    String rwuserPassword = System.getenv("EXAMPLE_PASSWORD_ENV");
                    MongoCredential credential = MongoCredential.createScramSha1Credential("rwuser", "admin", rwuserPassword.toCharArray());
                    List credentials = new ArrayList();
                    credentials.add(credential);
                    MongoClientOptions opts= MongoClientOptions.builder()
                    .sslEnabled(true)
                    .sslInvalidHostNameAllowed(true)
                    .build();
                    MongoClient mongoClient = new MongoClient(addrs,credentials,opts);
                    MongoDatabase mongoDatabase = mongoClient.getDatabase("testdb");
                    MongoCollection collection = mongoDatabase.getCollection("testCollection");
                    Document document = new Document("title", "MongoDB").
                    append("description", "database").
                    append("likes", 100).
                    append("by", "Fly");
                    List documents = new ArrayList();
                    documents.add(document);
                    collection.insertMany(documents);
                    System.out.println("Connect to database successfully");
                    } catch (Exception e) {
                    System.err.println( e.getClass().getName() + ": " + e.getMessage() );
               }
            }
      }

      样例代码:

      javac -cp .:mongo-java-driver-3.2.0.jar MongoDBJDBC.java
      java -cp .:mongo-java-driver-3.2.0.jar MongoDBJDBC
    • SSL关闭
      import java.util.ArrayList;
      import java.util.List;
      import org.bson.Document;
      import com.mongodb.MongoClient;
      import com.mongodb.MongoCredential;
      import com.mongodb.ServerAddress;
      import com.mongodb.client.MongoDatabase;
      import com.mongodb.client.MongoCollection;
      import com.mongodb.MongoClientURI;
      import com.mongodb.MongoClientOptions;
      public class MongoDBJDBC {
      public static void main(String[] args){
            try {
                    ServerAddress serverAddress = new ServerAddress("ip", port);
                    List addrs = new ArrayList();
                    addrs.add(serverAddress);
                    // 认证用的用户名和密码直接写到代码中有很大的安全风险,建议在配置文件或者环境变量中存放(密码应密文存放、使用时解密),确保安全;
                    // 本示例以用户名和密码保存在环境变量中为例,运行本示例前请先在本地环境中设置环境变量(环境变量名称请根据自身情况进行设置)EXAMPLE_USERNAME_ENV和EXAMPLE_PASSWORD_ENV。
                    String userName = System.getenv("EXAMPLE_USERNAME_ENV");
                    String rwuserPassword = System.getenv("EXAMPLE_PASSWORD_ENV");
                    MongoCredential credential = MongoCredential.createScramSha1Credential("rwuser", "admin", rwuserPassword.toCharArray());
                    List credentials = new ArrayList();
                    credentials.add(credential);
                    MongoClient mongoClient = new MongoClient(addrs,credentials);
                    MongoDatabase mongoDatabase = mongoClient.getDatabase("testdb");
                    MongoCollection collection = mongoDatabase.getCollection("testCollection");
                    Document document = new Document("title", "MongoDB").
                    append("description", "database").
                    append("likes", 100).
                    append("by", "Fly");
                    List documents = new ArrayList();
                    documents.add(document);
                    collection.insertMany(documents);
                    System.out.println("Connect to database successfully");
                    } catch (Exception e) {
                    System.err.println( e.getClass().getName() + ": " + e.getMessage() );
               }
              }
      }
support.huaweicloud.com/bestpractice-dds/dds_0002.html