61 lines
1.9 KiB
Java
61 lines
1.9 KiB
Java
package eu.univento.commons.database;
|
|
|
|
import com.mongodb.MongoCredential;
|
|
import com.mongodb.ServerAddress;
|
|
import com.mongodb.async.client.MongoClient;
|
|
import com.mongodb.async.client.MongoClientSettings;
|
|
import com.mongodb.async.client.MongoClients;
|
|
import com.mongodb.async.client.MongoDatabase;
|
|
import com.mongodb.connection.ClusterSettings;
|
|
|
|
import java.util.ArrayList;
|
|
import java.util.List;
|
|
|
|
/**
|
|
* @author joethei
|
|
* @version 0.1
|
|
*/
|
|
public class AsyncMongoDB {
|
|
|
|
private final MongoClient client;
|
|
private MongoDatabase database;
|
|
|
|
private final String host;
|
|
private final int port;
|
|
private final String username;
|
|
private final String password;
|
|
private final String databaseName;
|
|
|
|
public AsyncMongoDB(String host, int port, String username, String password, String databaseName) {
|
|
this.host = host;
|
|
this.port = port;
|
|
this.username = username;
|
|
this.password = password;
|
|
this.databaseName = databaseName;
|
|
|
|
List<ServerAddress> addressList = new ArrayList<>();
|
|
addressList.add(new ServerAddress(host, port));
|
|
List<MongoCredential> credentials = new ArrayList<>();
|
|
credentials.add(MongoCredential.createCredential(username, databaseName, password.toCharArray()));
|
|
ClusterSettings clusterSettings = ClusterSettings.builder().hosts(addressList).build();
|
|
MongoClientSettings settings = MongoClientSettings.builder().clusterSettings(clusterSettings).credentialList(credentials).build();
|
|
client = MongoClients.create(settings);
|
|
}
|
|
|
|
private MongoClient getClient() {
|
|
if(client == null)
|
|
new AsyncMongoDB(host, port, username, password, databaseName);
|
|
return client;
|
|
}
|
|
|
|
public MongoDatabase getDatabase() {
|
|
if(database == null)
|
|
database = getClient().getDatabase(databaseName);
|
|
return database;
|
|
}
|
|
|
|
public void closeConnection() {
|
|
if(client != null)
|
|
client.close();
|
|
}
|
|
} |