BAEL-5369: Checking Connection to MongoDB (#12057)

This commit is contained in:
Kapil Khandelwal 2022-04-13 05:56:26 +05:30 committed by GitHub
parent 266c908abf
commit 2c72a1e42c
2 changed files with 93 additions and 0 deletions

View File

@ -0,0 +1,46 @@
package com.baeldung;
import com.mongodb.DB;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions;
import com.mongodb.ServerAddress;
public class ConnectionCheck {
public static void checkingConnection() {
MongoClientOptions.Builder builder = MongoClientOptions.builder();
builder.connectionsPerHost(100);
builder.maxWaitTime(60000);
builder.connectTimeout(1500);
builder.socketTimeout(60000);
builder.socketKeepAlive(true);
ServerAddress ServerAddress = new ServerAddress("localhost", 27017);
MongoClient mongoClient = new MongoClient(ServerAddress, builder.build());
try {
System.out.println("MongoDB Server is Up:- " + mongoClient.getAddress());
DB db = mongoClient.getDB("baeldung");
System.out.println(mongoClient.getConnectPoint());
System.out.println(db.getStats());
} catch (Exception e) {
System.out.println("MongoDB Server is Down");
mongoClient.close();
}
}
public static void main(String[] args) {
//
// Connection check
//
checkingConnection();
}
}

View File

@ -0,0 +1,47 @@
package com.baeldung.mongo;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import java.io.IOException;
import org.junit.BeforeClass;
import org.junit.Test;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions;
import com.mongodb.ServerAddress;
public class ConnectionCheckLiveTest {
private static MongoClient mongoClient;
private static MongoClientOptions.Builder builder;
private static ServerAddress ServerAddress;
@BeforeClass
public static void setup() throws IOException {
if (mongoClient == null) {
builder = MongoClientOptions.builder();
builder.connectionsPerHost(100);
builder.maxWaitTime(60000);
builder.connectTimeout(1500);
builder.socketTimeout(60000);
builder.socketKeepAlive(true);
ServerAddress = new ServerAddress("localhost", 27017);
mongoClient = new MongoClient(ServerAddress, builder.build());
}
}
@Test
public void givenMongoClient_whenConnectionCheck_thenCheckingForConnectionPoint() {
String connectionPoint = mongoClient.getConnectPoint();
assertNotNull(connectionPoint);
assertFalse(connectionPoint.isEmpty());
}
}