I am using MongoDbFactory to connect to mongodb with Java. But the mongo service throws a socket exception at least once per hour. Therefore, I am forced to restart the mongodb service to restore operations. I think this may be the result of unclosed connections with mongodb from java, and also MongoDbFactory does not provide me with a function to close the connection. How can I make sure all connections are closed after a specific session.
This is the code I'm using:
package com.####.mongo.configuration; import com.mongodb.Mongo; import org.springframework.context.annotation.Bean; import org.springframework.data.mongodb.MongoDbFactory; import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.context.annotation.Configuration; import org.springframework.data.mongodb.core.SimpleMongoDbFactory; import org.springframework.data.mongodb.core.convert.DefaultMongoTypeMapper; import org.springframework.data.mongodb.core.convert.MappingMongoConverter; import org.springframework.data.mongodb.core.mapping.MongoMappingContext; @Configuration public class SpringMongoFeedConfig { public @Bean MongoDbFactory mongoDbFactory() throws Exception { return new SimpleMongoDbFactory(new Mongo(), "feedDatabase"); } public @Bean MongoTemplate mongoTemplate() throws Exception { MappingMongoConverter converter = new MappingMongoConverter(mongoDbFactory(), new MongoMappingContext()); converter.setTypeMapper(new DefaultMongoTypeMapper(null)); MongoTemplate mongoTemplate = new MongoTemplate(mongoDbFactory(), converter); return mongoTemplate; }
}
and
private String insertFeedsToMongo(FeedMongoDTO feedObject, FeedType type) throws UnknownHostException { try { ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringMongoFeedConfig.class); MongoOperations mongoOperation = (MongoOperations) ctx.getBean("mongoTemplate"); switch (type) { case FOLLOW: mongoOperation.save(feedObject, "feedsByUid"); break; case GENERAL: mongoOperation.save(feedObject, "allFeeds"); break; default: break; } return feedObject.getId(); } catch (Exception ex) { log.info("insertFeedsToMongo() : mongo Exception - ", ex); return null; } }
source share