gpt4 book ai didi

java - 如何将 io.dropwizard.lifecycle.Managed 与 com.mongodb.MongoClient 一起使用?

转载 作者:行者123 更新时间:2023-12-01 09:44:11 30 4
gpt4 key购买 nike

我正在尝试在 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)

最佳答案

我刚刚发现最好的方法是创建一个单独的调用来实现 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();
}
}

这样我就可以在应用程序停止时安全地关闭客户端。

关于java - 如何将 io.dropwizard.lifecycle.Managed 与 com.mongodb.MongoClient 一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38202999/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com