【问题标题】:com.mongodb.MongoSocketReadException: Prematurely reached end of streamcom.mongodb.MongoSocketReadException:过早到达流的末尾
【发布时间】:2018-08-05 08:38:02
【问题描述】:

我正在使用远程 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 文件中保留编码的 url,然后想在使用前对其进行解码。 我正在使用 MongoOperations 来查询 mongoDB。

我尝试在 Configuration 类中创建 MongoDBTemplate,但它正在抛出

com.mongodb.MongoSocketReadException:过早到达结束 流

这是代码

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);

    }

}

【问题讨论】:

标签: java spring mongodb spring-boot


【解决方案1】:

我在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;
    }
    }

【讨论】:

    【解决方案2】:

    这在 Spring Boot 中使用基于云的 mongo(集群实例)对我有用。

    像这样编辑 application.properties:

    spring.data.mongodb.uri = mongodb+srv://username:password@solarsystem-1tpu0.mongodb.net/dbname
    

    对于常规 mongo 实例(非集群),请使用:

    spring.data.mongodb.uri = mongodb://username:password@solarsystem-shard-00-00-1tpu0.mongodb.net:27017,hostname2:27017/dbname?ssl=true
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-12
      • 1970-01-01
      • 2016-12-29
      • 1970-01-01
      相关资源
      最近更新 更多