开发者

MongoDB java connection issues [duplicate]

开发者 https://www.devze.com 2023-03-03 19:17 出处:网络
This question already has answers here: 开发者_如何学运维 Java Networking "Connection Refused: Connect"
This question already has answers here: 开发者_如何学运维 Java Networking "Connection Refused: Connect" (5 answers) Closed 2 years ago.

I am trying to run the following code:

public static void main(String args[]) throws UnknownHostException, MongoException{
        Mongo m = new Mongo( "localhost", 27017 );
        DB db = m.getDB( "test" );


        Set<String> coll = db.getCollectionNames();
    }

but for some reason I am getting connection issues :

bc:java.net.ConnectException: Connection refused: connect

EDIT: Nvm I forgot to run the database in the background


Obviously, make sure you can connect to MongoDB on "localhost" port 27017. You should be able to open the MongoDB shell with no arguments and get a prompt back:

» mongo
MongoDB shell version: 1.8.1
connecting to: test
> 

If you can't the answer should be obvious: MongoDB isn't running. You'll want to make sure you start up the MongoDB server process. There are some Quickstart Guides in the MongoDB Docs which should guide you to the process on your platform of choice.

Otherwise, you don't indicate what platform you are on but there is an issue with how Java resolves certain hostnames like "localhost" on Mac OS X... This is actually a Java issue rather than a MongoDB Java Driver issue.

When asked to resolve "localhost" from a hostname to an InetSocketAddr, Java for Mac will typically return the IP for your machine's external interface. As a few installers for Mac MongoDB like Homebrew lock the listening IP Address to 127.0.0.1, this can cause connecting to "localhost" to fail completely on Mac with Java.

0

精彩评论

暂无评论...
验证码 换一张
取 消