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:[email protected]/emp-mate-db?retryWrites=true&retryReads=true&w=majority
and also tried
spring.data.mongodb.uri=mongodb+srv://emuser:[email protected]/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","[email protected]", 24, "Male", "1111111111", "Delhi"));
usersRepository.save(new Users("2","Adam Clark", "[email protected]",24,"Male", "2222222222", "Shelton CT"));
}
}
POM.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>