Example usage for com.mongodb MongoClientOptions getConnectionsPerHost

List of usage examples for com.mongodb MongoClientOptions getConnectionsPerHost

Introduction

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

Prototype

public int getConnectionsPerHost() 

Source Link

Document

The maximum number of connections allowed per host for this MongoClient instance.

Usage

From source file:com.bnrc.sdn.properties.MongoProperties.java

License:Apache License

private Builder builder(MongoClientOptions options) {
    Builder builder = MongoClientOptions.builder();
    if (options != null) {
        builder.alwaysUseMBeans(options.isAlwaysUseMBeans());
        builder.connectionsPerHost(options.getConnectionsPerHost());
        builder.connectTimeout(options.getConnectTimeout());
        builder.cursorFinalizerEnabled(options.isCursorFinalizerEnabled());
        builder.dbDecoderFactory(options.getDbDecoderFactory());
        builder.dbEncoderFactory(options.getDbEncoderFactory());
        builder.description(options.getDescription());
        builder.maxWaitTime(options.getMaxWaitTime());
        builder.readPreference(options.getReadPreference());
        builder.socketFactory(options.getSocketFactory());
        builder.socketKeepAlive(options.isSocketKeepAlive());
        builder.socketTimeout(options.getSocketTimeout());
        builder.threadsAllowedToBlockForConnectionMultiplier(
                options.getThreadsAllowedToBlockForConnectionMultiplier());
        builder.writeConcern(options.getWriteConcern());
    }//from   ww w .j  av a  2  s.c  o  m
    return builder;
}

From source file:com.impetus.client.mongodb.MongoDBClientFactory.java

License:Apache License

/**
 * On set mongo server properties.//w  w  w  . j  a  v  a2  s  .c o  m
 * 
 * @param contactNode
 *            the contact node
 * @param defaultPort
 *            the default port
 * @param poolSize
 *            the pool size
 * @param addrs
 *            the addrs
 * @return the mongo client
 * @throws UnknownHostException
 *             the unknown host exception
 */
private MongoClient onSetMongoServerProperties(String contactNode, String defaultPort, String poolSize,
        List<ServerAddress> addrs) throws UnknownHostException {
    MongoClient mongo = null;
    MongoClientOptions mo = null;
    MongoDBSchemaMetadata metadata = MongoDBPropertyReader.msmd;
    ClientProperties cp = metadata != null ? metadata.getClientProperties() : null;
    Properties propsFromCp = null;
    if (cp != null) {
        DataStore dataStore = metadata != null ? metadata.getDataStore() : null;
        List<Server> servers = dataStore != null && dataStore.getConnection() != null
                ? dataStore.getConnection().getServers()
                : null;
        if (servers != null && !servers.isEmpty()) {
            for (Server server : servers) {
                addrs.add(
                        new ServerAddress(server.getHost().trim(), Integer.parseInt(server.getPort().trim())));
            }
        }

        propsFromCp = dataStore != null && dataStore.getConnection() != null
                ? dataStore.getConnection().getProperties()
                : null;
    } else {
        for (String node : contactNode.split(Constants.COMMA)) {
            if (StringUtils.countMatches(node, Constants.COLON) == 1) {
                // node is given with hostname and port
                // count == 1 is to exclude IPv6 addresses
                String host = node.split(":")[0];
                int port = Integer.parseInt(node.split(Constants.COLON)[1]);

                addrs.add(new ServerAddress(host.trim(), port));
            } else {
                addrs.add(new ServerAddress(node.trim(), Integer.parseInt(defaultPort.trim())));
            }
        }
    }

    MongoClientOptions.Builder b = new PopulateMongoOptions(propsFromCp, externalProperties).prepareBuilder();
    mo = b.build();

    if (mo.getConnectionsPerHost() <= 0 && !StringUtils.isEmpty(poolSize)) {
        mo = b.connectionsPerHost(Integer.parseInt(poolSize)).build();
    }

    mongo = new MongoClient(addrs, mo);

    return mongo;
}

From source file:com.ultratechnica.mongodb.Main.java

License:Apache License

public static void main(String[] args) {

    log.info("=============================================================================================\n"
            + "                       _   _     _                 \n"
            + " |\\/|  _  ._   _   _  | \\ |_)   |_)  _  ._   _ |_  \n"
            + " |  | (_) | | (_| (_) |_/ |_)   |_) (/_ | | (_ | | \n"
            + "               _|                                  \n"
            + "Copyright 2013 Keith Bishop, Ultratechnica Ltd, http://ultratechnica.com\n"
            + "Licensed to Apache "
            + "=============================================================================================\n");
    Options options = getOptions();/*from ww w  .  ja v  a2s  . c  o m*/

    CommandLine commandLine = parseArgs(args, options);

    MongoClient client = null;

    if (commandLine.hasOption("host") && commandLine.hasOption("port")) {

        String host = commandLine.getOptionValue("host");
        String port = commandLine.getOptionValue("port");

        try {

            client = new MongoClient(host, Integer.parseInt(port));
        } catch (UnknownHostException e) {
            log.error("Unable to connect to host [{}] on port [{}]", host, port);
        }
    } else if (options.hasOption("host")) {

        String host = commandLine.getOptionValue("host");

        try {
            client = new MongoClient(host);
        } catch (UnknownHostException e) {
            log.error("Unable to connect to host [{}] on default port ()", host);
        }
    } else {

        try {
            client = new MongoClient();
        } catch (UnknownHostException e) {
            log.error("Unable to connect default host ({}) on default port ()", DEFAULT_HOST, DEFAULT_PORT);
        }
    }

    if (client == null) {
        System.out.println("Exiting, due to previous connection errors");
        System.exit(1);
    }

    ServerAddress clientAddress = client.getAddress();
    log.info("Connected to MongoDB [{}]", clientAddress);

    MongoClientOptions mongoClientOptions = client.getMongoClientOptions();

    log.info("=============================================================================================\n"
            + "Using Mongo Client options:\n" + "\tConnections per host: "
            + mongoClientOptions.getConnectionsPerHost() + "\n" + "\tConect timeout: "
            + mongoClientOptions.getConnectTimeout() + " \n" + "\tSocket timeout: "
            + mongoClientOptions.getSocketTimeout() + "\n" + "\tMax Wait time: "
            + mongoClientOptions.getMaxWaitTime() + "\n" + "\tMax Auto connect retry time: "
            + mongoClientOptions.getMaxAutoConnectRetryTime() + "\n"
            + "\tMax threads allowed to block for conneciton multipler: "
            + mongoClientOptions.getThreadsAllowedToBlockForConnectionMultiplier() + "\n" + "\tWrite concern: "
            + mongoClientOptions.getWriteConcern() + "\n" + "\tRead Preference: "
            + mongoClientOptions.getReadPreference() + "\n"
            + "=============================================================================================\n");

    String items = commandLine.getOptionValue("n");

    int numberOfItems = 0;
    try {
        numberOfItems = Integer.parseInt(items);
    } catch (NumberFormatException e) {
        log.error("The parameter provided for -n was not an integer [{}]", items);
        System.exit(1);
    }

    DB local = client.getDB("local");

    DBCollection collection = local.getCollection(DEFAULT_COLLECTION_NAME);

    log.info("Starting benchmark, inserting [{}] items into collection [{}]", numberOfItems,
            DEFAULT_COLLECTION_NAME);

    long startTime = System.currentTimeMillis();

    for (int i = 0; i < numberOfItems; i++) {

        BasicDBObjectBuilder builder = BasicDBObjectBuilder.start().add("timestamp", new Date())
                .add("field1", "123456").add("field2", "2345678")
                .add("field3", "123123231313131232131231231231123132123123123").add("field4", true);

        WriteResult result = collection.insert(builder.get());
        if (!result.getLastError().ok()) {
            log.error("An error occurred [{}]", result.getLastError());
        }
    }

    long endTime = System.currentTimeMillis();

    log.info("Finished benchmarking.");
    long timeTakenMillis = endTime - startTime;

    float timeTaken = (float) timeTakenMillis / 1000;

    log.info("Results:\n\n" + String.format("%-25s %d", "Number of Items inserted:", numberOfItems) + "\n"
            + String.format("%-25s %.2f", "Time elapsed:", timeTaken) + " seconds\n"
            + String.format("%-25s %.2f", "Throughput:", numberOfItems / timeTaken) + " items/sec\n");

    log.info("Removing test data...");
    collection.remove(new BasicDBObject());
    log.info("Cleared collection [test]");
}

From source file:io.dirigible.mongodb.jdbc.MongodbConnection.java

License:Apache License

private Properties mongoClientOptionsAsProperties(MongoClientOptions ops, Properties props) {
    //TODO: write complex object properties too?
    if (ops.getDescription() != null)
        props.setProperty("description", ops.getDescription());
    if (ops.getRequiredReplicaSetName() != null)
        props.setProperty("requiredReplicaSetName", ops.getRequiredReplicaSetName());
    props.setProperty("connectionsPerHost", "" + ops.getConnectionsPerHost());
    props.setProperty("connectTimeout", "" + ops.getConnectTimeout());
    props.setProperty("heartbeatConnectTimeout", "" + ops.getHeartbeatConnectTimeout());
    props.setProperty("heartbeatFrequency", "" + ops.getHeartbeatFrequency());
    props.setProperty("heartbeatSocketTimeout", "" + ops.getHeartbeatSocketTimeout());
    props.setProperty("localThreshold", "" + ops.getLocalThreshold());
    props.setProperty("maxConnectionIdleTime", "" + ops.getMaxConnectionIdleTime());
    props.setProperty("maxConnectionLifeTime", "" + ops.getMaxConnectionLifeTime());
    props.setProperty("maxWaitTime", "" + ops.getMaxWaitTime());
    props.setProperty("minConnectionsPerHost", "" + ops.getMinConnectionsPerHost());
    props.setProperty("minHeartbeatFrequency", "" + ops.getMinHeartbeatFrequency());
    props.setProperty("serverSelectionTimeout", "" + ops.getServerSelectionTimeout());
    props.setProperty("socketTimeout", "" + ops.getSocketTimeout());
    return props;
}

From source file:org.apache.jackrabbit.oak.plugins.document.util.MongoConnection.java

License:Apache License

public static String toString(MongoClientOptions opts) {
    return Objects.toStringHelper(opts).add("connectionsPerHost", opts.getConnectionsPerHost())
            .add("connectTimeout", opts.getConnectTimeout()).add("socketTimeout", opts.getSocketTimeout())
            .add("socketKeepAlive", opts.isSocketKeepAlive()).add("maxWaitTime", opts.getMaxWaitTime())
            .add("threadsAllowedToBlockForConnectionMultiplier",
                    opts.getThreadsAllowedToBlockForConnectionMultiplier())
            .add("readPreference", opts.getReadPreference().getName())
            .add("writeConcern", opts.getWriteConcern()).toString();
}

From source file:org.axonframework.mongo.eventsourcing.eventstore.MongoOptionsFactory.java

License:Apache License

/**
 * Uses the configured parameters to create a MongoOptions instance.
 *
 * @return MongoOptions instance based on the configured properties
 *//*from   w  ww  .  j ava  2s  .co  m*/
public MongoClientOptions createMongoOptions() {
    MongoClientOptions options = MongoClientOptions.builder().connectionsPerHost(getConnectionsPerHost())
            .connectTimeout(getConnectionTimeout()).maxWaitTime(getMaxWaitTime())
            .threadsAllowedToBlockForConnectionMultiplier(getThreadsAllowedToBlockForConnectionMultiplier())
            .socketTimeout(getSocketTimeOut()).build();
    if (logger.isDebugEnabled()) {
        logger.debug("Mongo Options");
        logger.debug("Connections per host :{}", options.getConnectionsPerHost());
        logger.debug("Connection timeout : {}", options.getConnectTimeout());
        logger.debug("Max wait timeout : {}", options.getMaxWaitTime());
        logger.debug("Threads allowed to block : {}",
                options.getThreadsAllowedToBlockForConnectionMultiplier());
        logger.debug("Socket timeout : {}", options.getSocketTimeout());
    }
    return options;
}

From source file:org.s1.mongodb.MongoDBConnectionHelper.java

License:Apache License

/**
 *
 * @param instance/*  w  w w. ja  v a 2s . c  o m*/
 */
private static synchronized void initialize(String instance) {
    if (!connections.containsKey(instance)) {

        Map<String, Object> mopt = Options.getStorage().getMap(OPTIONS);
        Map<String, Object> m = Objects.get(mopt, "connections." + instance);
        if (Objects.isNullOrEmpty(m)) {
            m = Objects.get(mopt, "connections." + DEFAULT_INSTANCE);
        }

        MongoClientOptions.Builder b = MongoClientOptions.builder();
        MongoClientOptions def_opt = MongoClientOptions.builder().build();
        b.connectionsPerHost(Objects.get(m, "connectionsPerHost", def_opt.getConnectionsPerHost()));
        b.autoConnectRetry(Objects.get(m, "autoConnectRetry", def_opt.isAutoConnectRetry()));
        b.connectTimeout(Objects.get(m, "connectTimeout", def_opt.getConnectTimeout()));
        b.socketKeepAlive(Objects.get(m, "socketKeepAlive", def_opt.isSocketKeepAlive()));
        b.socketTimeout(Objects.get(m, "socketTimeout", def_opt.getSocketTimeout()));
        b.maxAutoConnectRetryTime(
                Objects.get(m, "maxAutoConnectRetryTime", def_opt.getMaxAutoConnectRetryTime()));
        b.maxWaitTime(Objects.get(m, "maxWaitTime", def_opt.getMaxWaitTime()));
        b.threadsAllowedToBlockForConnectionMultiplier(
                Objects.get(m, "threadsAllowedToBlockForConnectionMultiplier",
                        def_opt.getThreadsAllowedToBlockForConnectionMultiplier()));
        b.writeConcern(WriteConcern.FSYNC_SAFE);
        MongoClientOptions opt = b.build();

        MongoClient cl = null;
        try {
            cl = new MongoClient(
                    new ServerAddress(Objects.get(m, "host", "localhost"), Objects.get(m, "port", 27017)), opt);
        } catch (UnknownHostException e) {
            throw S1SystemError.wrap(e);
        }

        String dbName = Objects.get(m, "name");
        if (Objects.isNullOrEmpty(dbName))
            throw new S1SystemError("Cannot initialize MongoDB connection, because name is not set");

        DB db = cl.getDB(dbName);

        String user = Objects.get(m, "user");
        String password = Objects.get(m, "password");
        if (!Objects.isNullOrEmpty(user)) {
            if (!db.authenticate(user, password.toCharArray())) {
                throw new S1SystemError(
                        "Cannot authenticate MongoDB connection " + dbName + " with user " + user);
            }
        }
        LOG.info("MongoDB connected " + cl.getAddress().getHost() + ":" + cl.getAddress().getPort());

        connections.put(instance, db);
    }
}