blog.broncotoxique.com

Juste another geek’s website

Spring-Framework, JavaMelody and MongoTemplate

Let say you use Spring-Framework (without Spring-Boot), MongoTemplate and JavaMelody in the same app. I guess you will need to see the mongo request statistics in the Melody dashboard, like you see the SQL statistics.

First you might have followed the JavaMelody documentation to setup Melody into you app.

Let say you create your MongoTemplate Bean like that :

@Bean
public MongoTemplate template() {
  return new MongoTemplate(...);
}

If you wanna have the same type of bean creation with JavaMelody monitoring, you can do it like that following.

First you will need to Override the org.springframework.data.mongodb.MongoDatabaseFactory :

public class JavaMelodyMongoClientDatabaseFactory extends SimpleMongoClientDatabaseFactory {

  public JavaMelodyMongoClientDatabaseFactory(MongoClient mongoClient, String databaseName) {
    super(mongoClient, databaseName);
  }

  @Override
  public MongoDatabase getMongoDatabase() throws DataAccessException {
    MongoDatabase db = getMongoDatabase(getDefaultDatabaseName());
    return MongoWrapper.createDatabaseProxy(db); // JavaMelody Monitoring
  }
}

Then you modify your app configuration to wrap the mongo connection before creating the MongoTemplate :

@Bean
public MongoTemplate template() {
  String dbName = "dbName"; // Name of the DB linked to the Template
  return buildTemplate(dbName);
}

private MongoTemplate buildTemplate(String dbName) {
  MongoClient client = getMongoClient();
  JavaMelodyMongoClientDatabaseFactory dbf = new JavaMelodyMongoClientDatabaseFactory(client, dbName);
  return new MongoTemplate(dbf);
}

private MongoClient getMongoClient() {
  MongoCredential credential = MongoCredential.createScramSha256Credential(user, source, pass);
  ConnectionString uri = new ConnectionString("mongodb://[HOST]:[PORT]");
  MongoClientSettings settings = MongoClientSettings.builder().credential(credential).applyConnectionString(uri).build();
  return MongoClients.create(settings);
}

Posted

in

, ,

by

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *