首页 > 解决方案 > MongoSocketReadException:过早到达流的末尾,同时通过 Spring Boot 连接 MongoDB Atlas

问题描述

我正在使用 MongoDB 地图集(集群)连接到我的 Spring Boot 应用程序。我之前能够成功地插入并从集群中获取数据,但是在几分钟不活动后,我开始得到,

com.mongodb.MongoSocketReadException: Prematurely reached the end of stream. 我尝试在 mongodb 集群 URI 中进行一些更改,例如:

spring.data.mongodb.uri=mongodb+srv://emuser:empassword@emp-mate-bzmeh.gcp.mongodb.net/emp-mate-db?retryWrites=true&retryReads=true&w=majority 也试过

spring.data.mongodb.uri=mongodb+srv://emuser:empassword@emp-mate-bzmeh.gcp.mongodb.net/emp-mate-db?ssl=true&retryWrites=true&retryReads=true&w=majority&maxIdleTimeMS=80

我还检查了 JRE 中的 SSL 设置及其正常,并且在 MongoDB 集群的警报部分中也没有看到任何错误日志。下面是我使用过的代码片段 MongoTemplate

import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import com.mongodb.client.result.UpdateResult;
import employeemate.repository.UsersRepository;
import employeemate.resources.Users;

    @Service
    public class UserService {
        @Autowired
        MongoTemplate mongoTemplate;
        @Autowired
        UsersRepository usersRepository;

        public void addSampleData() {
             System.out.println("Adding sample data");
             usersRepository.save(new Users("1","Ashu","test@gmail.com", 24, "Male", "1111111111", "Delhi"));
             usersRepository.save(new Users("2","Adam Clark", "adam@gmail.com",24,"Male", "2222222222", "Shelton CT"));

             }
        }

POM.xml

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>

标签: javamongodbspring-bootspring-data-mongodb

解决方案


除了maxIdleTimeMS,尝试keepAlive手动设置一个值。

另外,请参阅此相关问题中的解决方案。


推荐阅读