如何通过OpenShift使用JAVA连接到MongoDB服务器?

问题描述:

我在OpenShift中创建了一个MongoDB实例.我可以通过RockMongo连接到它,这是OpenShift提供的服务.

I have created a MongoDB instance in OpenShift. I can connect to it via RockMongo, which is a service offered by OpenShift.

我正在尝试使用JAVA连接到我的实例,但是我只是收到一个Connection refuesed错误.而且,我无法使用RoboMongo进行连接.

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.

在我的RockMongo状态标签中,看到以下信息:

In my RockMongo status tab, I see the following information:

Host: 127.11.201.2
Port: 27017

RoboMongoMongoLab实例一起使用可以很好地为其提供正确的凭据,但是在OpenShift的情况下,它无法连接到该实例.

Using RoboMongo with MongoLab instance works just fine giving it the right credentials, but here with OpenShift it fails on connecting to the instance.

在我的JAVA应用中,我正在尝试以下操作:

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));

使用127.11.201.2作为MONGO_URI. 为什么我无法连接到我的实例?我在做什么错了?

With 127.11.201.2 as MONGO_URI. Why am I failing to connect to my instance? What am I doing wrong?

P.S我只需执行命令mongo就能连接到我的mongo实例.

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

OpenShift提供了环境变量,您应该使用它来连接到MongoDB.

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

  • OPENSHIFT_MONGODB_DB_HOST MongoDB IP地址
  • OPENSHIFT_MONGODB_DB_PORT MongoDB端口
  • OPENSHIFT_MONGODB_DB_USERNAME MongoDB用户名
  • OPENSHIFT_MONGODB_DB_PASSWORD MongoDB密码
  • OPENSHIFT_MONGODB_DB_URL MongoDB连接URL(例如mongodb://<username>:<password>@<hostname>:<port>/)
  • 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")));