Java
Connect a Java application to TeselaDB with the official MongoDB driver.
Connect a Java application to TeselaDB with the official MongoDB driver for Java. TeselaDB presents itself as a mongos, so the driver works unchanged.
Requirements
- Java 11 or later and Maven or Gradle.
- The address of one or more nodes, a user with
readWriteon the database and thepki/ca.pemfile of the cluster.
Install the driver
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongodb-driver-sync</artifactId>
<version><!-- the latest driver version --></version>
</dependency>Store the connection string
Put the string in an environment variable instead of writing it in the code:
export TESELADB_URI="mongodb://user:<password>@node-01:27017,node-02:27017/shop?tls=true"Add the CA to a trust store
The Java driver does not read tlsCAFile from the string. Put the cluster CA in a trust store with keytool and give
that store to the JVM, together with its password, in the javax.net.ssl.trustStore and
javax.net.ssl.trustStorePassword properties when you start your application:
keytool -importcert -alias teseladb -file ca.pem -keystore teseladb.jks -storepass <secret>
java -Djavax.net.ssl.trustStore=teseladb.jks -Djavax.net.ssl.trustStorePassword=<secret> -jar app.jarIn the connection string of your application keep only the tls=true option, without tlsCAFile.
Write and read a document
try (MongoClient client = MongoClients.create(System.getenv("TESELADB_URI"))) {
MongoCollection<Document> orders = client.getDatabase("shop").getCollection("orders");
orders.insertOne(new Document("total", 149.5));
System.out.println(orders.countDocuments());
}Check
The program prints the number of documents in orders, which grows by one each time you run it.
Common problems
- The connection closes before authenticating because
tls=trueis missing from the string. - The driver does not trust the node certificate because it does not have the CA of this cluster.