I am using MongoDB URI (mongodb://user:pass#IP:27017/myDB?retryWrites=false&connectTimeoutMS=10000) configuration in Spring-boot. I observed approx every 5 min. Mongodb not responding for first hit, Second hit working fine.
Some time getting this message "Opened connection [connectionId{localValue:8}]" in log.
Java Configuration.
#Bean
public MongoDbFactory mongoDbFactory() {
return new SimpleMongoDbFactory(new MongoClientURI(prop.getDbConnectionUri()));
}
#Bean
public MongoTemplate mongoTemplate() {
log.info("Loging MongoDB Config Loging...");
MongoTemplate mongoTemplate = new MongoTemplate(mongoDbFactory());
return mongoTemplate;
}
Please suggest any other optional configuration required in Mongo URI.
After so many Changes,I fixed this problem by changing below system configuration. This is not related to mongo configuration.
Open sysctl.conf by using "sudo vim /etc/sysctl.conf" command.
Change "net.ipv4.tcp_keepalive_time = 220".
Save Changes.
Run "sysctl --system" command.
And Restart your micro service.
Now Mongo Connection working fine.
Related
We have a spring boot application (2.2.2) which uses mongodb. As we want to deploy it in AWS we need to migrate to DocumentDB. But when we migrate, things which were working in MongoDB are no longer working. See the following code:
public int getCount(String collection, List<Bson> pipeline, MongoTemplate mongoTemplate) {
List<Bson> newpipeline = new ArrayList<Bson>();
newpipeline.addAll(pipeline);
String cntStr = "{$group:{_id:null, val:{'$sum':1}}}";
newpipeline.add(BasicDBObject.parse(cntStr));
MongoDatabase mongo = mongoTemplate.getDb();
int count = 0;
try {
count = mongo.getCollection(collection).aggregate(newpipeline).first().getInteger("val");
} catch (NullPointerException e) {
} catch (Exception e) {
e.printStackTrace();
}
return count;
}
This works in mongodb, but not in documentdb.Gives error like:
{"timestamp":"2021-03-29T08:29:58.101+0000","status":500,"error":"Internal Server Error","message":"Command failed with error 18537: 'Could not convert date to string: date component was outside the supported range of 0-9999: 10000' on server xxxx-manager-document-db.cn30hpxqos6b.eu-central-1.docdb.amazonaws.com:27017. The full response is {\"ok\": 0.0, \"operationTime\": {\"$timestamp\": {\"t\": 1617006598, \"i\": 1}}, \"code\": 18537, \"errmsg\": \"Could not convert date to string: date component was outside the supported range of 0-9999: 10000\"}","path":"/pmt/api/v1/pm/analytics/getKpiByDimension"}
Is it possible that some of the cursor apis do not work in documentDB?
Another option that you have is to install MongoDB on an EC2 instance then you can use the MongoDB API within a Spring BOOT Application. To learn how to install MongoDB on EC2, see:
Install and configure MongoDB community edition
There is an example of creating a Spring BOOT app that uses MongoDB to store application data here.
Creating the MongoDB web application item tracker
Looking for some proper documentation on async commit for mongo db . We have a spring boot app where we are trying to generate audits for our domain objects , we would like to commit the audits generated by javers into mongo db asynchronously while our main SQL based transaction is fr of this mongodb call. Any pointers on this would be really helpful.
If you are using the Javers Spring Boot Mongo starter, you can simply put the #JaversAuditableAsync ann on a repository method.
There are limitations:
It works only with Mongo and there is no integration for magical-autogenerated ReactiveMongoRepository yet. So you have to put the #JaversAuditableAsync on an actual method which does the save.
#Repository
interface DummyObjectReactiveRepository
extends ReactiveMongoRepository<DummyObject, String> { }
...
#Repository
class MyRepository {
#Autowired DummyObjectReactiveRepository dummyObjectReactiveRepository;
#JaversAuditableAsync
void save(DummyObject d){
dummyObjectReactiveRepository.save(d)
}
}
In my spring boot application i have configured two databases in my yml file. So now I want to specify which database is to use in each MongoRepository. Is this possible? If so, how to do it? Thanks in advance.
yml file :
spring:
data:
mongodb:
first:
host: 127.0.0.1
port: 27017
database: db_admin
rest:
base-path: /admin
second:
host: 127.0.0.1
port: 27018
database: `user_forms`
rest:
base-path: /users
So in User MongoRepository i want to use the user_forms database.
The user MongoRepository :
#RepositoryRestResource(collectionResourceRel = "users",path = "users")
public interface UserRepository extends MongoRepository<User, String> {
List<User> findByUserId(String id);
}
Spring Boot auto configuration provides a default MongoTemplate to facilitate generating MongoDB Repositories.
Nevertheless if you want to use multi MongoDB databases, you would need to
register MongoTemplates for every MongoDB databases
designate each of the MongoTemplates to base packages of MongoRepositories accordingly, so that Spring Data MongoDB is informed to use the right template when generating repositories.
For example, say you registered 2 MongoTemplates, namely templateAdmin and templateUser, configured explicitly to their MongoDB. Then you could use code like this to inform Spring Data MongoDB which repositories use which template:
#EnableMongoRepositories(
basePackages = "com.the.base.package.name.of.admin.repositories",
mongoTemplateRef = "adminTemplateBeanName")
#Configuration
public class AdminMongoConfig {
#Bean
public MongoTemplate adminTemplateBeanName() {
//...
}
}
Configure Multiple MongoDB repositories with Spring Data Mongo Basically explained almost all points what I have said. So my wild guess is that you may have a misconception that MongoTemplate is irrelevant to MongoRepository, which is not the case.
Adding an answer despite having marked the question as a duplicate, as there is some confusion whether MongoRepository uses MongoTemplate.
When you inject your MongoRepository, it is proxied by an instance of SimpleMongoRepository class. it has a field
private final MongoOperations mongoOperations;
MongoOperations is an interface, and MongoTemplate is its implementation.
Now, the question is where does this default mongo template come from in a Spring Boot application.
Look at MongoDataAutoConfiguration
#Bean
#ConditionalOnMissingBean
public MongoTemplate mongoTemplate(MongoDbFactory mongoDbFactory,
MongoConverter converter) {
return new MongoTemplate(mongoDbFactory, converter);
}
Therefore, I am still claiming it is a duplicate of: Configure Multiple MongoDB repositories with Spring Data Mongo
I am trying to connect MongoDB using MongoClientURI(URL) my URL is mongodb://userName:Password#host:PortNumber/DBName?connectTimeoutMS=10000
when my MongoDB is Down i try to Post Request but it take default time 30 sec.
Can any one help me solve the problem
Thanks in Advance.
You can set timeouts by using the Mongo Java client's MongoClientOptions. For example:
MongoClientOptions clientOptions = MongoClientOptions.builder()
.connectTimeout(...)
.socketTimeout(...)
.serverSelectionTimeout(...)
.build();
MongoClient mongoClient = new MongoClient(new ServerAddress(host, port), clientOptions);
Examining mongoClient.getMongoClientOptions() after the above line of code clearly shows that the created client is faithful to the supplied config values. By contrast, if you do not set these values via MongoClientOptions then mongoClient.getMongoClientOptions() shows that the default values have been chosen.
Based on your updated comments I think the situation you are trying to cater for is this:
Creating a connection against a server instance which does not exists / is unavailable should fail sooner that the default of 30s.
If so then the configuration parameter you want to use is serverSelectionTimeout. The following invocation ...
MongoClientOptions clientOptions = MongoClientOptions.builder()
.serverSelectionTimeout(2000)
.build();
MongoClient mongoClient = new MongoClient(new ServerAddress(host, port), clientOptions);
... will cause this exception to be thrown:
com.mongodb.MongoTimeoutException: Timed out after 2000 ms while waiting to connect.
Note: serverSelectionTimeout is available in the version of the MongoDB Java driver which you are using (3.2.2 according to the comment you posted on your question).
I have a springboot app that connects to PostgreDB.
here is the datasource bean
#Bean
public DriverManagerDataSource createDataSourceBean(Environment env) {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("org.postgresql.Driver");
dataSource.setUrl("jdbc:postgresql://localhost:5432/postgres");
dataSource.setUsername("postgres");
dataSource.setPassword("<myspassword>");
return dataSource;
}
This works fine, but I wonder why even if I try to disconnect the database server via pgAdmin and then run the app my app still works. I believe I should encounter an exception when dbserver is disconnected.
I'm sure there's something weird happening . . .