1

I am using MongoDB atlas (cluster) to connect to my spring boot application. I was earlier able to successfully insert & get the data from the cluster but after few minutes of inactivity I started getting,

com.mongodb.MongoSocketReadException: Prematurely reached the end of stream. I tried to make some changes in the mongodb cluster URI such as:

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

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

I have also checked the SSL settings in JRE and its fine & I did not also see any error log in the Alert section on MongoDB cluster. Below is the snippet of the code where I have used 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>
Ashutosh dwivedi
  • 510
  • 3
  • 16

4 Answers4

2

One possibility is that in MongoDB Atlas you have (sensibly) restricted access to specific IP addresses, and the IP address of the machine you are connecting from has changed because it is set dynamically. If that's the case, you may have to add your IP address to your MongoDB Atlas account each time it changes, or set yourself up with a static IP address.

1

Along with maxIdleTimeMS, try setting a keepAlive value manually too.

Also, refer to solutions in this related question.

Bojan Krkic
  • 349
  • 3
  • 10
0

I got this error when i tried to connect to mongodb on atlas cluster from my springboot app. Adding allow access from anywhere (0.0.0.0/0) to network permission list fixed my issue.

helvete
  • 2,455
  • 13
  • 33
  • 37
Vishwa
  • 1
  • 2
0

Add your ip to the acl, it worked for me

enter image description here

Andrea Ciccotta
  • 598
  • 6
  • 16