简体   繁体   English

使用java连接到远程mongodb服务器

[英]Connect to remote mongodb server with java

I'm trying to connect to a remote mongodb instance, but it keeps throwing an error.我正在尝试连接到远程 mongodb 实例,但它不断抛出错误。

Java code:爪哇代码:

Mongo mongo = new Mongo("172.234.52.24");
DB db = mongo.getDB("myDB");
collection = db.getCollection("myCollection");

But I keep getting the following exception:但我不断收到以下异常:

java.io.IOException: couldn't connect to [/172.234.52.24:27017] bc:java.net.ConnectException: Connection refused

Is there something else I have to do?还有什么我需要做的吗? Set username/password when I try to access the database or change some permissions on the mongo side?当我尝试访问数据库或更改 mongo 端的某些权限时设置用户名/密码? Its just the normal mongo install on a ubuntu server, no added configuration or permissions.它只是在 ubuntu 服务器上的普通 mongo 安装,没有添加配置或权限。

ADDITIONAL INFORMATION: mongo 172.234.52.24:8888 doesn't work either, says exception: connect failed.附加信息:mongo 172.234.52.24:8888 也不起作用,说异常:连接失败。 I can ping the other host, and know mongo is running on it.我可以 ping 另一台主机,并且知道 mongo 正在其上运行。

Any ideas?有任何想法吗? Thanks!谢谢!

I figured it out... y'all had great suggestions but the problem was more fundamental.我想通了……你们都有很好的建议,但问题更根本。

In my mongo configuration file on the remote server, there was a bind_ip variable set to the local ip.在远程服务器上的 mongo 配置文件中,有一个 bind_ip 变量设置为本地 ip。 Once I commented this out, everything worked properly.一旦我将其注释掉,一切正常。

Thank you all very much though!不过还是非常感谢大家!

Make sure you have added correct maven dependency in your pom.xml 1. spring-data-mongodb (1.5.2.RELEASE) 2. mongo-java-driver (2.13.0)确保在 pom.xml 中添加了正确的 maven 依赖项 1. spring-data-mongodb (1.5.2.RELEASE) 2. mongo-java-driver (2.13.0)

Just update your credential in following java code and it will work for you.只需在以下 java 代码中更新您的凭据,它就会为您工作。 "$external" in the below code represents that you are trying to connect database which is on Linux machine at remote location.以下代码中的“$external”表示您正在尝试连接位于远程位置的 Linux 机器上的数据库。

Below code is working in standalone Java program.下面的代码在独立的 Java 程序中工作。

String database = "TestDev";
    String username = "user@test.COM";
    String pass = "XXXXX";
    char[] password = pass.toCharArray();

    try {

        List<ServerAddress> serverAddresses = new ArrayList<ServerAddress>();
        ServerAddress address = new ServerAddress("hostname", portnumber);
        serverAddresses.add(address);
        List<MongoCredential> credentials = new ArrayList<MongoCredential>();
        MongoCredential credential = MongoCredential.createPlainCredential(username, "$external", password);
        credentials.add(credential);
        MongoClient mongoClient1 = new MongoClient(serverAddresses, credentials);
        DB db = mongoClient1.getDB(database);
        System.out.println(db.getCollectionNames());


        System.out.println("Done");
    } catch (UnknownHostException e) {
        e.printStackTrace();
    }

Connect to remote MongoDB database using Java web application.使用 Java Web 应用程序连接到远程 MongoDB 数据库。 Below code surely help you.下面的代码肯定对你有帮助。

Before to use below code please add property file having credentials all other required details in it.在使用下面的代码之前,请添加具有凭据的属性文件,其中包含所有其他必需的详细信息。 Read that property file in spring-config.xml.在 spring-config.xml 中读取该属性文件。 You can use below code to read the property file -您可以使用以下代码读取属性文件 -

<context:property-placeholder location='classpath:/config/configTest.properties'/>

@Configuration public class MongoConfiguration extends AbstractMongoConfiguration{ @Configuration 公共类 MongoConfiguration 扩展 AbstractMongoConfiguration{

@Value("${mongodb.dbname}")
private String  dbName;

@Value("${mongodb.host}")
private String  host;

@Value("${mongodb.port}")
private Integer port;

@Value("${mongodb.username}")
private String  userName;

@Value("${mongodb.password}")
private String  password;

@Value("${mongodb.authenticationdatabase}")
private String  authenticationDatabase;

@Override
protected String getDatabaseName()  {
    return this.dbName;
}

@Override
public MongoClient mongo() throws Exception {
    List<ServerAddress> serverAddresses = new ArrayList<ServerAddress>();
    ServerAddress address = new ServerAddress(host, port);
    serverAddresses.add(address);
    List<MongoCredential> credentials = new ArrayList<MongoCredential>();
    MongoCredential credential = MongoCredential.createPlainCredential(userName, authenticationDatabase, password.toCharArray());
    credentials.add(credential);
    return new MongoClient(serverAddresses, credentials);
}

@Override
@Bean
public SimpleMongoDbFactory mongoDbFactory() throws Exception {
    return new SimpleMongoDbFactory(mongo(), getDatabaseName());
}

@Override
@Bean
public MongoTemplate mongoTemplate() throws Exception {

    final MongoTemplate mongoTemplate = new MongoTemplate(mongo(), getDatabaseName());
    mongoTemplate.setWriteConcern(WriteConcern.SAFE);
    return mongoTemplate;
}

The following works for me:以下对我有用:

private static final String DB_NAME = "yourDbName";

MongoClient mongo = new MongoClient();
DB db = mongo.getDB(DB_NAME);
collection = db.getCollection("myCollection");

The db name is used by the driver;驱动程序使用数据库名称; the connection string (172.234.52.24:27017) is used by the client when viewing the data (MongoVue or MongoExplorer).客户端在查看数据(MongoVue 或 MongoExplorer)时使用连接字符串 (172.234.52.24:27017)。 Also, stick to port 27017.另外,请坚持使用端口 27017。

Edit: I'm using MongoDriver for java to connect.编辑:我使用 MongoDriver for java 进行连接。

In case the recommended answer didnt work;如果推荐的答案不起作用; try setting the bindIp: 0.0.0.0 in mongod.conf file located in /etc/mongod.conf尝试在位于 /etc/mongod.conf 的 mongod.conf 文件中设置 bindIp: 0.0.0.0

Edit: Apparently, late post with no other answer solving my issue and one line answer is insufficient.编辑:显然,迟到的帖子没有其他答案可以解决我的问题,而单行答案是不够的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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