我正在使用远程 MongoDB 并将其与我的 Spring boot 应用程序连接。如果我在 application.properties 文件中定义 spring.data.mongodb.uri 以及用户名和密码,应用程序可以正常工作。 类似的东西
spring.data.mongodb.uri = mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[database][?options]]
我想将编码后的网址保留在我的 application.property 文件中,然后在使用前对其进行解码。 我正在使用 MongoOperations 来查询 mongoDB。
我尝试在 Configuration 类中创建 MongoDBTemplate,但它抛出了
com.mongodb.MongoSocketReadException: Prematurely reached end of stream
这是代码
package com.expensemanagement.base;
import java.util.Arrays;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoDbFactory;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
@Configuration
public class AppConfig {
@Bean
public MongoTemplate mongoTemplate() throws Exception {
char[] password2 = "XXXX".toCharArray();
MongoCredential credential2 = MongoCredential.createCredential("XXXX", "MongoDB",password2);
MongoClient mongoClient = new MongoClient(new ServerAddress("XXX-XXX-XX-XX-XXX.mongodb.net",27017), Arrays.asList(credential2));
MongoDbFactory mongoDbFactory = new SimpleMongoDbFactory(mongoClient, "MongoDB");
return new MongoTemplate(mongoDbFactory);
}
}
最佳答案
我在 How to connect to MongoDB 3.2 in Java with username and password? 得到了答案
我在 application.property 文件中添加了自定义属性,然后在 AppConfig 类中创建了 MongoClient 对象,如下所示。
@Configuration
public class AppConfig {
@Value("${mongo.url}")
private String url;
@Value("${application.key}")
private String secretKey;
private MongoClient mongoClient;
@Bean
public MongoClient mongoClient()
{
String decrptedUrl = DecryptionService.decrypt(url, secretKey);
MongoClientURI connectionString = new MongoClientURI(decrptedUrl);
if (this.mongoClient == null) {
this.mongoClient = new MongoClient(connectionString);
}
return mongoClient;
}
}
关于java - com.mongodb.MongoSocketReadException : Prematurely reached end of stream,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48979191/