List of usage examples for com.mongodb MongoClientOptions getConnectTimeout
public int getConnectTimeout()
The connection timeout in milliseconds.
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()); }// w ww . j ava 2s. co m return builder; }
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();/* w w w .j a v a 2 s .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 www . j a va 2 s . c o 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.hibernate.ogm.datastore.mongodb.impl.MongoDBDatastoreProvider.java
License:LGPL
protected MongoClient createMongoClient(MongoDBConfiguration config) { MongoClientOptions clientOptions = config.buildOptions(); List<MongoCredential> credentials = config.buildCredentials(); log.connectingToMongo(config.getHost(), config.getPort(), clientOptions.getConnectTimeout()); try {// w w w . j av a 2 s . c om ServerAddress serverAddress = new ServerAddress(config.getHost(), config.getPort()); return credentials == null ? new MongoClient(serverAddress, clientOptions) : new MongoClient(serverAddress, credentials, clientOptions); } catch (UnknownHostException e) { throw log.mongoOnUnknownHost(config.getHost()); } catch (RuntimeException e) { throw log.unableToInitializeMongoDB(e); } }
From source file:org.s1.mongodb.MongoDBConnectionHelper.java
License:Apache License
/** * * @param instance/*from w w w . j a v a 2 s . 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); } }