我正在尝试在Dropwizard应用程序中执行以下操作:
public void run(SandmanConfiguration configuration, Environment environment) {
MongoClient mongoClient = configuration.getMongoFactory().build(environment);
environment.lifecycle().manage(mongoClient);
}
这引用了MongoFactory的构建方法:
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;
}
当我尝试以这种方式使用mongoClient时,我得到一个错误:
environment.lifecycle().manage(mongoClient);
Cannot resolve method 'manage(com.mongodb.MongoClient)
答案 0 :(得分:1)
我刚才发现最好是创建一个单独的调用来实现mongo客户端的启动和停止。
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();
}
}
这样我可以在应用程序停止时安全地关闭客户端。