connect java app to mongoDB on openshift cloud - java

i'm trying to connect local java app to openshift MongoDB using this code
String mongoUri = "mongodb://admin:password#myServerIP:27017/";
MongoClient mongoClient;
mongoClient = new MongoClient(new MongoClientURI(mongoUri));
DB db = mongoClient.getDB("mongo");
System.out.println("Successfully connected to MongoDB ");
but it connect to local machine MongDB ? it give me this error ?
com.mongodb.MongoTimeoutException: Timed out after 10000 ms while waiting for a server that matches AnyServerSelector{}. Client view of cluster state is {type=Unknown, servers=[{address=remoteIpAddress:27017, type=Unknown, state=Connecting, exception={com.mongodb.MongoException$Network: Exception opening the socket}, caused by {java.net.ConnectException: Connection refused: connect}}]
i'm search and i found solution (port forward) but i can't do it , any one give me solution , thanks .

Related

Connecting to containerised MongoDB replica set with Docker results in "Canonical address ... does not match server address."

I am trying to connect to my local MongoDB replica set (configured via Docker Compose) via an application running on Quarkus, however I am getting the following logs as soon as I try to access the database via the application:
2022-01-25 13:18:30,299 INFO [org.mon.dri.cluster] (cluster-ClusterId{value='61efea96e5029b1a675a4312', description='null'}-mongo3:27023) Canonical address mongo3:27017 does not match server address. Removing mongo3:27023 from client view of cluster
2022-01-25 13:18:30,303 INFO [org.mon.dri.cluster] (cluster-ClusterId{value='61efea96e5029b1a675a4312', description='null'}-mongo2:27022) Canonical address mongo2:27017 does not match server address. Removing mongo2:27022 from client view of cluster
2022-01-25 13:18:30,306 INFO [org.mon.dri.cluster] (cluster-ClusterId{value='61efea96e5029b1a675a4312', description='null'}-mongo1:27021) Server mongo1:27021 is no longer a member of the replica set. Removing from client view of cluster.
Which eventually leads to a ConnectionException to be thrown and the following error log:
2022-01-25 13:18:35,304 ERROR [nl.rab.kno.int.LoggingInterceptor] (executor-thread-0) LoggingInterceptor.MethodCallEvent(className=nl.rabobank.knowledge.service.PreferencesService, methodName=getLanguagesForUser, result=EXCEPTION, exception=com.mongodb.MongoTimeoutException: Timed out after 5000 ms while waiting for a server that matches com.mongodb.client.internal.MongoClientDelegate$1#4fe08d8a. Client view of cluster state is {type=REPLICA_SET, servers=[{address=mongo3:27017, type=UNKNOWN, state=CONNECTING, exception={com.mongodb.MongoSocketOpenException: Exception opening socket}, caused by {java.net.ConnectException: Connection refused (Connection refused)}}, {address=mongo2:27017, type=UNKNOWN, state=CONNECTING, exception={com.mongodb.MongoSocketOpenException: Exception opening socket}, caused by {java.net.ConnectException: Connection refused (Connection refused)}}, {address=mongo1:27017, type=UNKNOWN, state=CONNECTING, exception={com.mongodb.MongoSocketOpenException: Exception opening socket}, caused by {java.net.ConnectException: Connection refused (Connection refused)}}])
For some reason it seems to automatically remove the node from the client view when the application tries to connect to the database for reading/retrieving data. I am wondering what goes wrong here?
I simply followed this guide for setting up a replica set in MongoDB with Docker Compose: https://blog.tericcabrel.com/mongodb-replica-set-docker-compose/. Note that the application is able to successfully connect to the database when I create a non-containerised replica set (as also explained in the same tutorial). I
therefore have the feeling that this issue is occurring due to something being misconfigured with my containerised setup.
This is the connection string that I am using in my Quarkus application:
quarkus:
mongodb:
connection-string: mongodb://mongo1:27021,mongo2:27022,mongo3:27023/database?replicaSet=dbrs
These are the dependencies used by my Quarkus application (version 2.6.2):
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-mongodb-client</artifactId>
</dependency>
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-mongodb-panache</artifactId>
</dependency>

Getting an error trying to connect to mongodb database on android

The error that I am getting is
com.mongodb.MongoTimeoutException: Timed out after 30000 ms while waiting to connect. Client view of cluster state is {type=UNKNOWN, servers=[{address=localhost:27017, type=UNKNOWN, state=CONNECTING, exception={com.mongodb.MongoSocketOpenException: Exception opening socket}, caused by {java.net.ConnectException: failed to connect to localhost/127.0.0.1 (port 27017) from /127.0.0.1 (port 43950) after 10000ms: isConnected failed: ECONNREFUSED (Connection refused)}, caused by {android.system.ErrnoException: isConnected failed: ECONNREFUSED (Connection refused)}}]
I'm assuming the issue here is that the AVD is using the same IP as my computer, but if I try to change it in the settings of the AVD it fails to connect to androidWifi. (I tried changing it to 10.0.2.2, because that's the solution I found on annother stackoverflow post, it didn't work.)
If it matters, my code looks like this:
MongoClient client = MongoClients.create("mongodb://localhost:27017");
MongoDatabase db = client.getDatabase("userData");
MongoCollection<Document> users = db.getCollection("users");
Document user = new Document("name", "user").append("password", "pass");
users.insertOne(user);
Adding this answer for posterity - the reason why this error occurs is because in the line:
MongoClient client = MongoClients.create("mongodb://localhost:27017");
the DB address is being set to the ANDROID'S localhost and NOT the PC's that's hosting the AVD. To fix this, find your ipv4 address using the command ipconfig
in CMD, then, when running the mongo shell type the following command: mongod --bind_ip "yourIPHere"
please do note, however that this will open your database up to external connections, if someone happens to have your internal IP address.

I cannot connect to Maria db it says socket fail all solutions I tried didn't work

java.sql.SQLNonTransientConnectionException: Could not connect to address=(host=localhost)(port=3306)(type=master) : Socket fail to connect to host:localhost, port:3306. Connection refused
tried: adding this bind-address = ::
tried changing from localhost too xxx.xx.xx.....
Help. thank you

How to connect to Atlas M0 (Free Tier) cluster correctly via Java driver?

Trying to connect Atlas cluster via Java driver using MongoDB version 3.6.
So, I'm writting like:
MongoClientURI uri = new MongoClientURI("mongodb+srv://admin:mypassword#cluster0-ox90k.mongodb.net/test?retryWrites=true");
MongoClient mongoClient = new MongoClient(uri);
In this case the error is:
java.lang.IllegalArgumentException: The connection string is invalid. Connection strings must start with 'mongodb://'
at com.mongodb.ConnectionString.<init>(ConnectionString.java:203)
at com.mongodb.MongoClientURI.<init>(MongoClientURI.java:176)
at com.mongodb.MongoClientURI.<init>(MongoClientURI.java:158)
at project.Bot.check(Bot.java:30)
at project.Bot.onUpdateReceived(Bot.java:104)
at java.util.ArrayList.forEach(ArrayList.java:1249)
at org.telegram.telegrambots.generics.LongPollingBot.onUpdatesReceived(LongPollingBot.java:27)
at org.telegram.telegrambots.updatesreceivers.DefaultBotSession$HandlerThread.run(DefaultBotSession.java:309)
When the program starts with snippet using MongoDB version 3.6 or later without +srv:
MongoClientURI uri = new MongoClientURI("mongodb://admin1:mypassword#cluster0-ox90k.mongodb.net/test?retryWrites=true");
MongoClient mongoClient = new MongoClient(uri);
I'm getting an error:
com.mongodb.MongoTimeoutException: Timed out after 30000 ms while waiting for a server that matches ReadPreferenceServerSelector{readPreference=primary}. Client view of cluster state is {type=UNKNOWN, servers=[{address=cluster0.mongodb.net:27017, type=UNKNOWN, state=CONNECTING, exception={com.mongodb.MongoSocketException: cluster0.mongodb.net}, caused by {java.net.UnknownHostException: cluster0.mongodb.net}}]
at com.mongodb.connection.BaseCluster.createTimeoutException(BaseCluster.java:369)
at com.mongodb.connection.BaseCluster.selectServer(BaseCluster.java:101)
at com.mongodb.binding.ClusterBinding$ClusterBindingConnectionSource.<init>(ClusterBinding.java:75)
at com.mongodb.binding.ClusterBinding$ClusterBindingConnectionSource.<init>(ClusterBinding.java:71)
at com.mongodb.binding.ClusterBinding.getReadConnectionSource(ClusterBinding.java:63)
at com.mongodb.operation.OperationHelper.withConnection(OperationHelper.java:201)
at com.mongodb.operation.CountOperation.execute(CountOperation.java:206)
at com.mongodb.operation.CountOperation.execute(CountOperation.java:53)
at com.mongodb.Mongo.execute(Mongo.java:772)
at com.mongodb.Mongo$2.execute(Mongo.java:759)
at com.mongodb.MongoCollectionImpl.count(MongoCollectionImpl.java:185)
at com.mongodb.MongoCollectionImpl.count(MongoCollectionImpl.java:170)
at project.Bot.check(Bot.java:36)
at project.Bot.onUpdateReceived(Bot.java:103)
at java.util.ArrayList.forEach(ArrayList.java:1249)
at org.telegram.telegrambots.generics.LongPollingBot.onUpdatesReceived(LongPollingBot.java:27)
at org.telegram.telegrambots.updatesreceivers.DefaultBotSession$HandlerThread.run(DefaultBotSession.java:309)
In POM file I have dependency:
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>3.6.0</version>
</dependency>
Also, when I'm starting mongo my database is added to this address mongodb://127.0.0.1:27017, but I added path to the cluster not for this. Maybe I need to write path to concrete cluster or?
Ofc, I have admin-user. In addition, I can connect via Compass to my cluster and from shell. mongod process is started. This error appears only, when I'm running in IDE. Same issue probably here.
Does anyone know how to solve this error? I appreciate any help.
Solved it!
So, what I've done:
I tried only to connect to tier cluster via driver3.6 and wrote
mongodb+srv://user:#cluster0-ox90k.mongodb.net/test?retryWrites=true
I always get an error: Connection strings must start with 'mongodb://'.
Okay, I deleted the snippet +srv and wrote the same way
mongodb://user:#cluster0-ox90k.mongodb.net/test?retryWrites=true
and get again the error:
com.mongodb.MongoTimeoutException: Timed out after 30000 ms while waiting for a server that matches ReadPreferenceServerSelector{readPreference=primary}. Client view of cluster state is {type=UNKNOWN, servers=[{address=cluster0-ox90k.mongodb.net:27017, type=UNKNOWN, state=CONNECTING, exception={com.mongodb.MongoSocketException: cluster0-ox90k.mongodb.net}, caused by {java.net.UnknownHostException: cluster0-ox90k.mongodb.net}}]
So, I wrote via driver3.4 or earlier like
mongodb://user:<PASSWORD>#cluster0-shard-00-00-ox90k.mongodb.net:27017,cluster0-shard-00-01-ox90k.mongodb.net:27017,cluster0-shard-00-02-ox90k.mongodb.net:27017/test?ssl=true&replicaSet=Cluster0-shard-0&authSource=admin&retryWrites=true
and finally it solved.
Note: You can get this connection string from the Atlas management console by setting your Java driver to '3.4 or later'. This will help you avoid having to come up with the connection string yourself.
Updated: if you want to use drivers 3.7+, you need to write instead of format connection (and to avoid my issues above)
MongoClientURI uri = new MongoClientURI("mongodb+srv://admin:mypassword#cluster0-ox90k.mongodb.net/test?retryWrites=true");
MongoClient mongoClient = new MongoClient(uri);
another variant using MongoClients.create() (as of the 3.7 release), and as mentioned here:
MongoClient mongoClient = MongoClients.create("mongodb+srv://admin:mypassword#cluster0-ox90k.mongodb.net/test?retryWrites=true");
Note: the password need to write not like mongodb://user:<mypassword>#...,
just in format mongodb://user:mypassword#...
without braces <>.
There seem to be a few issues here
First
3.6.0 is not the Mongo driver library that was actually loaded into your application classpath; I suspect that you were previously testing with an old version, and recently updated the POM? You were previously using version 3.2.0.
How do I know this?
I started digging through the code, and at version 3.6.0, the error message you provided is nowhere near line 203. And also, you can see that the above linked code has support for the +srv.
Browing back through previousl releases, I finally found that error massge on line 203, back at release 3.2.0.
Long story short, trying doing a Maven clean, and rebuild.
Relaunch Eclipse to pick up new dependencies if a project refresh does not help.
Second
MongoTimeoutException: Timed out after 30000 ms while waiting for a server
This one is highly likely a firewall / access control group configuration issue, in that the firewall is blocking the packets from reaching your Atlas cluster.
See adding addresses to the whitelist.
One more important note:
in this string:
MongoClientURI uri = new MongoClientURI("mongodb+srv://admin:mypassword#cluster0-ox90k.mongodb.net/test?retryWrites=true");
test ==> is a Db name, before making this connection, DB should exist.
The above-mentioned solution is not working in the current assignment, because I'm working on the Spring-boot framework assignment.
I have got error as Caused by: java.net.UnknownHostException: khweshacluster0.brzta.mongodb.net
To Solve this I have to take configurations from below
Take Highlighted URL
& make below format URL as
spring.data.mongodb.uri=mongodb://:#<Atlas_cluster_URL>
& same update in application.properties
as follows,
spring.data.mongodb.uri=mongodb://username:password#khweshacluster0-shard-00-00.brzta.mongodb.net:27017,khweshacluster0-shard-00-01.brzta.mongodb.net:27017,khweshacluster0-shard-00-02.brzta.mongodb.net:27017/myFirstDatabase?ssl=true&replicaSet=atlas-3b1nqz-shard-0&authSource=admin&retryWrites=true&w=majority
I faced same issue when trying to connect from my tomcat application to MongoDB.
I had tomcat 9.0 and MongoDB 4.2 installed with application using Mongo Driver 3.12.3
Error: org.springframework.dao.DataAccessResourceFailureException: Timed out after
30000 ms while waiting to connect. Client view of cluster state is {type=UNKNOWN,
servers=[{address=#127.0.0.1:27017, type=UNKNOWN, state=CONNECTING, exception=
{com.mongodb.MongoSocketException: #127.0.0.1}, caused by
{java.net.UnknownHostException: #127.0.0.1}}]; nested exception is
com.mongodb.MongoTimeoutException: Timed out after 30000 ms while waiting to connect.
Client view of cluster state is {type=UNKNOWN, servers=[{address=#127.0.0.1:27017,
type=UNKNOWN, state=CONNECTING, exception={com.mongodb.MongoSocketException:
#127.0.0.1}, caused by {java.net.UnknownHostException: #127.0.0.1}}]
I tried creating sample Java application to connect DB and it worked, however it was not able to connect from web application.
So created user for DB and assigned role userAdmin, which worked for me.
Not working Conn String - mongodb://#127.0.0.1:27017/docs <br>
Working Conn string - mongodb://docs_local:docs#127.0.0.1:27017/docs
i had this issue and i checked the documentation
i created a configuration class like this
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
#Configuration
public class AppConfig {
public #Bean
MongoClient mongoClient() {
return MongoClients.create("mongodb://localhost:27017");
}
}
you can put your uri where "mongodb://localhost:27017" is
https://docs.spring.io/spring-data/mongodb/docs/current/reference/html/#reference
I had the similar issue and solved it by selecting Node driver version 2.2.12 or later and it will give me a connection string starting with 'mongodb://'

Connect to Openshift Mongodb remotely with Java, timeout error

I have turn on the port-forward with rhc, it shows
mongodb 127.0.0.1:27017 => xxx.x.xxx.x:27017
doc here port-forward
but I still have no luck connect to that mongodb cartridge. I've try both mongo shell 3.0 and java MongoClient.
mongo shell return error 10061
java return com.mongodb.MongoTimeoutException: Timed out after 10000 ms while waiting for a server that matches AnyServerSelector{}
what else could I try to connect to openshift mongodb remotely?
my code, I've test this on local mongodb which works fine
String mongoUri = "mongodb://admin:password#xxx.x.xxx.x:27017/";
MongoClient mongoClient;
try {
mongoClient = new MongoClient(new MongoClientURI(mongoUri));
DB db = mongoClient.getDB("mycoll");
DBCollection cc = db.getCollection("DBObject");
cc.insert(dbo);
}
You should be using the following connection string locally while you have port forwarding enabled:
String mongoUri = "mongodb://admin:password#127.0.0.1:27017/";
Since the connection is being forwarded over an ssh tunnel, you need to use the local port. See this answer for more information: OpenShift: How to connect to postgresql from my PC

Categories

Resources