How can I connect to MongoDB server using JAVA fro

2020-04-17 07:04发布

问题:

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