问题
I have created a MongoDB instance in OpenShift. I can connect to it via RockMongo, which is a service offered by OpenShift.
I'm trying to connect to my instance using JAVA, but I just receive a Connection refuesed error. Moreover, I cannot connect it using RoboMongo.
In my RockMongo status tab, I see the following information:
Host: 127.11.201.2
Port: 27017
Using RoboMongo with MongoLab instance works just fine giving it the right credentials, but here with OpenShift it fails on connecting to the instance.
In my JAVA app I'm trying the following:
MongoCredential credential = MongoCredential.createCredential(
Const.MONGO_USERNAME, Cont.MONGO_DB,
Const.MONGO_PASSWORD.toCharArray());
mongo = new MongoClient(new ServerAddress(Const.MONGO_URI), Arrays.asList(credential));
With 127.11.201.2 as MONGO_URI.
Why am I failing to connect to my instance? What am I doing wrong?
P.S using putty I am able to connect to my mongo instance by just executing the command mongo.
回答1:
OpenShift provides environment variables, which you should use to connect to your MongoDB.
OPENSHIFT_MONGODB_DB_HOSTThe MongoDB IP addressOPENSHIFT_MONGODB_DB_PORTThe MongoDB portOPENSHIFT_MONGODB_DB_USERNAMEThe MongoDB usernameOPENSHIFT_MONGODB_DB_PASSWORDThe MongoDB passwordOPENSHIFT_MONGODB_DB_URLThe MongoDB connection URL (e.g.mongodb://<username>:<password>@<hostname>:<port>/)
I'm using one line of code to connect to the database:
new MongoClient(new MongoClientURI(System.getenv("OPENSHIFT_MONGODB_DB_URL")));
来源:https://stackoverflow.com/questions/30128804/how-can-i-connect-to-mongodb-server-using-java-from-openshift