简体   繁体   中英

How to use io.dropwizard.lifecycle.Managed with com.mongodb.MongoClient?

I am trying to do the following in a Dropwizard app:

 public void run(SandmanConfiguration configuration, Environment environment) {
   MongoClient mongoClient = configuration.getMongoFactory().build(environment);
   environment.lifecycle().manage(mongoClient);
  }

This references the MongoFactory's build method:

public MongoClient build(Environment environment) {
        // Example conn string: "mongodb://db1.example.net,db2.example.net:2500/?replicaSet=test"
        MongoClient mongoClient = new MongoClient(getHost(), getPort());
        environment.lifecycle().manage(new Managed() {
            @Override
            public void start() {
            }
            @Override
            public void stop() {
                LOGGER.info("Mongo Client is being shut down...");
                mongoClient.close();
            }
        });
        return mongoClient;
    }

How ever when i try to use mongoClient this way I get an error:

environment.lifecycle().manage(mongoClient);
Cannot resolve method 'manage(com.mongodb.MongoClient)

I just figured out that the best is to create a separate call that implements start and stop for the mongo client.

import com.mongodb.MongoClient;
import io.dropwizard.lifecycle.Managed;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class MongoClientManager implements Managed {
    private static final Logger LOGGER = LoggerFactory.getLogger(MongoClientManager.class);
    private final MongoClient client;

    public MongoClientManager(MongoClient client) {
        this.client = client;
    }

    @Override
    public void start() throws Exception {
        LOGGER.info("MongoClient is starting up...");
    }

    @Override
    public void stop() throws Exception {
        LOGGER.info("MongoClient is being shut down...");
        client.close();
    }
}

This way I can safely shut down the client when the app is stopping.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM