gpt4 book ai didi

java - 有没有办法检查mongoDB连接的正确性?

转载 作者:行者123 更新时间:2023-11-30 01:50:39 26 4
gpt4 key购买 nike

在我的 spring boot 应用程序中,我使用 spring-boot-starter-data-mongodb:2.1.3 来获取 MongoDB 的连接。我有一些属性文件来配置 mongoDB:

 spring.data.mongodb.host=localhost
spring.data.mongodb.port=27017
spring.data.mongodb.database=database

如果我设置了不正确的主机名(spring.data.mongodb.host=不正确的主机)或端口,我的应用程序将成功启动。但我希望该应用程序失败,就像我设置错误格式的主机名一样 (spring.data.mongodb.host=hxxt://wrongFormat)

Caused by: com.mongodb.MongoException: host and port should be specified in host:port format

我怎样才能做到这一点?

示例:

应用程序属性

 #Wrong host
spring.data.mongodb.host=www.google.com
spring.data.mongodb.port=27017
spring.data.mongodb.database=database

DemoApplication.java:

 @SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}

配置.java:

@Configuration
public class Config {
@Bean
public CommandLineRunner commandLineRunner(JobRepository jobRepository ){
return args -> jobRepository.findById("1");
}
}

JobRepository.java:

  public interface JobRepository extends MongoRepository<Job, String> {}

作业.java:

  @Getter
@Setter
@EqualsAndHashCode
@NoArgsConstructor
@Document(collection = "Jobs")
public class Job {
@Id
private String id = null;
private String field;
}

最佳答案

您的问题是 mongo 上的连接检查是异步发生的。因此,如果输入正确,则 bean 均由 spring boot 创建,稍后连接会失败。您可以通过定义一个在启动时检查连接的 bean 来强制它爆炸。例如,我使用这个:

/**
* This is a testing bean. It is only here to explode when the database is not available.
* This is to counter act default spring boot behaviour where the Mongo configuration
* will connect to a localhost DB regardless of whether it exists or not.
*
*/
public class MongoDatabaseVerifier {
private static final Logger log = LoggerFactory.getLogger(MongoDatabaseVerifier.class);

public MongoDatabaseVerifier(MongoClient mongoClient) {
checkConnectionOrThrow(mongoClient);
}

/**
* Calls {@link MongoClient#getAddress()} and throws the result away if successful
* @param client
*/
void checkConnectionOrThrow(MongoClient client) {
client.getAddress(); // this will either succeed super fast or explode
log.info("Database fully started ...");
}
}

由于该 bean 在创建时进行检查,因此 spring 仅在成功时才会继续启动。否则,将抛出 Bean 创建异常并中止启动。

希望对您有帮助

关于java - 有没有办法检查mongoDB连接的正确性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56183731/

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