连接到 MongoDB
概述
本页包含代码示例,展示了如何使用各种设置将您的Java反应式流应用程序连接到MongoDB。
提示
要了解更多关于本页上的连接选项,请参阅每个部分提供的链接。
要使用本页上的连接示例,请将代码示例复制到示例应用程序或您自己的应用程序中。请确保将代码示例中的所有占位符(如<Atlas连接字符串>
)替换为MongoDB部署的相关值。
重要
项目反应器库
本指南使用项目反应器库来消费Java反应式流驱动程序方法返回的发布者
实例。要了解更多关于项目反应器库及其使用方法,请参阅Reactor文档中的入门指南。要了解更多关于本指南中如何使用项目反应器库方法,请参阅将数据写入MongoDB指南。将数据写入MongoDB指南。
您可以使用以下示例应用程序来测试本页上的代码示例。要使用示例应用程序,请执行以下步骤
在您的IDE中创建一个新的Java项目。
在您的Java项目中安装Java反应式流驱动程序。
在您的Java项目中安装Project Reactor库。
复制以下代码,并将其粘贴到一个名为
ConnectionApp.java
的新Java文件中。从本页面复制代码示例,并将其粘贴到文件中的指定行。
1 import com.mongodb.ConnectionString; 2 import com.mongodb.MongoClientSettings; 3 import com.mongodb.ServerApi; 4 import com.mongodb.ServerApiVersion; 5 6 import org.bson.BsonDocument; 7 import org.bson.BsonInt64; 8 import org.bson.Document; 9 10 import com.mongodb.reactivestreams.client.MongoClient; 11 import com.mongodb.reactivestreams.client.MongoClients; 12 import com.mongodb.reactivestreams.client.MongoDatabase; 13 import org.bson.conversions.Bson; 14 import reactor.core.publisher.Mono; 15 16 class ConnectionApp { 17 public static void main(String[] args) { 18 //start example code here 19 20 //end example code here 21 { 22 Bson command = new BsonDocument("ping", new BsonInt64(1)); 23 MongoDatabase database = mongoClient.getDatabase("admin"); 24 Publisher<Document> MonoPublisher = database.runCommand(command); 25 26 Mono.from(MonoPublisher) 27 .doOnSuccess(x -> System.out.println("Pinged your deployment. You successfully connected to MongoDB!")) 28 .doOnError(err -> System.out.println("Error: " + err.getMessage())) 29 .block(); 30 31 //other application code 32 33 } 34 } 35 }
连接
本地部署
String uri = "mongodb://<hostname>:<port>/"; try (MongoClient mongoClient = MongoClients.create(uri))
Atlas
String uri = "<Atlas connection string>"; ServerApi serverApi = ServerApi.builder() .version(ServerApiVersion.V1) .build(); MongoClientSettings settings = MongoClientSettings.builder() .applyConnectionString(new ConnectionString(uri)) .serverApi(serverApi) .build(); try (MongoClient mongoClient = MongoClients.create(settings))
副本集
String uri = "mongodb://<replica set member>:<port>/?replicaSet=<replica set name>"; try (MongoClient mongoClient = MongoClients.create(uri))
分片集群
要连接到分片集群,请指定 mongos
实例或实例到 MongoClients.create()
方法。有关分片集群的更多信息,请参阅服务器手册中的 分片。
您可以通过以下方式连接到单个 mongos
实例
在连接字符串中指定主机名和端口号,如下所示
MongoClient mongoClient = MongoClients.create( "mongodb://<hostname>:<port>" ); 如果
mongos
在localhost:27017
上运行,则排除连接字符串,如下所示MongoClient mongoClient = MongoClients.create();
您可以通过以下方式连接到多个 mongos
实例
在连接字符串中指定它们的主机名和端口号,如下所示
MongoClient mongoClient = MongoClients.create("mongodb://<first hostname>:<first port>,<second hostname>:<second port>"); 指定对应每个实例的
ServerAddress
对象列表,如下所示MongoClient mongoClient = MongoClients.create( MongoClientSettings.builder() .applyToClusterSettings(builder -> builder.hosts(Arrays.asList( new ServerAddress("<first hostname>", <first port>), new ServerAddress("<second hostname", <second port>)))) .build());
连接选项
您可以使用连接字符串或MongoClientSettings
类型来指定连接设置,也可以同时使用两者。
例如,您可以在连接字符串中指定TLS/SSL和身份验证设置,如下所示
MongoClient mongoClient = MongoClients.create("mongodb://user1:pwd1@host1/?authSource=db1&ssl=true");
您还可以使用一个MongoClientSettings
实例来指定TLS/SSL,并使用MongoCredential
类型来存储身份验证信息,如下所示
String user; // the username String database; // the name of the database in which the user is defined char[] password; // the password as a character array // ... MongoCredential credential = MongoCredential.createCredential(user, database, password); MongoClientSettings settings = MongoClientSettings.builder() .credential(credential) .applyToSslSettings(builder -> builder.enabled(true)) .applyToClusterSettings(builder -> builder.hosts(Arrays.asList(new ServerAddress("host1", 27017)))) .build(); MongoClient mongoClient = MongoClients.create(settings);
在某些情况下,您可能需要结合连接字符串和程序配置,如下所示
ConnectionString connectionString = new ConnectionString("mongodb://host1:27107,host2:27017/?ssl=true"); CommandListener myCommandListener = ...; MongoClientSettings settings = MongoClientSettings.builder() .addCommandListener(myCommandListener) .applyConnectionString(connectionString) .build(); MongoClient mongoClient = MongoClients.create(settings);