Overview
このページには、 Java Reactive Streamsアプリケーションをさまざまな設定でMongoDBに接続する方法を示すコード例が含まれています。
Tip
このページの接続オプションの詳細については、各セクションに記載されているリンクを参照してください。
このページの接続例を使用するには、コード例をサンプルアプリケーションまたは独自のアプリケーションにコピーします。 <Atlas connection string>などのコード例にあるすべてのプレースホルダーを、MongoDB 配置に関連する値に置き換えてください。
重要
プロジェクトリ アクター ライブラリ
このガイドでは、プロジェクト Reactive ライブラリを使用して、 Java Reactive Streams ドライバー メソッドによって返された インスタンスを消費します。Project Reactive ライブラリとその使用方法の詳細については、React ドキュメントの 使用開始 を参照してください。Publisherプロジェクト Reactor ライブラリとその使用方法の詳細については、React ドキュメントの使用開始を参照してください。このガイドでプロジェクト Reactorライブラリのメソッドをどのように使用するかについて詳しく学ぶには、「ドキュメントの挿入」ガイドを参照してください。
次のサンプルアプリケーションを使用して、このページのコード例をテストできます。 サンプル アプリケーションを使用するには、次の手順を実行します。
IDE で新しいJavaプロジェクトを作成します。
Java Reactive Streams ドライバーをJavaプロジェクトにインストールします。
Project Reactive ライブラリをJavaプロジェクトにインストールします。
次のコードをコピーし、
ConnectionApp.javaという名前の新しいJavaファイルに貼り付けます。このページからコード例をコピーし、 ファイル内の指定された行に貼り付けます。
import com.mongodb.ConnectionString;import com.mongodb.MongoClientSettings;import com.mongodb.ServerApi;import com.mongodb.ServerApiVersion;
import org.bson.BsonDocument;import org.bson.BsonInt64;import org.bson.Document;
import com.mongodb.reactivestreams.client.MongoClient;import com.mongodb.reactivestreams.client.MongoClients;import com.mongodb.reactivestreams.client.MongoDatabase;import org.bson.conversions.Bson;import reactor.core.publisher.Mono;
class ConnectionApp { public static void main(String[] args) { //start example code here //end example code here { Bson command = new BsonDocument("ping", new BsonInt64(1)); MongoDatabase database = mongoClient.getDatabase("admin"); Publisher<Document> MonoPublisher = database.runCommand(command);
Mono.from(MonoPublisher) .doOnSuccess(x -> System.out.println("Pinged your deployment. You successfully connected to MongoDB!")) .doOnError(err -> System.out.println("Error: " + err.getMessage())) .block();
//other application code
} }}接続
ローカル配置
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());
重要
Java Reactive Streams ドライバーは UnixServerAddress オブジェクトまたは ドメイン ソケット接続をサポートしていません。ドメイン ソケットを使用して接続するには、Java Sync Driver を使用します。それ以外の場合は、ServerAddressオブジェクトを使用してJava Reactive Streams ドライバーから接続します。
接続オプション
接続stringと MongoClientSettings のいずれかを使用して接続設定を指定できます。
例、次のコードに示すように、 接続stringで TLS/SSL および認証設定を指定できます。
MongoClient mongoClient = MongoClients.create("mongodb://user1:pwd1@host1/?authSource=db1&ssl=true");次のコードに示すように、 MongoClientSettingsインスタンスを使用して TLS/SSL を指定し、 MongoCredentialタイプを使用して認証情報を保存することもできます。
String user; // the usernameString database; // the name of the database in which the user is definedchar[] 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);