简体   繁体   中英

How can I connect to MongoDB server using JAVA from OpenShift?

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?

PS using putty I am able to connect to my mongo instance by just executing the command mongo .

OpenShift provides environment variables , which you should use to connect to your MongoDB.

  • OPENSHIFT_MONGODB_DB_HOST The MongoDB IP address
  • OPENSHIFT_MONGODB_DB_PORT The MongoDB port
  • OPENSHIFT_MONGODB_DB_USERNAME The MongoDB username
  • OPENSHIFT_MONGODB_DB_PASSWORD The MongoDB password
  • OPENSHIFT_MONGODB_DB_URL The MongoDB connection URL (eg 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")));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM