MongoSocketReadException: Prematurely reached end of stream (after a period of inactivity) MongoSocketReadException: Prematurely reached end of stream (after a period of inactivity) mongodb mongodb

MongoSocketReadException: Prematurely reached end of stream (after a period of inactivity)


I found it in some documentation:

For long running applications, it is often prudent to enable "keepAlive" with a number of milliseconds. Without it, after some period of time you may start to see "connection closed" errors for what seems like no reason.

Check if this helps. When you connect to mongoDB you can pass socket options to it. I am from node background we use following options to keep it alive.

server: {        socketOptions: {            keepAlive: 100,            connectTimeoutMS: 30000        }    }

Hope this helps!!


I solve this problem by set sslEnabled to true,code sampleļ¼š

@Beanpublic MongoClient mongoClient() {    List<ServerAddress> saList = new ArrayList<>();    saList.add(new ServerAddress("cluster0-shard-00-00-75shm.gcp.mongodb.net", 27017));    saList.add(new ServerAddress("cluster0-shard-00-01-75shm.gcp.mongodb.net", 27017));    saList.add(new ServerAddress("cluster0-shard-00-02-75shm.gcp.mongodb.net", 27017));    char[] pwd =  "password".toCharArray();    MongoCredential credential = MongoCredential.createCredential("username", "admin", pwd);    //set sslEnabled to true here    MongoClientOptions options = MongoClientOptions.builder()            .readPreference(ReadPreference.primaryPreferred())            .retryWrites(true)            .requiredReplicaSetName("Cluster0-shard-0")            .maxConnectionIdleTime(6000)            .sslEnabled(true)            .build();    MongoClient mongoClient = new MongoClient(saList, credential, options);         return mongoClient;}

Addition: my client jar is org.mongodb.mongodb-driver 3.6.4,server is mongodb atlas M0 3.6.6 on GCP


This worked for me in spring boot and cloud based mongo (Atlas clustered instances).

Edit application.properties like this:

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

For regular mongo instances (non-clustered) use this:

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