Things I Have tried:
InetAddress address = InetAddress.getByName("MyPCName");
MongoClientOptions.Builder builder = MongoClientOptions.builder().connectTimeout(3000);
MongoClient mongo = new MongoClient(new ServerAddress(address.getHostAddress(), 3001), builder.build());
try {
mongo.getAddress();
} catch (Exception e) {
System.out.println("Mongo is down");
mongo.close();
}
Second try:
InetAddress address = InetAddress.getByName("MyPCName");
MongoClientURI uri = new MongoClientURI( "mongodb://"+address.getHostAddress()+":27017/"+TEST_SKETCH_APP );
MongoClient instance = MongoDatabaseConnection.getInstance(uri);
try {
instance .getAddress();
} catch (Exception e) {
System.out.println("Mongo is down");
instance .close();
}
FireWall configured properly :
netsh advfirewall firewall add rule name="Allowing mongod" dir=in action=allow program=" C:\Program Files\MongoDB\Server\3.2\bin\mongod.exe"
But Still when I try to connect to do an insert operation I get this error message :
Timed out after 3000 ms while waiting to connect. Client view of cluster state is {type=Unknown, servers=[{address=192.168.138.1:3001, type=Unknown, state=Connecting}]
I am doing the save operation in an AsyncTask. My mongo db server is running in the "MyPCName" computer. My Mongodb config has bind ip commented too. And I have also tried the bind Ip to keep this bind_ip = 127.0.0.1,***.***.***.*,0.0.0.0
The '*' mark is the ip address which I get when I do a address.getHostAddress().
I am now stuck here.
Try this code:
MongoClientURI mongoUri = new MongoClientURI("mongodb://Dbuser:dbpass#ds047692.mongolab.com:47692");
MongoClient mongoClient = new MongoClient(mongoUri);
DB db = mongoClient.getDB("testdb");
Set<String> collectionNames = db.getCollectionNames();
In addition, you should check this answer: https://stackoverflow.com/a/21555200/4810206.
Related
Hi all i am new to spring maven project, and i am using MongoDB. I want to use two tomcats/ MongoDB both of theri IP address are different. when first DB is down i need to connect with second one how it is possible
I am using following code
public boolean mongoRunningAt(String uri) {
try {
Mongo mongo = new Mongo(new MongoURI(uri));
try {
Socket socket = mongo.getMongoOptions().socketFactory.createSocket();
socket.connect(mongo.getAddress().getSocketAddress());
socket.close();
} catch (IOException ex) {
mongo = new Mongo(new MongoURI(uri_second));
Socket socket = mongo.getMongoOptions().socketFactory.createSocket();
socket.connect(mongo.getAddress().getSocketAddress());
socket.close();
//return false;
}
mongo.close();
return true;
} catch (UnknownHostException e) {
return false;
}
}
Using this code i tried with first one successfully connected, now stoped first DB now restarted server it is connected with second db.
But if i didn't restart server it is always pointing to First only... how should i work on this
Thanks in advance
You deployed 2 servers, are they in a replica set. If not you can follow the link.
When they are already in a replica set you can use a connectionstring containing the 2 servers.
Like this:
mongodb://db1.example.net,db2.example.net:2500/?replicaSet=test
I have a simple database on my computer for testing purposed, and I'm trying to retrieve some information from the database, from my laptop. So I want my laptop to make a request to see the information inside my computers MySQL database. Below shows the java code I'm trying to run on my laptop to collect the first entry in the students table, which is located on my computer.
I have MySQL workbench installed on both my laptop and computer, is it necessary to be on both machines if the computer will store the data and the laptop only extracts data.
What I've learnt so far from researching is that the public ip should be used in the url instead of the ip for the computer, so I added that in but I received a CommunicationsException along with "Connection timed out" in the stack trace. I've read through this answer and this answer to a similar problem, but I'm having difficulty understanding both solutions, could someone refer me to a beginners guide to remotely accessing data from a database using MySQL.
public class TestRemote{
//JDBC variables
Connection connection;
Statement statement;
ResultSet resultSet;
//String variables
String url;
String user;
String password;
public static void main(String[] args) {
TestRemote sql = new TestRemote();
ArrayList<String> firstnames = sql.getColumn("students", "firstname", "studentid=4");
System.out.println(firstnames.get(0));
}
// Constructor
public TestRemote()
{
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
System.out.println("couldnt find class");
}
url = "jdbc:mysql://81.159.3.167:3306/test"; //?autoReconnect=true&useSSL=false";
user = "user";
password = "pass123";
connection = null;
statement = null;
resultSet = null;
}
private void closeConnection(){
try{
if(connection != null)
connection.close();
if(statement != null)
statement.close();
if(resultSet != null)
resultSet.close();
connection=null; resultSet=null; statement=null;
}catch(Exception e){
e.printStackTrace();
}
}
public ArrayList<String> getColumn(String table, String column, String where) {
ArrayList<String> resultsArray = new ArrayList<String>();
try {
connection = DriverManager.getConnection(url, user, password);
statement = connection.createStatement();
if(!where.equals(""))
resultSet = statement.executeQuery("SELECT "+column+" FROM "+table + " WHERE "+where);
else
resultSet = statement.executeQuery("SELECT "+column+" FROM "+table);
while(resultSet.next()) {
String val = resultSet.getString(1);
if(val==null)
resultsArray.add("");
else
resultsArray.add(val);
}
//resultsArray = (ArrayList<String>) resultSet.getArray(column);
} catch (SQLException ex) {
Logger lgr = Logger.getLogger(Model.class.getName());
lgr.log(Level.SEVERE, ex.getMessage(), ex);
}
closeConnection();
return resultsArray;
}
}
Your Java code is probably fine. But the question is, is on the other machine a MySQL server running and listening on port 3306 on the public IP? By default it should only listen on localhost, so you need to change your MySQL installation so that it listens to the public IP. Also make sure that no Firewall is blocking the access. Try connecting with the Workbench on the Laptop to reach the MySQL server on the other box. If you got this running, try your Java code again.
I have MySQL workbench installed on both my laptop and computer, is it
necessary to be on both machines if the computer will store the data
and the laptop only extracts data.
No what you call the "Computer" is your server here. it doesn't need mysql workbench. it only needs mysql server
the public ip should be used in the url instead of the ip for the
computer
A database should almost never be exposed on the public IP address. If you are having both computers on the LAN, the private network IP is what the server should listen on and that's what you should use on the connection string.
CommunicationsException along with "Connection timed out" in the stack
trace
Because the server is not running, not listening on that ip:port or firewalled to drop packets.
I've been searching for hours, and I can't find out why this isn't working, could you give me a hand guys? I'm trying to implement mongodb on my project, it seems to connect all right, but when I try to modify/access something on it, it gives me this "Mongo Timeout Exception".
try {
MongoCredential credential = MongoCredential.createCredential(USER, DATABASE, PASSWORD.toCharArray());
MongoClient mongoClient = new MongoClient(new ServerAddress(HOST), Arrays.asList(credential));
DB database = mongoClient.getDB(DATABASE);
DBCollection collection = database.getCollection(COLLECTION);
DBCursor cursor = collection.find();
cursor.next();
System.out.println("Success!");
} catch(Exception ex) { ex.printStackTrace(); }
com.mongodb.MongoTimeoutException: Timed out after 10000 ms while waiting to connect. Client view of cluster state is {type=Unknown, servers=[{address=104.236.68.242:27017, type=Unknown, state=Connecting}]
at com.mongodb.BaseCluster.getDescription(BaseCluster.java:128)
at com.mongodb.DBTCPConnector.getClusterDescription(DBTCPConnector.java:394)
at com.mongodb.DBTCPConnector.getType(DBTCPConnector.java:571)
at com.mongodb.DBTCPConnector.isMongosConnection(DBTCPConnector.java:368)
at com.mongodb.Mongo.isMongosConnection(Mongo.java:622)
at com.mongodb.DBCursor._check(DBCursor.java:494)
at com.mongodb.DBCursor._next(DBCursor.java:551)
at com.mongodb.DBCursor.next(DBCursor.java:701)
at net.Heiden.DB.Testing.main(Testing.java:29)
Any Help is apreciated.
Thanks ^^
I'm looking for best way to check connection to Mongo DB.
Situation: client makes request (api) to server. And server returns status of all databases.
What the best way to do it?
I use this:
Builder o = MongoClientOptions.builder().connectTimeout(3000);
MongoClient mongo = new MongoClient(new ServerAddress("192.168.0.1", 3001), o.build());
try {
mongo.getAddress();
} catch (Exception e) {
System.out.println("Mongo is down");
mongo.close();
return;
}
In Java MongoDriver 3.3.0 use ServerMonitorListener to determine whether server is up and connected or not.
Here is the example code,
public class ServerConnection implements ServerMonitorListener {
private MongoClient client;
public ServerConnection(){
try {
MongoClientOptions clientOptions = new MongoClientOptions.Builder()
.addServerMonitorListener(this)
.build();
client = new MongoClient(new ServerAddress("localhost", 27017), clientOptions);
} catch (Exception ex) {
}
}
#Override
public void serverHearbeatStarted(ServerHeartbeatStartedEvent serverHeartbeatStartedEvent) {
// Ping Started
}
#Override
public void serverHeartbeatSucceeded(ServerHeartbeatSucceededEvent serverHeartbeatSucceededEvent) {
// Ping Succeed, Connected to server
}
#Override
public void serverHeartbeatFailed(ServerHeartbeatFailedEvent serverHeartbeatFailedEvent) {
// Ping failed, server down or connection lost
}
}
The ping command is a no-op used to test whether a server is responding to commands. This command will return immediately even if the server is write-locked:
try{
DBObject ping = new BasicDBObject("ping", "1");
mongoTemplate.getDb().getMongo().getDB("DATABASE NAME"").command(ping);
} catch (Exception exp){
// MongoDb is down..
}
Use MongoClient for Java, all the info you need is here...
http://docs.mongodb.org/ecosystem/tutorial/getting-started-with-java-driver/
If I understand your question correctly you want to get state returned via a web service call. You can write a function that invokes db.serverStatus() and have it return the data. Check out the documentation here:
Monitoring for MongoDB
I'm trying to use MongoDB in a Java Web Service.
As suggested in Mongo tutorial I should have a MongoClient, let it be dbInstance, connection pool and call dbinstance to get a connection to the database, which is in localhost.
So this is what I have:
private static MongoClient dbInstance = null;
public static DB getDBInstance() {
if (dbInstance == null) {
try {
dbInstance = new MongoClient();
registerShutdownHook();
}
catch (Exception exc) {
System.out.println("Exception");
}
}
return dbInstance.getDB("SAED");
}
What I don't understand is how I can understand if I'm connected to the DB, because, also il mongo isn't working (by starting mongod service) it doesn't throw exceptions.
And another question, I have multiple thread calling Class.getDBInstance, should I synchronize it, and if yes, how can I do that?
You will be thrown an exception when the mongo is not running while you try to connect.
When you do the MongoClient(), it will always look for in the localhost for port 27017 to connect. You can also parameterize this to connect to a different machine and/or port.
You can read more in depth details about this at Mongo Documentation.
MongoClient mongoClient = new MongoClient();
// or
MongoClient mongoClient = new MongoClient( "localhost" );
// or
MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
Regarding your synchronization question,
Yes, you can synchronize at a block level to make it better instead of at the method level.