Overview
このページには、 Java Reactive Streamsアプリケーションをさまざまな設定でMongoDBに接続する方法を示すコード例が含まれています。
Tip
このページの接続オプションの詳細については、各セクションに記載されているリンクを参照してください。
このページの接続例を使用するには、コード例をサンプル アプリケーションまたは独自のアプリケーションにコピーします。 <Atlas
connection string>
など、コード例にあるすべてのプレースホルダーを、MongoDB 配置に関連する値に置き換えてください。
重要
プロジェクトリ アクター ライブラリ
This guide uses the Project Reactor library to consume Publisher
instances returned by the Java Reactive Streams driver methods. To learn more about the Project Reactor library and how to use it, see Getting Started in the Reactor documentation. To learn more about how we use Project Reactor library methods in this guide, see the Write Data to MongoDB guide.
次のサンプルアプリケーションを使用して、このページのコード例をテストできます。 サンプル アプリケーションを使用するには、次の手順を実行します。
IDE で新しいJavaプロジェクトを作成します。
Java Reactive Streams ドライバーをJavaプロジェクトにインストールします。
Project Reactive ライブラリをJavaプロジェクトにインストールします。
次のコードをコピーし、
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
インスタンスに接続できます。
次のコードに示すように、 接続stringでホスト名とポートを指定します。
MongoClient mongoClient = MongoClients.create( "mongodb://<hostname>:<port>" ); 次のコードに示すように、
mongos
がlocalhost:27017
で実行中されている場合は、接続stringを除外します。MongoClient mongoClient = MongoClients.create();
次の方法で複数のmongos
インスタンスに接続できます。
次のコードに示すように、ホスト名とポートを含むように接続stringを指定します。
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());
重要
The Java Reactive Streams driver does not support UnixServerAddress objects or domain socket connections. To use a domain socket to connect, use the Java Sync driver. Otherwise, use a ServerAddress object to connect from the Java Reactive Streams driver.
接続オプション
接続stringと MongoClientSettings
のいずれかを使用して接続設定を指定できます。
例、次のコードに示すように、 接続stringで 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);
場合によっては、次のコードに示すように、接続stringとプログラムによる構成を組み合わせる必要がある場合があります。
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);