public static void main(String[] args) { MongoClientOptions mongoClientOptions = new MongoClientOptions.Builder().codecRegistry(getCodecRegistry()).build(); MongoClient mongoClient = new MongoClient(new ServerAddress("localhost", 27017), mongoClientOptions); MongoDatabase database = mongoClient.getDatabase("tutorial"); MongoCollection<PolymorphicPojo> collection = database.getCollection("entities").withDocumentClass(PolymorphicPojo.class); // create some pojo Pojo pojo = new Pojo(); pojo.setName("A nice name"); pojo.setPojos(Arrays.asList(new SubPojo(42), new SubPojo(48))); // insert into db collection.insertOne(pojo); // read from db PolymorphicPojo foundPojo = collection.find(Filters.eq("_id", pojo.getId())).first(); // output LOGGER.debug("Found pojo {}", foundPojo); }
@Override public void create(JSONObject config) { String key = config.getString("key"); if (mongos.containsKey(key)) return; String schema = config.getString("schema"); if (validator.isEmpty(schema)) throw new NullPointerException("未设置schema值[" + config + "]!"); JSONArray array = config.getJSONArray("ips"); if (array == null || array.size() == 0) throw new NullPointerException("未设置ips值[" + config + "]!"); String username = config.getString("username"); String password = config.getString("password"); MongoClientOptions.Builder builder = MongoClientOptions.builder().connectionsPerHost(maxActive).maxWaitTime(maxWait); List<MongoClient> list = new ArrayList<>(); for (int i = 0; i < array.size(); i++) list.add(new MongoClient(new MongoClientURI("mongodb://" + username + ":" + password + "@" + array.getString(i) + "/" + schema, builder))); schemas.put(key, schema); mongos.put(key, list); if (logger.isDebugEnable()) logger.debug("Mongo数据库[{}]初始化完成。", config); }
@SuppressWarnings("deprecation") public void init() { String[] list = server.split(":"); String host = list[0]; int port = Integer.parseInt(list[1]); int connectTimeout = 1000 * 60; MongoClientOptions options = new MongoClientOptions.Builder().connectTimeout(connectTimeout).build(); client = new MongoClient(new ServerAddress(host, port), options); this.db = client.getDB(this.database); if (username != null && username.length() > 0) { if (password != null && password.length() > 0) { db.addUser(username, password.toCharArray()); } } this.collection = db.getCollection(collectionName); }
private MongoClientOptions getOptions() { Builder builder = new Builder(); if (this.connectionsPerHost != null) { builder.connectionsPerHost(connectionsPerHost); } if (this.threadsAllowedToBlockForConnectionMultiplier != null) { builder.threadsAllowedToBlockForConnectionMultiplier(threadsAllowedToBlockForConnectionMultiplier); } if (this.maxWaitTime != null) { builder.maxWaitTime(maxWaitTime); } if (this.connectTimeout != null) { builder.connectTimeout(connectTimeout); } if (this.socketTimeout != null) { builder.socketTimeout(socketTimeout); } if (this.socketKeepAlive != null) { builder.socketKeepAlive(socketKeepAlive); } // database configure return builder.build(); }
public MongoDatabase connect(String host, int port, String user, String password) { Builder o = MongoClientOptions.builder().serverSelectionTimeout(3000); String databaseName = "djigger"; List<MongoCredential> credentials = new ArrayList<>(); if (user != null && password != null && !user.trim().isEmpty() && !password.trim().isEmpty()) { credentials.add(MongoCredential.createCredential(user, databaseName, password.toCharArray())); } mongoClient = new MongoClient(new ServerAddress(host,port), credentials, o.build()); // call this method to check if the connection succeeded as the mongo client lazy loads the connection mongoClient.getAddress(); db = mongoClient.getDatabase(databaseName); return db; }
private Map<String, Method> createSettingsMap() { final Map<String, Method> settingsMap = new HashMap<>(); final Method[] methods = MongoClientOptions.Builder.class.getDeclaredMethods(); for (final Method method : methods) { if (method.getParameterTypes().length == 1) { final Class<?> parameterType = method.getParameterTypes()[0]; // only int, string and boolean if (int.class.equals(parameterType) || String.class.equals(parameterType) || boolean.class.equals(parameterType)) { settingsMap.put(method.getName(), method); } } } return settingsMap; }
protected void setOptions(final MongoClientOptions.Builder builder, final ConfigurationPropertyRetriever propertyRetriever) { final Map<String, Method> settingsMap = createSettingsMap(); for (final Map.Entry<String, Method> entry : settingsMap.entrySet()) { final String value = propertyRetriever.get(entry.getKey()); if (value == null) { continue; } final Method setterMethod = entry.getValue(); try { setterMethod.invoke(builder, convertTo(entry.getValue().getParameterTypes()[0], value)); } catch (InvocationTargetException | IllegalAccessException e) { LOG.error("Could not set options", e); } } }
private static synchronized void openMongoDbClient() { if (mongoClient == null) { String mongoHost = PropertyManager.getProperty(PropertyNames.MDW_MONGODB_HOST); int mongoPort = PropertyManager.getIntegerProperty(PropertyNames.MDW_MONGODB_PORT, 27017); int maxConnections = PropertyManager.getIntegerProperty(PropertyNames.MDW_MONGODB_POOLSIZE, PropertyManager.getIntegerProperty(PropertyNames.MDW_DB_POOLSIZE, 100)); MongoClientOptions.Builder options = MongoClientOptions.builder(); options.socketKeepAlive(true); if (maxConnections > 100) // MongoClient default is 100 max connections per host options.connectionsPerHost(maxConnections); mongoClient = new MongoClient(new ServerAddress(mongoHost, mongoPort), options.build()); for (String name : mongoClient.getDatabase("mdw").listCollectionNames()) { createMongoDocIdIndex(name); } LoggerUtil.getStandardLogger().info(mongoClient.getMongoClientOptions().toString()); } }
@Override public boolean start() { Read spec = source.spec; MongoClientOptions.Builder optionsBuilder = new MongoClientOptions.Builder(); optionsBuilder.maxConnectionIdleTime(spec.maxConnectionIdleTime()); optionsBuilder.socketKeepAlive(spec.keepAlive()); client = new MongoClient(new MongoClientURI(spec.uri(), optionsBuilder)); MongoDatabase mongoDatabase = client.getDatabase(spec.database()); MongoCollection<Document> mongoCollection = mongoDatabase.getCollection(spec.collection()); if (spec.filter() == null) { cursor = mongoCollection.find().iterator(); } else { Document bson = Document.parse(spec.filter()); cursor = mongoCollection.find(bson).iterator(); } return advance(); }
@Override public void activateService() throws Exception { loadConfiguration(); // Create Mongo driver and open the database MongoClientOptions options = MongoClientOptions.builder().writeConcern( writeConcern ).build(); if( username.isEmpty() ) { mongo = new MongoClient( serverAddresses, options ); } else { MongoCredential credential = MongoCredential.createMongoCRCredential( username, databaseName, password ); mongo = new MongoClient( serverAddresses, Collections.singletonList( credential ), options ); } db = mongo.getDatabase( databaseName ); // Create index if needed MongoCollection<Document> entities = db.getCollection( collectionName ); if( !entities.listIndexes().iterator().hasNext() ) { entities.createIndex( new BasicDBObject( IDENTITY_COLUMN, 1 ) ); } }
public void initialize(IMongoClientOptionsHandler optionsHandler, MongoDataSourceCfgMeta cfgMeta) throws Exception { __cfgMeta = cfgMeta; MongoClientOptions.Builder _builder = null; if (optionsHandler != null) { _builder = optionsHandler.handler(cfgMeta.getName()); } if (_builder == null) { _builder = MongoClientOptions.builder(); } if (StringUtils.isNotBlank(cfgMeta.getConnectionUrl())) { __mongoClient = new MongoClient(new MongoClientURI(cfgMeta.getConnectionUrl(), _builder)); } else { String _username = StringUtils.trimToNull(cfgMeta.getUserName()); String _password = StringUtils.trimToNull(cfgMeta.getPassword()); if (_username != null && _password != null) { if (__cfgMeta.isPasswordEncrypted() && __cfgMeta.getPasswordClass() != null) { _password = __cfgMeta.getPasswordClass().newInstance().decrypt(_password); } MongoCredential _credential = MongoCredential.createCredential(cfgMeta.getUserName(), cfgMeta.getDatabaseName(), _password == null ? null : _password.toCharArray()); __mongoClient = new MongoClient(cfgMeta.getServers(), Collections.singletonList(_credential), _builder.build()); } else { __mongoClient = new MongoClient(cfgMeta.getServers(), _builder.build()); } } }
private void prepareClient() { try { ServerAddress address = new ServerAddress(config.getMongo().getHost(), config.getMongo().getPort()); MongoClientOptions options = MongoClientOptions.builder() .serverSelectionTimeout(5000) .socketKeepAlive(false) .readPreference(ReadPreference.primaryPreferred()) .sslInvalidHostNameAllowed(true) .build(); client = connectToClient(address, options); } catch (Exception ex) { logger.error(ex.getMessage(), ex); System.exit(-1); } }
public MongoClientOptions toMongoClientOptions(final CodecRegistry codecRegistry) { return builder() .sslEnabled(sslEnabled) .codecRegistry(codecRegistry) .readPreference(ReadPreference.valueOf(readPreference)) .connectTimeout(connectTimeout) .serverSelectionTimeout(serverSelectionTimeout) .cursorFinalizerEnabled(true) .maxWaitTime(maxWaitTime) .maxConnectionLifeTime(connectionpool.getMaxLifeTime()) .threadsAllowedToBlockForConnectionMultiplier(connectionpool.getBlockedConnectionMultiplier()) .maxConnectionIdleTime(connectionpool.getMaxIdleTime()) .minConnectionsPerHost(connectionpool.getMinSize()) .connectionsPerHost(connectionpool.getMaxSize()) .build(); }
@Override public void startUp() { Logger.getLogger("org.mongodb").setLevel(Level.SEVERE); Logger.getLogger("com.mongodb").setLevel(Level.SEVERE); AppConfiguration configuration = AppConfiguration.instance(); this.databaseName = configuration.getProperty("database.name"); if (this.databaseName == null) { throw new VerbumDominiException("Property database.name not found in app-configuration.properties file."); } String connectionUrl = configuration.getProperty("mongodb.connection.url"); if (Environments.TEST.equals(configuration.getEnvironment())) { this.databaseName = "verbum_domini_test"; connectionUrl = "mongodb://localhost"; } else if (Environments.PRODUCTION.equals(configuration.getEnvironment())) { this.databaseName = System.getenv("MONGOLAB_DB_NAME"); connectionUrl = System.getenv("MONGOLAB_URI"); } MongoClientOptions.Builder options = this.buildOptions(configuration); MongoClientURI uri = new MongoClientURI(connectionUrl, options); this.mongoClient = new MongoClient(uri); }
private MongoClientOptions.Builder buildOptions(AppConfiguration configuration) { MongoClientOptions.Builder builder = MongoClientOptions.builder(); if (configuration.getProperty("mongodb.connection.max.per.host") != null) { builder.connectionsPerHost(Integer.parseInt(configuration.getProperty("mongodb.connection.max.per.host"))); } if (configuration.getProperty("mongodb.connection.min.per.host") != null) { builder.minConnectionsPerHost(Integer.parseInt(configuration.getProperty("mongodb.connection.min.per.host"))); } if (configuration.getProperty("mongodb.connection.life.time") != null) { builder.maxConnectionLifeTime(Integer.parseInt(configuration.getProperty("mongodb.connection.life.time"))); } if (configuration.getProperty("mongodb.connection.timeout") != null) { builder.connectTimeout(Integer.parseInt(configuration.getProperty("mongodb.connection.timeout"))); } return builder.codecRegistry(this.buildCodecRegistries()); }
@Test public void testCreate() { final String test1_hostname = "example.com"; final String test1_username = "username"; final String test1_password = "password"; final String test1_database = "database"; final List<ServerAddress> servers = ImmutableList.of( new ServerAddress(test1_hostname) ); final List<MongoCredential> credentials = ImmutableList.of( MongoCredential.createCredential(test1_username, test1_database, test1_password.toCharArray()) ); final MongoClientOptions options = new MongoClientOptions.Builder().build(); final ComposeForMongoDBServiceInfo serviceInfo = new ComposeForMongoDBServiceInfo("id", servers, credentials, options); assertTrue(creator.create(serviceInfo, new ServiceConnectorConfig() { }) instanceof MongoClient); }
public MongoDbConnection connect(ConnectionSettings connectionSettings) { StringBuilder authString = new StringBuilder(); String user = connectionSettings.getUser(); if (user != null && !user.isEmpty()) { authString.append(user); String password = connectionSettings.getPassword(); if (password != null && !password.isEmpty()) { authString.append(":").append(password); } authString.append("@"); } String uri = String.format("mongodb://%s%s", authString, connectionSettings.getHost()); Builder options = MongoClientOptions.builder().serverSelectionTimeout(10000); MongoClient client = new MongoClient(new MongoClientURI(uri, options)); MongoConnection mongoConnection = new MongoConnection(client); return new MongoDbConnection(mongoConnection, connectionSettings); }
@Override public Mongo mongo() throws Exception { List<ServerAddress> serverAddresses = hosts.stream() .map(this::createServerAddress) .collect(toList()); LOG.info("Connecting to DB hosts: {}...", serverAddresses); if (serverAddresses.size() == 1) { // create a mongo client that connects to a single database, // this is NOT the same as calling the constructor with a list of ServerAddresses with only one element! return new MongoClient(serverAddresses.get(0), mongoCredentials()); } else { // create a mongo client that connects to a replicaset MongoClientOptions options = MongoClientOptions.builder() .writeConcern(WriteConcern.ACKNOWLEDGED) .build(); return new MongoClient(serverAddresses, mongoCredentials(), options); } }
private MongoDB() { MongoClientOptions mongoOptions = MongoClientOptions.builder() .socketTimeout(60000) // Wait 1m for a query to finish, https://jira.mongodb.org/browse/JAVA-1076 .connectTimeout(15000) // Try the initial connection for 15s, http://blog.mongolab.com/2013/10/do-you-want-a-timeout/ .maxConnectionIdleTime(600000) // Keep idle connections for 10m, so we discard failed connections quickly .readPreference(ReadPreference.primaryPreferred()) // Read from the primary, if not available use a secondary .build(); MongoClient mongoClient; mongoClient = new MongoClient(new ServerAddress(DB_HOST, DB_PORT), mongoOptions); mongoClient.setWriteConcern(WriteConcern.SAFE); datastore = new Morphia().mapPackage(BaseEntity.class.getPackage().getName()) .createDatastore(mongoClient, DB_NAME); datastore.ensureIndexes(); datastore.ensureCaps(); LOG.info("Connection to database '" + DB_HOST + ":" + DB_PORT + "/" + DB_NAME + "' initialized"); }
@Inject public MongoClientWrapper(MongoClientConfiguration configuration) throws UnreachableMongoServerException { try { MongoClientOptions options = toMongoClientOptions(configuration); ImmutableList<MongoCredential> credentials = toMongoCredentials(configuration); testAddress(configuration.getHostAndPort(), options); this.configuration = configuration; this.driverClient = new com.mongodb.MongoClient( new ServerAddress( configuration.getHostAndPort().getHostText(), configuration.getHostAndPort().getPort()), credentials, options ); version = calculateVersion(); codecRegistry = CodecRegistries.fromCodecs(new DocumentCodec()); closed = false; } catch (com.mongodb.MongoException ex) { throw new UnreachableMongoServerException(configuration.getHostAndPort(), ex); } }
/** * Customize the MongoDB client connection properties. * * @return A {@link MongoClientOptions} bean that is used by the {@link * org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration} when creating the {@link * com.mongodb.Mongo} facade * @see MongoClientOptions * @see org.springframework.core.env.Environment */ @Bean public MongoClientOptions mongoClientOptions( @Value("${spring.data.mongodb.min-connections:2}") final int minConnections, @Value("${spring.data.mongodb.max-connections:10}") final int maxConnections, @Value("${spring.data.mongodb.socket-connect.ms:5000}") final int connectTimeout, @Value("${spring.data.mongodb.socket-timeout.ms:5000}") final int socketTimeout) { return MongoClientOptions.builder() .legacyDefaults() .minConnectionsPerHost(minConnections) .connectionsPerHost(maxConnections) .connectTimeout(connectTimeout) .socketTimeout(socketTimeout) .build(); }
/** * Returns an options object with defaults overriden where there is a valid * override. * * @return */ public MongoClientOptions getMongoClientOptions() { MongoClientOptions.Builder builder = MongoClientOptions.builder(); if (connectionsPerHost != null) { builder.connectionsPerHost(connectionsPerHost); } if (this.readPreference != null) { builder.readPreference(readPreference); } if (ssl) { // taken from MongoClientURI, written this way so we don't have to // construct a URI to connect builder.socketFactory(getSocketFactory()); } builder.writeConcern(writeConcern); return builder.build(); }
public void correctlyExtractsMongoClientFromConfiguration() throws Exception { final Example example = factory.build(testFile); final MongoClient client = example.getMongoClient().build(environment); assertThat(client.getAddress().getHost()).isIn("localhost", "127.0.0.1"); assertThat(client.getAddress().getPort()).isEqualTo(ServerAddress.defaultPort()); assertThat(client.getCredentialsList()).isEmpty(); final MongoClientOptions options = client.getMongoClientOptions(); assertThat(options.getDbDecoderFactory()).isEqualTo(DefaultDBDecoder.FACTORY); assertThat(options.getDbEncoderFactory()).isEqualTo(DefaultDBEncoder.FACTORY); assertThat(options.getReadPreference()).isEqualTo(ReadPreference.primary()); assertThat(options.getWriteConcern()).isEqualTo(WriteConcern.ACKNOWLEDGED); assertThat(options.getSocketFactory()).isEqualTo(SocketFactory.getDefault()); }
public Schema create(SchemaPlus parentSchema, String name, Map<String, Object> operand) { final String host = (String) operand.get("host"); final String database = (String) operand.get("database"); final String authMechanismName = (String) operand.get("authMechanism"); final MongoClientOptions.Builder options = MongoClientOptions.builder(); final List<MongoCredential> credentials = new ArrayList<>(); if (authMechanismName != null) { final MongoCredential credential = createCredentials(operand); credentials.add(credential); } return new MongoSchema(host, database, credentials, options.build()); }
protected void connectDBWithOptions(MongoClientOptions options){ List<ServerAddress> serverList = new ArrayList<ServerAddress>(); try { serverList.add(new ServerAddress("192.168.0.200", 27017)); serverList.add(new ServerAddress("192.168.0.200", 27018)); serverList.add(new ServerAddress("192.168.0.200", 27019)); } catch (UnknownHostException ex) { ex.printStackTrace(); } List<MongoCredential> credentialList = new ArrayList<MongoCredential>(); MongoCredential credentialA = MongoCredential.createCredential("test", "test", "test".toCharArray()); MongoCredential credentialB = MongoCredential.createCredential("test", "test", "test".toCharArray()); MongoCredential credentialC = MongoCredential.createCredential("test", "test", "test".toCharArray()); credentialList.add(credentialA); credentialList.add(credentialB); credentialList.add(credentialC); BuguConnection conn = BuguFramework.getInstance().createConnection(); conn.setOptions(options); conn.setServerList(serverList); conn.setCredentialList(credentialList); conn.setDatabase("test"); conn.connect(); }
@Bean public MongoClient mongo() throws UnknownHostException { // location of db ServerAddress sa = new ServerAddress( environment.getProperty("mongodb.host"), environment.getProperty("mongodb.port", Integer.class) ); // set optional default parameters here MongoClientOptions.Builder builder = MongoClientOptions.builder(); // none yet MongoClientOptions options = builder.build(); return new MongoClient(sa, options); }
@Override public void init() throws ServletException { super.init(); try { LumongoPoolConfig lumongoPoolConfig = new LumongoPoolConfig().addMember("localhost").setDefaultRetries(2); lumongoPoolConfig.setMemberUpdateEnabled(false); lumongoWorkPool = new LumongoWorkPool(lumongoPoolConfig); Properties properties = new Properties(); properties.load(UIQueryServiceImpl.class.getResourceAsStream("/version.properties")); lumongoVersion = properties.getProperty("lumongoVersion"); luceneVersion = properties.getProperty("luceneVersion"); MongoClientOptions mongoClientOptions = MongoClientOptions.builder().connectionsPerHost(32).build(); MongoClient mongoClient = new MongoClient("localhost", mongoClientOptions); Morphia morphia = new Morphia(); morphia.map(UIQueryObject.class); datastore = morphia.createDatastore(mongoClient, QUERY_HISTORY); datastore.ensureIndexes(); } catch (Exception e) { LOG.error("Failed to initiate lumongo work pool.", e); } }
private MongoClientOptions extractMongoOptions(Map<String, String> properties) { MongoClientOptions.Builder builder = new MongoClientOptions.Builder(); String connectionsPerHost = properties.get(DBConstants.MongoDB.CONNECTIONS_PER_HOST); if (!DBUtils.isEmptyString(connectionsPerHost)) { builder.connectionsPerHost(Integer.parseInt(connectionsPerHost)); } String maxWaitTime = properties.get(DBConstants.MongoDB.MAX_WAIT_TIME); if (!DBUtils.isEmptyString(maxWaitTime)) { builder.maxWaitTime(Integer.parseInt(maxWaitTime)); } String connectTimeout = properties.get(DBConstants.MongoDB.CONNECT_TIMEOUT); if (!DBUtils.isEmptyString(connectTimeout)) { builder.connectTimeout(Integer.parseInt(connectTimeout)); } String socketTimeout = properties.get(DBConstants.MongoDB.SOCKET_TIMEOUT); if (!DBUtils.isEmptyString(socketTimeout)) { builder.socketTimeout(Integer.parseInt(socketTimeout)); } String threadsAllowedToBlockForConnectionMultiplier = properties.get( DBConstants.MongoDB.THREADS_ALLOWED_TO_BLOCK_CONN_MULTIPLIER); if (!DBUtils.isEmptyString(threadsAllowedToBlockForConnectionMultiplier)) { builder.threadsAllowedToBlockForConnectionMultiplier( Integer.parseInt(threadsAllowedToBlockForConnectionMultiplier)); } return builder.build(); }
/** * init mongo client as the singleton */ public MongoDB(){ try{ mongoClient = new MongoClient(new ServerAddress(serverName), Arrays.asList(MongoCredential.createMongoCRCredential(username, databaseName,password.toCharArray())), new MongoClientOptions.Builder().cursorFinalizerEnabled(false).build()); db = mongoClient.getDB(databaseName); db.authenticate(username, password.toCharArray()); } catch (Exception e) { e.printStackTrace(); } }
private MongoClientOptions.Builder options(final Config config) { MongoClientOptions.Builder builder = MongoClientOptions.builder(); builder.connectionsPerHost(config.getInt("connectionsPerHost")); builder.threadsAllowedToBlockForConnectionMultiplier( config.getInt("threadsAllowedToBlockForConnectionMultiplier")); builder.maxWaitTime((int) config.getDuration("maxWaitTime", TimeUnit.MILLISECONDS)); builder.connectTimeout((int) config.getDuration("connectTimeout", TimeUnit.MILLISECONDS)); builder.socketTimeout((int) config.getDuration("socketTimeout", TimeUnit.MILLISECONDS)); builder.socketKeepAlive(config.getBoolean("socketKeepAlive")); builder.cursorFinalizerEnabled(config.getBoolean("cursorFinalizerEnabled")); builder.alwaysUseMBeans(config.getBoolean("alwaysUseMBeans")); builder.heartbeatFrequency(config.getInt("heartbeatFrequency")); builder.minHeartbeatFrequency(config.getInt("minHeartbeatFrequency")); builder.heartbeatConnectTimeout( (int) config.getDuration("heartbeatConnectTimeout", TimeUnit.MILLISECONDS)); builder.heartbeatSocketTimeout( (int) config.getDuration("heartbeatSocketTimeout", TimeUnit.MILLISECONDS)); return builder; }
@Bean public MongoClientOptions mongoClientOptions() { try { final MongoClientOptionsFactoryBean bean = new MongoClientOptionsFactoryBean(); bean.setSocketTimeout(TIMEOUT); bean.setConnectTimeout(TIMEOUT); bean.afterPropertiesSet(); return bean.getObject(); } catch (final Exception e) { throw new BeanCreationException(e.getMessage(), e); } }
/** * New mongo db client options. * * @param mongo the mongo * @return the mongo client options */ public static MongoClientOptions newMongoDbClientOptions(final AbstractMongoInstanceProperties mongo) { try { return newMongoDbClientOptionsFactoryBean(mongo).getObject(); } catch (final Exception e) { throw new BeanCreationException(e.getMessage(), e); } }
public MongoV3(List<ServerAddress> servers, List<MongoCredential> authors) { Builder options = new MongoClientOptions.Builder(); options.connectionsPerHost(50);// 连接池设置为300个连接,默认为100 options.connectTimeout(15000);// 连接超时,推荐>3000毫秒 options.maxWaitTime(5000); // options.socketTimeout(500); options.writeConcern(WriteConcern.W2); con = new MongoClient(servers, authors, options.build()); setMongoConnect(this); }
/** * Override client options in order to make the timeout shorter. * More on timeouts here: https://scalegrid.io/blog/understanding-mongodb-client-timeout-options/ */ @Bean public MongoClientOptions mongoClientOptions() { return MongoClientOptions.builder() // timeout for selecting a server to execute operation on .serverSelectionTimeout(3000) // after server selection, tries to connect to server .socketTimeout(3000) .build(); }
private MongoClient createMongoClient(MongoDataSourceSetting setting) { ServerAddress host = new ServerAddress(setting.getUrl(), setting.getPort()); MongoClientOptions options = createMongoOptions(setting); if(shouldAuthenticate(setting)){ return new MongoClient(host, Arrays.asList(createMongoCredential(setting)), options); } return new MongoClient(host, options); }
private MongoClientOptions createMongoOptions(MongoDataSourceSetting setting){ Builder option = MongoClientOptions.builder() .writeConcern(setting.getWriteConcern()) .connectionsPerHost(setting.getConnectionsPerHost()) .socketKeepAlive(setting.getSocketKeepAlive()); return option.build(); }
@BeforeTest private void configure() { final String mongoURI = System.getProperty("indra.mongoURI"); if (mongoURI == null) { Assert.fail("System.getProperty(\"indra.mongoURI\") is null. Provide a mongoURI to execute the integration test."); } MongoClientOptions builder = MongoClientOptions.builder().serverSelectionTimeout(5000).build(); MongoClient mongoClient = new MongoClient(mongoURI, builder); vectorSpaceFactory = new MongoVectorSpaceFactory(mongoClient); translatorFactory = new MongoTranslatorFactory(mongoClient); }
/** * @decription 初始化配置 * @author yi.zhang * @time 2017年6月2日 下午2:15:57 */ public void init(String servers,String database,String schema,String username,String password) { try { List<ServerAddress> saddress = new ArrayList<ServerAddress>(); if (servers != null && !"".equals(servers)) { for (String server : servers.split(",")) { String[] address = server.split(":"); String ip = address[0]; int port = 27017; if (address != null && address.length > 1) { port = Integer.valueOf(address[1]); } saddress.add(new ServerAddress(ip, port)); } } MongoCredential credential = MongoCredential.createScramSha1Credential(username, database,password.toCharArray()); List<MongoCredential> credentials = new ArrayList<MongoCredential>(); credentials.add(credential); Builder builder = new MongoClientOptions.Builder(); builder.maxWaitTime(MAX_WAIT_TIME); // 通过连接认证获取MongoDB连接 MongoClient client = new MongoClient(saddress, credentials, builder.build()); // 连接到数据库 session = client.getDatabase(schema); } catch (Exception e) { logger.error("-----MongoDB Config init Error-----", e); } }