Example usage for com.mongodb MongoOptions MongoOptions

List of usage examples for com.mongodb MongoOptions MongoOptions

Introduction

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

Prototype

@Deprecated
public MongoOptions() 

Source Link

Document

Creates a new default MongoOptions .

Usage

From source file:org.rnott.places.MongoDB.java

License:Apache License

public MongoDB() {
    // TODO: look into 'strict' write setting

    /*/* w  w  w . ja va 2  s .  c o  m*/
     * http://stackoverflow.com/questions/6520439/how-to-configure-mongodb-java-driver-mongooptions-for-production-use
     * 
     * autoConnectRetry 
     * Simply means the driver will automatically attempt to reconnect to the server(s) after unexpected disconnects. 
     * In production environments you usually want this set to true.
     * 
     * connectionsPerHost
     * the amount of physical connections a single Mongo instance (it's singleton so you usually have one per application)
     * can establish to a mongod/mongos process. At time of writing the java driver will establish this amount of connections eventually even if the
     * actual query throughput is low (in order words you will see the "conn" statistic in mongostat rise until it hits this number per app server).
     * There is no need to set this higher than 100 in most cases but this setting is one of those "test it and see" things. Do note that you will have 
     * to make sure you set this low enough so that the total amount of connections to your server do not exceed db.serverStatus().connections.available.
     * In production we currently have this at 40.
     * 
     * connectTimeout
     * As the name suggest number of milliseconds the driver will wait before a connection attempt is aborted. Keep the default unless there's a 
     * realistic, expected change this will be in the way of otherwise successful connection attempts.
     * 
     * maxWaitTime
     * Number of ms a thread will wait for a connection to become available on the connection pool, and raises an exception if this does not happen
     * in time. Keep default.
     * 
     * socketTimeout
     * Standard socket timeout value. Keep default.
     * 
     * threadsAllowedToBlockForConnectionMultiplier
     * Number of threads that are allowed to wait for connections to become available if the pool is currently exhausted. This is the setting that will
     * cause the "com.mongodb.DBPortPool$SemaphoresOut: Out of semaphores to get db connection" exception. It will throw this exception once this thread
     * queue exceeds the threadsAllowedToBlockForConnectionMultiplier value. If you expect big peaks in throughput that could case large queues temporarily
     * increase this value. We have it at 1500 at the moment for exactly that reason. If your query load consistently outpaces the server you should just
     * improve your hardware/scaling situation accordingly.
     * 
     * slaveOk
     * Very important for increased read performance if you use replica sets. This basically allows mongo to direct reads to non-primary replica members,
     * spreading the read load. Note that this can also be configured per query in your code. If you use replica sets (and you should) and you can live 
     * with eventual consistency issues (meaning your secondaries might be slightly behind the primary's state) enable this.
     * 
     * safe
     * When enabled the driver is forced to send a getLastError() command to the server after every write operation. This ensures that any possible problems
     * (unique constraint violations, query issues, etc.) are noticed on the client side and possibly throw an error. It defaults to false but you should set
     * this to true and change the WriteConcern of your updates if, and only if, you know you will not care about the result of the update and/or desperately
     * require additional performance.
     * 
     * w
     * Oddly named parameter ;). If safe = true and w > 0 it determines the amount of replica set members a write has to be propogated to before considering
     * it successful. Use this for increased durability at the (considerable) expense of throughput.
     * 
     * fsync
     * Durability option that forces mongo to flush to disk after each write when enabled. I've never had any durability issues related to a write backlog so
     * we have this on false (the default) in production.
     */
    MongoOptions options = new MongoOptions();
    options.autoConnectRetry = true;
    //options.slaveOk = true;  see ReadPreference.SECONDARY
    options.safe = true;
    options.fsync = true; // durability is a must

    if (env == null) {
        //throw new RuntimeException( "Runtime environment is not injected" );
        // TODO: runtime environment bean is not being injected
        env = new Environment();
        env.initialize();
    }
    try {
        ServerAddress addr = new ServerAddress(env.getDatabaseHost(), env.getDatabasePort());
        mongo = new Mongo(addr, options);
    } catch (UnknownHostException e) {
        throw new RuntimeException("Failed to locate MongoDB", e);
    } catch (MongoException e) {
        throw new RuntimeException("Failed MongoDB initialization", e);
    }

    // authenticate
    logger.info("Initializing database: {}", env.getDatabaseName());
    logger.info(env.toString());
    mongo.getDB(env.getDatabaseName()).authenticate(env.getDatabaseUser(),
            env.getDatabasePassword().toCharArray());

    // initialize Morphia
    morphia = new Morphia();

    // set up mapping for entity types
    for (Class<?> c : MAPPED_CLASSES) {
        morphia.map(c);
    }

    // enable JSR303 Validation
    // this is extended so that it can respond to dynamic validation groups
    // TODO: re-enable validation after figuring out how to deal with Address issues (when embedded in Place, city and postal code may be null)
    //new DynamicValidationExtension( morphia );
}

From source file:org.springframework.data.document.mongodb.MongoFactoryBean.java

License:Apache License

public void afterPropertiesSet() throws Exception {
    // apply defaults - convenient when used to configure for tests
    // in an application context
    if (mongo == null) {

        if (host == null) {
            logger.warn("Property host not specified. Using default configuration");
            mongo = new Mongo();
        } else {/*  w  w w .j a v a 2  s  . c o  m*/
            ServerAddress defaultOptions = new ServerAddress();
            if (mongoOptions == null)
                mongoOptions = new MongoOptions();
            if (replicaPair != null) {
                if (replicaPair.size() < 2) {
                    throw new CannotGetMongoDbConnectionException(
                            "A replica pair must have two server entries");
                }
                mongo = new Mongo(replicaPair.get(0), replicaPair.get(1), mongoOptions);
            } else if (replicaSetSeeds != null) {
                mongo = new Mongo(replicaSetSeeds, mongoOptions);
            } else {
                String mongoHost = host != null ? host : defaultOptions.getHost();
                if (port != null) {
                    mongo = new Mongo(new ServerAddress(mongoHost, port), mongoOptions);
                } else {
                    mongo = new Mongo(mongoHost, mongoOptions);
                }
            }
        }
    }
}

From source file:org.springframework.data.mongodb.core.MongoFactoryBean.java

License:Apache License

@Override
protected Mongo createInstance() throws Exception {

    Mongo mongo;//from  www .j  a  v  a2  s .com
    ServerAddress defaultOptions = new ServerAddress();

    if (mongoOptions == null) {
        mongoOptions = new MongoOptions();
    }

    if (!isNullOrEmpty(replicaPair)) {
        if (replicaPair.size() < 2) {
            throw new CannotGetMongoDbConnectionException("A replica pair must have two server entries");
        }
        mongo = new Mongo(replicaPair.get(0), replicaPair.get(1), mongoOptions);
    } else if (!isNullOrEmpty(replicaSetSeeds)) {
        mongo = new Mongo(replicaSetSeeds, mongoOptions);
    } else {
        String mongoHost = StringUtils.hasText(host) ? host : defaultOptions.getHost();
        mongo = port != null ? new Mongo(new ServerAddress(mongoHost, port), mongoOptions)
                : new Mongo(mongoHost, mongoOptions);
    }

    if (writeConcern != null) {
        mongo.setWriteConcern(writeConcern);
    }

    return mongo;
}

From source file:org.springframework.data.mongodb.core.MongoOptionsFactoryBean.java

License:Apache License

@Override
protected MongoOptions createInstance() throws Exception {

    if (MongoClientVersion.isMongo3Driver()) {
        throw new IllegalArgumentException(String.format(
                "Usage of 'mongo-options' is no longer supported for MongoDB Java driver version 3 and above. Please use 'mongo-client-options' and refer to chapter 'MongoDB 3.0 Support' for details."));
    }//from w w  w .  j  a v a 2 s  . c o m

    MongoOptions options = new MongoOptions();

    options.setConnectionsPerHost(connectionsPerHost);
    options.setThreadsAllowedToBlockForConnectionMultiplier(threadsAllowedToBlockForConnectionMultiplier);
    options.setMaxWaitTime(maxWaitTime);
    options.setConnectTimeout(connectTimeout);
    options.setSocketTimeout(socketTimeout);
    options.setSocketKeepAlive(socketKeepAlive);

    options.setW(writeNumber);
    options.setWtimeout(writeTimeout);
    options.setFsync(writeFsync);

    if (ssl) {
        options.setSocketFactory(sslSocketFactory != null ? sslSocketFactory : SSLSocketFactory.getDefault());
    }

    ReflectiveMongoOptionsInvoker.setAutoConnectRetry(options, autoConnectRetry);
    ReflectiveMongoOptionsInvoker.setMaxAutoConnectRetryTime(options, maxAutoConnectRetryTime);
    ReflectiveMongoOptionsInvoker.setSlaveOk(options, slaveOk);

    return options;
}