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).
Related
I'm using Azure Cosmos DB 4.0 with MongoDB C# Driver 2.10.4.
Most of the times the queries work fine, but I'm getting intermittent errors like this:
MongoDB.Driver.MongoConnectionException: An exception occurred while sending a message to the server.
System.IO.IOException: Unable to write data to the transport connection: An existing connection was forcibly closed by the remote host.
System.Net.Sockets.SocketException: An existing connection was forcibly closed by the remote host
at System.Net.Sockets.Socket.BeginSend(...
at System.Net.Sockets.NetworkStream.BeginWrite
--- End of inner exception stack trace ---
at System.Net.Sockets.NetworkStream.BeginWrite
at System.Net.Security._SslStream.StartWriting
at System.Net.Security._SslStream.ProcessWrite
at System.Net.Security._SslStream.BeginWrite
When that error happens the call takes 10-25 seconds before failing.
I'm building the MongoClient with new MongoClient(MongoClientSettings.FromConnectionString(cnstr)) and I was using the connectionstring with these arguments ?ssl=true&replicaSet=globaldb&retrywrites=false.
I tried with retryWrites=true (as per Azure Support suggestion) but that didn't help.
I tried different settings and that didn't work either (connect=direct, maxIdleTimeMS=30000, serverSelectionTimeout=5000ms, socketTimeout=10000ms).
What's causing those exceptions?
The fix was to set/force TLS 1.2 (based on this Microsoft document):
//return new MongoClient(connectionString);
var settings = MongoClientSettings.FromConnectionString(connectionString);
settings.SslSettings = new SslSettings()
{
EnabledSslProtocols = System.Security.Authentication.SslProtocols.Tls12
};
return new MongoClient(settings);
Looks like although my connection string had ssl=true, it wasn't enough to work on some servers (the error is intermittent). The same underlying error can usually be fixed by forcing TLS 1.2 so I assumed that in Mongo it could be the same issue - and it really fixed the problem.
I'm currently working on a simple python CRUD script to check MongoDB out. Turns out I'm liking it a lot, but I have found myself being unable to work with MongoDB transactions. Everytime I try to start a transaction an exception is thrown saying:
This MongoDB deployment does not support retryable writes. Please add retryWrites=false to your connection string.
And, eventhough I've already added that option to my connection string:
self._client = MongoClient('mongodb://localhost/?retryWrites=false')
self._db = self._client.workouts
self._collection = self._db.workouts
That error is still popping up when running the following lines of code:
with self._client.start_session() as s:
with s.start_transaction():
self._collection.delete_one({'_id': id}, session=s)
next = self._collection.find_one({'_id': next_id}, session=s)
return next
What can I do?
I'm running python 3.7.3, pymongo 3.9.0 and MongoDB 4.0.12.
I've a simple data structure (the Transaction referenced below) to be inserted into mongodb:
{"amount":111,"debitAcc":"588188286231743e7d5c923d","type":"CHARGE"}
An I got the following error stackļ¼
com.mongodb.MongoSocketReadException: Prematurely reached end of stream
at com.mongodb.connection.SocketStream.read(SocketStream.java:88)
at com.mongodb.connection.InternalStreamConnection.receiveResponseBuffers(InternalStreamConnection.java:494)
at com.mongodb.connection.InternalStreamConnection.receiveMessage(InternalStreamConnection.java:224)
at com.mongodb.connection.UsageTrackingInternalConnection.receiveMessage(UsageTrackingInternalConnection.java:96)
at com.mongodb.connection.DefaultConnectionPool$PooledConnection.receiveMessage(DefaultConnectionPool.java:440)
at com.mongodb.connection.WriteCommandProtocol.receiveMessage(WriteCommandProtocol.java:262)
at com.mongodb.connection.WriteCommandProtocol.execute(WriteCommandProtocol.java:104)
at com.mongodb.connection.InsertCommandProtocol.execute(InsertCommandProtocol.java:67)
at com.mongodb.connection.InsertCommandProtocol.execute(InsertCommandProtocol.java:37)
at com.mongodb.connection.DefaultServer$DefaultServerProtocolExecutor.execute(DefaultServer.java:168)
at com.mongodb.connection.DefaultServerConnection.executeProtocol(DefaultServerConnection.java:289)
at com.mongodb.connection.DefaultServerConnection.insertCommand(DefaultServerConnection.java:118)
at com.mongodb.operation.InsertOperation.executeCommandProtocol(InsertOperation.java:76)
at com.mongodb.operation.BaseWriteOperation$1.call(BaseWriteOperation.java:139)
at com.mongodb.operation.BaseWriteOperation$1.call(BaseWriteOperation.java:133)
at com.mongodb.operation.OperationHelper.withConnectionSource(OperationHelper.java:422)
at com.mongodb.operation.OperationHelper.withConnection(OperationHelper.java:413)
at com.mongodb.operation.BaseWriteOperation.execute(BaseWriteOperation.java:133)
at com.mongodb.operation.BaseWriteOperation.execute(BaseWriteOperation.java:60)
at com.mongodb.Mongo.execute(Mongo.java:845)
at com.mongodb.Mongo$2.execute(Mongo.java:828)
at com.mongodb.DBCollection.executeWriteOperation(DBCollection.java:342)
at com.mongodb.DBCollection.insert(DBCollection.java:337)
at com.mongodb.DBCollection.insert(DBCollection.java:328)
at org.mongodb.morphia.DatastoreImpl.saveDocument(DatastoreImpl.java:1297)
at org.mongodb.morphia.DatastoreImpl.tryVersionedUpdate(DatastoreImpl.java:1340)
at org.mongodb.morphia.DatastoreImpl.save(DatastoreImpl.java:1286)
at org.mongodb.morphia.DatastoreImpl.save(DatastoreImpl.java:775)
at org.mongodb.morphia.DatastoreImpl.save(DatastoreImpl.java:758)
My mongodb version is 3.4.2.
Intereting is that I don't have the issue on my local dev environment (mint linux 18.1). But it just can't work on my SIT environment, which is a ubuntu 16.04
Any idea?
Updates with code to insert the document
Where transactionDao.save(...) implementation could be found at:
https://github.com/actframework/act-morphia/blob/master/src/main/java/act/db/morphia/MorphiaDaoBase.java#L206
update 2
The system works with other writes (even with much bigger records)
Most of the time this is a result of timeouts with long reads\writes.
try to increase the timeouts or remove them completely:
MongoClientOptions.Builder options_builder = new MongoClientOptions.Builder();
options_builder.maxConnectionIdleTime(<some_long_time>);
MongoClientOptions options = options_builder.build();
MongoClient mongo_db = new MongoClient ("your.db.address", options);
I don't have the root cause, but in the end I get the issue fixed by changing a field type from BigDecimal to double.
The issue is found in our SIT environmet and one developer's windows environment which has a mongodb cluser setup.
The most likely reason is the compatibility version is set too low.
Try db.adminCommand( { setFeatureCompatibilityVersion: "3.4" } )
https://docs.mongodb.com/manual/reference/command/setFeatureCompatibilityVersion/
Is it possible to connect to a remote MongoDB when using Jongo (jongo.org)?
I saw a piece of code where MongoClientURI was used like this:
MongoClientURI uri = new MongoClientURI("mongodb://IP_ADDRESS:27017/DB_NAME");
I have the following code:
if(client != null) {
db = client.getDatabase("StockApp");
database = client.getDB("StockApp");
jongo = new Jongo(database);
}
In this example, StockApp is the name of my database. It will connect to my local database (127.0.0.1:27017/StockApp). When I try to change StockApp to uri.getDatabase() in both lines, I get the following exception:
com.mongodb.MongoSocketOpenException: Exception opening socket
I can also see that it tries to connect to localhost (127.0.0.1).
When I change the uri to new MongoClientURI("IP_ADDRESS") or new MongoClientURI("IP_ADDRESS:27017) I get the error that the uri should start with mongodb://
Does anyone know if it is possible to connect to a remote MongoDB server using Jongo?
You can initialize Jongo from a MongoClient like this:
MongoClient mongoClient = new MongoClient("host", 27017);
DB db = mongoClient.getDB("theDB");
Jongo jongo = new Jongo(db);
You can check the MongoClient constructor detail here
I've come across a node chat example on github, When I try to run it, I see the following error:
Error connecting to mongo perhaps it isn't running ?
I've installed mongo 0.9.2, nodejs 5.2 pre, npm 3.0 and other dependencies. The example can be found here: https://github.com/gregstewart/chat.io
I can not determine whether if the example not really works or I didn't run it right. Please help.
Did you install and start mongo-db on your system? This error is mostly because of a missing mongo instance running on the local machine.
Check out the follwing code excerpts from chat.io.
main.js:
/**
* Configure the user provider (mongodB connection for user data storage)
*/
var userProvider = new UserProvider('localhost', 27017);
Creates a new UserProvider object using host and port for database (localhost:27017, mongo-db default).
UserProvider.js:
UserProvider = function(host, port) {
this.db = new mongo.Db('node-mongo-chat', new Server(host, port, {auto_reconnect: true}, {}));
this.db.addListener('error', function(error) {
console.log('Error connecting to mongo -- perhaps it isn\'t running?');
});
this.db.open(function() {
});
};
Opening the connection to the server, printing out an error on failure (the error you mentioned above).
Consider reading up on the mongo-db docs concerning installation and setup here