Step 1 : Create an Amazon EC2 Instance
This EC2 instance is for ssh tunneling to aws documentDB cluster and application running locally.
- On the Amazon EC2 console, choose Launch instance.
- Locate Amazon AMI and choose Select.
- Choose the t2.micro instance type.
- Choose Review and Launch
- Under Security Groups, choose Edit security groups.
- Configure Security groups for testing purpose , allow all traffic
- Verify the information and choose Launch.
- A window will pop up titled Select an existing key pair or create a new key pair. It will look like this: This key pair will help in ssh tunneling
You must provide an Amazon EC2 key pair. If you do have an Amazon EC2 key pair:- Select a key pair, choose your key pair from the list.
- You must already have the private key file (.pem file) available to log in to your Amazon EC2 instance.
- If you do not have an Amazon EC2 key pair:
- Choose Create a new key pair.
- Write a name for the key bar in the field Key pair name.
- Download the private key file (.pem file). You need this file later when you log in to your Amazon EC2 instance.
- Choose Launch Instances.
- After downloading the key pair change the permissions of key pair
By using cmd: chmod 400 keypair-name :- Gives the user read permission, and removes all other permission.

Step 2 : Create an Amazon DocumentDB Cluster
- Navigate to the Amazon DocumentDB console and choose Clusters from the navigation pane.
- Choose Create.
- For Number of instances, choose 1. This will minimize cost. Leave other settings at their default.
- For Authentication, enter a username and password. Important: You will need this username and password to authenticate your cluster in a later step.
- Turn on Show advanced settings.
- In the Network settings section, for Amazon VPC security groups, choose demoDocDB. This security groups must same as we made in instance
- Choose Create cluster.



Step 3 : Create a Java application with the Axon framework for Event-Sourcing.(Aws DocumentDB as event store)
When connecting to a TLS-enabled Amazon DocumentDB cluster from a Java application, your program must use the AWS-provided certificate authority (CA) file to validate the connection. To use the Amazon RDS CA certificate, do the following:
- Download the Amazon RDS CA file from https://s3.amazonaws.com/rds-downloads/rds-combined-ca-bundle.pem .
- Create a trust store with the CA certificate contained in the file by performing the following commands. Be sure to change the <truststorePassword> to something else. If you are accessing a trust store that contains both the old CA certificate (rds-ca-2015-root.pem) and the new CA certificate (rds-ca-2019-root.pem), you can import the certificate bundle into the trust store.
The following is a sample shell script that imports the certificate bundle into a trust store.
Shell script
mydir=/tmp/certs
truststore=${mydir}/rds-truststore.jks
storepassword=<truststorePassword>
curl -sS “https://s3.amazonaws.com/rds-downloads/rds-combined-ca-bundle.pem” > ${mydir}/rds-combined-ca-bundle.pem
awk ‘split_after == 1 {n++;split_after=0} /—–END CERTIFICATE—–/ {split_after=1}{print > “rds-ca-” n “.pem”}’ < ${mydir}/rds-combined-ca-bundle.pem
for CERT in rds-ca-*; do
alias=$(openssl x509 -noout -text -in $CERT | perl -ne ‘next unless /Subject:/; s/.*(CN=|CN = )//; print’)
echo “Importing $alias”
keytool -import -file ${CERT} -alias “${alias}” -storepass ${storepassword} -keystore ${truststore} -noprompt
rm $CERT
done
rm ${mydir}/rds-combined-ca-bundle.pem
echo “Trust store content is: “
keytool -list -v -keystore “$truststore” -storepass ${storepassword} | grep Alias | cut -d ” ” -f3- | while read alias
do
expiry=`keytool -list -v -keystore “$truststore” -storepass ${storepassword} -alias “${alias}” | grep Valid | perl -ne ‘if(/until: (.*?)\n/) { print “$1\n”; }’`
echo ” Certificate ${alias} expires in ‘$expiry'”
done
After implementation of the shell script, a certificate will be generated named as
rds-truststore.jks this certificate will help in ssh tunneling by setting the properties in the system by using function setProperty()
In main class :-
String truststore = “rds-truststore.jks”;
String truststorePassword = “truststorepassword”;
System.setProperty(“javax.net.ssl.trustStore”, truststore);
System.setProperty(“javax.net.ssl.trustStorePassword”, truststorePassword);
javax.net.ssl.trustStore – Location of the Java keystore file containing the collection of CA certificates trusted by this application process (trust store).
javax.net.ssl.trustStorePassword:- Containing password of keystore file
Axon configurations
package org.knoldus.engine.config;
import com.mongodb.ConnectionString;
import com.mongodb.MongoClientSettings;
import com.mongodb.MongoCredential;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import java.security.NoSuchAlgorithmException;
import javax.net.ssl.SSLContext;
import org.axonframework.eventsourcing.eventstore.EmbeddedEventStore;
import org.axonframework.eventsourcing.eventstore.EventStorageEngine;
import org.axonframework.eventsourcing.eventstore.EventStore;
import org.axonframework.extensions.mongo.DefaultMongoTemplate;
import org.axonframework.extensions.mongo.eventsourcing.eventstore.MongoEventStorageEngine;
import org.axonframework.serialization.json.JacksonSerializer;
import org.axonframework.spring.config.AxonConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* Configuring the Axon.
*/
@Configuration
public class AxonConfig {
/**
* Event store embedded event store.
*
* @param storageEngine the storage engine stores Aggregate Events
* @param configuration the Axon configuration defines a number of
* conditional beans.
* @return the embedded event store automatically fetches new events
*/
@Bean
public EmbeddedEventStore eventStore(
final EventStorageEngine storageEngine,
final AxonConfiguration configuration) {
return EmbeddedEventStore.builder()
.storageEngine(storageEngine)
.messageMonitor(configuration.messageMonitor(EventStore.class,
“eventStore”))
.build();
}
/**
* Storage engine event storage engine.
*
* @return the event storage engine stores Aggregate Events
* @throws NoSuchAlgorithmException
*/
@Bean
public EventStorageEngine storageEngine() throws NoSuchAlgorithmException {
String template = “mongodb://%s:%s@%s/admin?ssl=true&replicaSet=rs0&readpreference=%s”;
String username = “username”;
String password = “password”;
String clusterEndpoint = “127.0.0.1:27017”;
String readPreference = “secondaryPreferred”;
String connectionString = String.format(template, username, password,
clusterEndpoint, readPreference);
ConnectionString uri = new ConnectionString(connectionString);
MongoCredential credential = MongoCredential
.createCredential(username, “admin”, password.toCharArray());
SSLContext sslContext = SSLContext.getDefault();
MongoClientSettings settings = MongoClientSettings.builder().credential(credential)
.applyToSslSettings(builder -> {
builder.applyConnectionString(uri);
builder.enabled(true);
builder.invalidHostNameAllowed(true);
builder.context(sslContext);
})
.build();
final MongoClient mongoClient = MongoClients.create(settings);
return MongoEventStorageEngine.builder()
.mongoTemplate(DefaultMongoTemplate.builder()
.mongoDatabase(mongoClient).build())
.eventSerializer(JacksonSerializer.defaultSerializer())
.snapshotSerializer(JacksonSerializer.defaultSerializer())
.build();
}
}
Step 4 : Connect our documentdb cluster to our local machine
We can use the following cmd:-
ssh -i “ec2Access.pem” -L 27017:sample-cluster.node.us-east-1.docdb.amazonaws.com:27017 ubuntu@ec2-34-229-221-164.compute-1.amazonaws.com -N
Example:-
After the SSH tunnel is created, any commands that you issue to localhost:27017 are forwarded to the Amazon DocumentDB cluster sample-cluster running in the Amazon VPC.
Now , To connect to your Amazon DocumentDB cluster via mongo shell from outside the Amazon VPC, use the following command.



mongo –sslAllowInvalidHostnames –ssl –sslCAFile rds-combined-ca-bundle.pem –username <yourUsername> –password <yourPassword>
Example:-
Then Run application by using the following cmd:
mvn spring-boot:run



Conclusion
In this blog we learnt about that how we connect our application to documentdb


