我想知道如何更改我的Java代码以使用spring-data和MongoDB支持replset。

我有3个运行的MongoDB服务器。

./mongod --dbpath=/home/jsmith/tmp/db1 --replSet=spring --port=27017
./mongod --dbpath=/home/jsmith/tmp/db2 --replSet=spring --port=27027
./mongod --dbpath=/home/jsmith/tmp/db3 --replSet=spring --port=27037


如果我执行rs.status(),我可以看到,如果27017上的数据库崩溃,那么其他数据库之一将成为主要数据库,因此我知道mongoDB正常运行,但是在我的Java代码中,如果我尝试运行它,则会出现以下错误:

Exception in thread "main" org.springframework.dao.DataAccessResourceFailureException: can't call something : /127.0.0.1:27017/demo


仅在端口27017上查找

这是我的mongodbconfig:

@Configuration
@EnableMongoRepositories
@ComponentScan(basePackageClasses = {MongoDBApp.class})
@PropertySource("classpath:application.properties")
public class MongoConfiguration extends AbstractMongoConfiguration {


    @Override
    protected String getDatabaseName() {
        return "demo";
    }



    @Override
    public Mongo mongo() throws Exception {
                return new Mongo(new ArrayList<ServerAddress>() {{ add(new ServerAddress("127.0.0.1", 27017)); add(new ServerAddress("127.0.0.1", 27027)); add(new ServerAddress("127.0.0.1", 27037)); }});

    }

    @Override
    protected String getMappingBasePackage() {
        return "com.xxxx.mongodb.example.domain";
    }

}


如何更改它以支持replset?但是,如果它的读数和其中一台服务器出现故障,我会收到一个错误..无论如何要进行重新连接?

最佳答案

这是我的方法:

    String mongoURI="mongodb://myUsrName:pass@mongoServer-001.company.com:27017,mongoServer-002.company.com:27017,mongoServer-003.company.com:27017/myDBname?waitqueuemultiple=1500&amp;w=1&amp;maxpoolsize=40&amp;safe=true";
    MongoURI uri = new MongoURI(mongoURI);
    Mongo mongo = new Mongo(uri);


我在URI中指定了3个服务器(以及其他参数,例如最大池大小)。
第三台服务器(mongoServer-003)是仲裁器,它不存储任何信息。当当前主服务器出现故障时,仲裁器有助于选择主服务器。看看this article

使用此配置,即使主服务器出现故障,该应用也可以继续工作。

10-04 12:05
查看更多