mongo java driver 2.14.0。更改已弃用的代码

时间:2016-07-28 10:30:43

标签: java spring mongo-java-driver

我正在将mongo java驱动程序jar升级到2.14.0。我的旧代码工作正常,但是代码显示了不推荐使用的类和构造函数,所以我需要兼容的代码而没有弃用的类和mongo-java-driver.jar 2.14.0的构造函数。

public MongoTemplate getMongoTemplate() {

    SimpleMongoDbFactory simpleMongoDbFactory = null;

    try {

        MongoOptions opts = new MongoOptions();//depricate

        opts.threadsAllowedToBlockForConnectionMultiplier = getThreadsAllowedToBlockForConnectionMultiplier();//depricate

        opts.connectionsPerHost = getConnectionsPerHost();//depricate

        ServerAddress addr = new ServerAddress(getHost(), getPort());

        Mongo mongo = new Mongo(addr, opts);//depricate

        simpleMongoDbFactory = new SimpleMongoDbFactory(mongo,
                getDatabaseName());//depricate

        if (mongoTemplate == null) {

            mongoTemplate = new MongoTemplate(simpleMongoDbFactory);

        }

    } catch (UnknownHostException e) {

        LOGGER.error(e.getMessage());

    } catch (MongoException e) {

        LOGGER.error(e.getMessage());

    }

    return mongoTemplate;
}

2 个答案:

答案 0 :(得分:1)

这不是Spring Data MongoDB代码。这是来自MongoDB Java驱动程序的代码,已经在很久以前就已经弃用了。鼓励用户使用MongoClient而非MongoMongoClientOptions超过MongoOptions等。

答案 1 :(得分:1)

相同的代码是

public MongoTemplate getMongoTemplate() {

    SimpleMongoDbFactory simpleMongoDbFactory = null;

    try {
        Builder builder =MongoClientOptions.builder();
        builder.threadsAllowedToBlockForConnectionMultiplier(getThreadsAllowedToBlockForConnectionMultiplier());
        builder.connectionsPerHost(getConnectionsPerHost());
        MongoClientOptions options = builder.build();

        ServerAddress addr = new ServerAddress(getHost(), getPort());
        MongoClient mongo = new MongoClient(addr, options);

        simpleMongoDbFactory = new SimpleMongoDbFactory(mongo,getDatabaseName());

        if (mongoTemplate == null) {

            mongoTemplate = new MongoTemplate(simpleMongoDbFactory);

        }

    } catch (UnknownHostException e) {

        LOGGER.error(e.getMessage());

    } catch (MongoException e) {

        LOGGER.error(e.getMessage());

    }

    return mongoTemplate;
}