Example usage for com.mongodb Mongo setReadPreference

List of usage examples for com.mongodb Mongo setReadPreference

Introduction

In this page you can find the example usage for com.mongodb Mongo setReadPreference.

Prototype

@Deprecated
public void setReadPreference(final ReadPreference readPreference) 

Source Link

Document

Sets the default read preference to use for reads operations executed on any DBCollection created indirectly from this instance, via a DB instance created from #getDB(String) .

Usage

From source file:com.tomtom.speedtools.tracer.mongo.MongoDBTraceHandler.java

License:Apache License

@Nonnull
static DBCollection getDBCollection(@Nonnull final String servers, @Nonnull final String database,
        @Nonnull final String userName, @Nonnull final String password, final int sizeMB,
        final int connectTimeoutMsecs) throws UnknownHostException {
    assert servers != null;
    assert database != null;
    assert userName != null;
    assert password != null;
    assert connectTimeoutMsecs >= 0;

    LOG.info("getDBCollection: Creating MongoDB connection for traces: {}", servers);
    final Mongo mongo = MongoConnectionCache.getMongoDB(servers, connectTimeoutMsecs, userName, database,
            password);//from   ww w.  j a  v a 2  s  .  c om

    // If this is a replica set, set read preference to secondary for traces.
    final List<ServerAddress> serverAddressList = mongo.getServerAddressList();
    if (serverAddressList.size() > 1) {
        mongo.setReadPreference(ReadPreference.secondary());
    }

    // Should writes fail, then don't throw exceptions, just ignore.
    // We care more about not disturbing the primary system then our own (traces) integrity.
    mongo.setWriteConcern(WriteConcern.UNACKNOWLEDGED);

    // The connection point may actually be null... Not an error.
    final String connectPoint = mongo.getConnectPoint();
    LOG.info("getDBCollection: MongoDB connection for traces established: '{}' at {}", database, connectPoint);

    final DB db = mongo.getDB(database);
    final DBObject options = new BasicDBObject();
    options.put("capped", true);
    options.put("size", sizeMB * MEGABYTE);

    final DBCollection collection;
    if (!db.getCollectionNames().contains(Constants.COLLECTION_NAME)) {
        collection = db.createCollection(Constants.COLLECTION_NAME, options);
    } else {
        collection = db.getCollection(Constants.COLLECTION_NAME);
    }

    return collection;
}

From source file:org.atlasapi.AtlasModule.java

License:Apache License

public @Bean Mongo mongo() {
    Mongo mongo = new Mongo(mongoHosts());
    mongo.setReadPreference(readPreference());
    if (isProcessing() && processingWriteConcern != null
            && !Strings.isNullOrEmpty(processingWriteConcern.get())) {

        WriteConcern writeConcern = WriteConcern.valueOf(processingWriteConcern.get());
        if (writeConcern == null) {
            throw new IllegalArgumentException(
                    "Could not parse write concern: " + processingWriteConcern.get());
        }/* w w w  .  j a v a2 s .  com*/
        mongo.setWriteConcern(writeConcern);
    }
    return mongo;
}

From source file:org.elasticsearch.river.mongodb.RiverMongoDBTestAbstract.java

License:Apache License

private void initMongoInstances(ExecutableType type) throws Exception {
    logger.debug("*** initMongoInstances(" + type + ") ***");
    CommandResult cr;//from   w  w w . j  a v a 2  s.  c o m
    Settings rsSettings = settings.getByPrefix(type.configKey + '.');
    int[] ports;
    if (rsSettings.getAsBoolean("useDynamicPorts", false)) {
        ports = new int[] { Network.getFreeServerPort(), Network.getFreeServerPort(),
                Network.getFreeServerPort() };
    } else {
        int start = 37017 + 10 * type.ordinal();
        ports = new int[] { start, start + 1, start + 2 };
    }
    String replicaSetName = "es-test-" + type.configKey;
    // Create 3 mongod processes
    Starter<IMongodConfig, MongodExecutable, MongodProcess> starter = type.newStarter();
    ImmutableList.Builder<MongoReplicaSet.Member> builder = ImmutableList.builder();
    for (int i = 1; i <= 3; ++i) {
        Storage storage = new Storage("target/" + replicaSetName + '/' + i, replicaSetName, 20);
        MongoReplicaSet.Member member = new MongoReplicaSet.Member();
        member.config = new MongodConfigBuilder()
                .version(Versions.withFeatures(new GenericVersion(rsSettings.get("version"))))
                .net(new de.flapdoodle.embed.mongo.config.Net(ports[i - 1], Network.localhostIsIPv6()))
                .replication(storage).build();
        logger.trace("replSetName in config: {}", member.config.replication().getReplSetName());
        member.executable = starter.prepare(member.config);
        member.process = member.executable.start();
        member.address = new ServerAddress(Network.getLocalHost().getHostName(), member.config.net().getPort());
        logger.debug("Server #" + i + ": {}", member.address);
        builder.add(member);
    }
    ImmutableList<MongoReplicaSet.Member> members = builder.build();
    Thread.sleep(2000);
    MongoClientOptions mco = MongoClientOptions.builder().autoConnectRetry(true).connectTimeout(15000)
            .socketTimeout(60000).build();
    Mongo mongo = new MongoClient(new ServerAddress(Network.getLocalHost().getHostName(), ports[0]), mco);
    DB mongoAdminDB = mongo.getDB(ADMIN_DATABASE_NAME);

    cr = mongoAdminDB.command(new BasicDBObject("isMaster", 1));
    logger.debug("isMaster: " + cr);

    // Initialize replica set
    cr = mongoAdminDB.command(new BasicDBObject("replSetInitiate",
            (DBObject) JSON.parse("{'_id': '" + replicaSetName + "', 'members': [" + "{'_id': 0, 'host': '"
                    + members.get(0).address.getHost() + ':' + members.get(0).address.getPort() + "'}, "
                    + "{'_id': 1, 'host': '" + members.get(1).address.getHost() + ':'
                    + members.get(1).address.getPort() + "'}, " + "{'_id': 2, 'host': '"
                    + members.get(2).address.getHost() + ':' + members.get(2).address.getPort()
                    + "', 'arbiterOnly' : true}]} }")));
    logger.debug("replSetInitiate result: " + cr);

    Thread.sleep(5000);
    cr = mongoAdminDB.command(new BasicDBObject("replSetGetStatus", 1));
    logger.trace("replSetGetStatus result: {}", cr);

    // Check replica set status before to proceed
    while (!isReplicaSetStarted(cr)) {
        logger.debug("Waiting 3 seconds for replicaset to change status...");
        Thread.sleep(3000);
        cr = mongoAdminDB.command(new BasicDBObject("replSetGetStatus", 1));
        // logger.debug("replSetGetStatus: " + cr);
    }

    mongo.close();
    mongo = null;

    // Initialize a new client using all instances.
    List<ServerAddress> mongoServers = new ArrayList<ServerAddress>();
    for (MongoReplicaSet.Member member : members) {
        mongoServers.add(member.address);
    }
    mongo = new MongoClient(mongoServers, mco);
    Assert.assertNotNull(mongo);
    mongo.setReadPreference(ReadPreference.secondaryPreferred());
    mongo.setWriteConcern(WriteConcern.REPLICAS_SAFE);
    replicaSets.put(type, new MongoReplicaSet(type, rsSettings.get("version"), mongo, mongoAdminDB, members));
}

From source file:org.unitedid.shibboleth.attribute.resolver.provider.dataConnector.MongoDbDataConnector.java

License:Apache License

/**
 * Creates the mongo database connection
 *//*from w  w w .ja v a 2s . c o  m*/
protected void initializeMongoDbConnection() {
    if (initialized) {
        log.debug("MongoDB connector initializing!");
        Mongo mongoCon = new Mongo(mongoHost);
        mongoCon.setReadPreference(getPreferredRead());
        db = mongoCon.getDB(mongoDbName);

        if (getMongoUser() != null && getMongoPassword() != null) {
            boolean dbAuth = db.authenticate(getMongoUser(), getMongoPassword().toCharArray());
            if (!dbAuth) {
                log.error(
                        "MongoDB data connector {} authentication failed for database {}, username or password!",
                        getId(), mongoDbName);
                throw new MongoException("MongoDB data connector " + getId() + " authentication failed!");
            } else {
                log.debug("MongoDB data connector {} authentication successful!", getId());
            }
        }
    }
}