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

可紊 提交于 2019-12-20 03:39:10

问题


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_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 (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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!