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; }
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); }
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; }
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); }
private MongoClientOptions createMongoOptions(MongoDataSourceSetting setting){ Builder option = MongoClientOptions.builder() .writeConcern(setting.getWriteConcern()) .connectionsPerHost(setting.getConnectionsPerHost()) .socketKeepAlive(setting.getSocketKeepAlive()); return option.build(); }
/** * @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); } }
private static MongoClient getInstance(){ if (client == null) { Properties prop = PropertiesUtil.loadProperties("mongodb.properties"); String host = PropertiesUtil.getString(prop, "host"); int port = PropertiesUtil.getInt(prop, "port"); defauleDbName = "admin"; try { client = new MongoClient(host, port); } catch (UnknownHostException e) { logger.info("{}", e); } // or, to connect to a replica set, with auto-discovery of the primary, supply a seed list of members // List<ServerAddress> listHost = Arrays.asList(new ServerAddress("localhost", 27017),new ServerAddress("localhost", 27018)); // instance.mongoClient = new MongoClient(listHost); // 大部分用户使用mongodb都在安全内网下,但如果将mongodb设为安全验证模式,就需要在客户端提供用户名和密码: //boolean auth = client.authenticate(myUserName, myPassword); Builder options = new MongoClientOptions.Builder(); options.connectionsPerHost(300); // 连接池设置为300个连接,默认为100 options.connectTimeout(15000); // 连接超时,推荐>3000毫秒 options.maxWaitTime(5000); options.socketTimeout(0); // 套接字超时时间,0无限制 options.threadsAllowedToBlockForConnectionMultiplier(5000);// 线程队列数,如果连接线程排满了队列就会抛出 "Out of semaphores to get db"错误。 options.writeConcern(WriteConcern.SAFE); options.build(); } return client; }
private MorphiaManager(String host, int port) { try { if (mongoClient == null) { Builder optionsBuilder = new MongoClientOptions.Builder().socketKeepAlive(true); mongoClient = new MongoClient(new MongoClientURI( host != null ? "mongodb://" + host + ':' + port : "mongodb://localhost:27017", optionsBuilder)); } } catch (Exception e) { throw new RuntimeException(e); } }
private MorphiaManager(String host, int port, String username, String password) { try { if (mongoClient == null) { Builder optionsBuilder = new MongoClientOptions.Builder().socketKeepAlive(true); ServerAddress srvAdr = new ServerAddress(host != null ? host : "localhost" , port); MongoCredential credential = MongoCredential.createScramSha1Credential(username, "admin", password.toCharArray()); mongoClient = new MongoClient(srvAdr, Arrays.asList(credential), optionsBuilder.build()); } } catch (Exception e) { throw new RuntimeException(e); } }
private static MongoClientOptions.Builder createDefaultClientOptionsBuilder(Properties connProperties ) { Builder clientOptionsBuilder = new MongoClientOptions.Builder( ); if ( connProperties != null ) { if ( hasKeepSocketAlive( connProperties ) ) // need to change // setting, // as MongoDB default is // false clientOptionsBuilder.socketKeepAlive( true ); } return clientOptionsBuilder; }
private static MongoClientURI getMongoURI( Properties connProps, MongoClientOptions.Builder clientOptionsBuilder ) throws Exception { // check if explicitly indicated not to use URI, even if URI value exists Boolean ignoreURI = getBooleanPropValue( connProps, IGNORE_URI_PROP ); if( ignoreURI != null && ignoreURI ) return null; String uri = getStringPropValue( connProps, MONGO_URI_PROP ); if( uri == null || uri.isEmpty() ) return null; try { if ( clientOptionsBuilder != null ) { return new MongoClientURI( uri, clientOptionsBuilder ); } else { return new MongoClientURI( uri ); } } catch( Exception ex ) { // log and ignore getLogger().log( Level.INFO, Messages.bind( "Invalid Mongo Database URI: {0}", uri ), ex ); //$NON-NLS-1$ throw ex; } //return null; }
@Override public MongoClientOptions.Builder getObject() throws Exception { Builder builder = MongoClientOptions.builder(); builder.socketTimeout(this.socketTimeout); builder.connectTimeout(this.connectTimeout); return builder; }
private Builder builder(MongoClientOptions options) { if (options != null) { return MongoClientOptions.builder(options); } return MongoClientOptions.builder(); }
@Bean public Builder options() { CodecRegistry codecRegistry = CodecRegistries.fromRegistries(MongoClient.getDefaultCodecRegistry(), CodecRegistries.fromCodecs(new LocalDateTimeCodec(), new HostAndPortCodec(), new LocalDateTimeCodec())); return MongoClientOptions.builder().codecRegistry(codecRegistry); }
private SimpleMongoDbFactory createMongoDbFactory(MongoServiceInfo serviceInfo, MongoClientOptions.Builder mongoOptionsToUse) throws UnknownHostException { MongoClientURI mongoClientURI = new MongoClientURI(serviceInfo.getUri(), mongoOptionsToUse); MongoClient mongo = new MongoClient(mongoClientURI); return new SimpleMongoDbFactory(mongo, mongoClientURI.getDatabase()); }
/** * Load settings for a specific shard */ private void loadShard (String shardName) throws Exception { ArrayList<String> shardSrc = scB.getMongoShards().get(shardName); ArrayList<String> consPerHostSrc = scB.getMongoConsPerHost().get(shardName); ArrayList<String> connectTimeoutSrc = scB.getMongoConnectTimeout().get(shardName); ArrayList<String> socketTimeoutSrc = scB.getMongoSocketTimeout().get(shardName); // Loading shard hosts if (shardSrc == null || shardSrc.size() == 0) { throw new Exception("¡Shard settings not defined for ("+shardName+")!"); } ArrayList<ServerAddress> addresses = new ArrayList<ServerAddress>(); for (String hostName : shardSrc) { ArrayList<String> hostAddrSrc = scB.getMongoHosts().get(hostName); if (hostAddrSrc == null || hostAddrSrc.size() != 2) { throw new Exception("¡No address found for \""+hostName+"\" host!"); } addresses.add(new ServerAddress( hostAddrSrc.get(0), Integer.parseInt(hostAddrSrc.get(1)) )); } // Loading shard tuning settings if (consPerHostSrc == null || consPerHostSrc.size() != 1) { consPerHostSrc = scB.getMongoConsPerHost().get(StorageConstantsBean.DEFAULT); if (consPerHostSrc == null) { throw new Exception("¡Number of connections per host not defined!"); } } if (connectTimeoutSrc == null || connectTimeoutSrc.size() != 1) { connectTimeoutSrc = scB.getMongoConnectTimeout().get(StorageConstantsBean.DEFAULT); if (connectTimeoutSrc == null) { throw new Exception("¡Connection timeout not defined!"); } } if (socketTimeoutSrc == null || socketTimeoutSrc.size() != 1) { socketTimeoutSrc = scB.getMongoSocketTimeout().get(StorageConstantsBean.DEFAULT); if (socketTimeoutSrc == null) { throw new Exception("¡Socket timeout not defined!"); } } int consPerHost = Integer.parseInt(consPerHostSrc.get(0)); int connectTimeout = Integer.parseInt(connectTimeoutSrc.get(0)); int socketTimeout = Integer.parseInt(socketTimeoutSrc.get(0)); MongoClient mc = new MongoClient( addresses, new MongoClientOptions.Builder() .socketKeepAlive(true) .autoConnectRetry(true) .connectionsPerHost(consPerHost) .connectTimeout(connectTimeout) .socketTimeout(socketTimeout) .writeConcern(WriteConcern.UNACKNOWLEDGED) .readPreference(ReadPreference.secondaryPreferred()) .build() ); mcs.put(shardName, mc); }
/** * Load settings for a specific host */ private void loadHost (String hostName) throws Exception { ArrayList<String> hostAddrSrc = scB.getMongoHosts().get(hostName); ArrayList<String> consPerHostSrc = scB.getMongoConsPerHost().get(hostName); ArrayList<String> connectTimeoutSrc = scB.getMongoConnectTimeout().get(hostName); ArrayList<String> socketTimeoutSrc = scB.getMongoSocketTimeout().get(hostName); // Loading host address if (hostAddrSrc == null || hostAddrSrc.size() != 2) { throw new Exception("¡No address found for \""+hostName+"\" host!"); } ServerAddress addr = new ServerAddress( hostAddrSrc.get(0), Integer.parseInt(hostAddrSrc.get(1)) ); // Loading host tuning settings if (consPerHostSrc == null || consPerHostSrc.size() != 1) { consPerHostSrc = scB.getMongoConsPerHost().get(StorageConstantsBean.DEFAULT); if (consPerHostSrc == null) { throw new Exception("¡Number of connections per host not defined!"); } } if (connectTimeoutSrc == null || connectTimeoutSrc.size() != 1) { connectTimeoutSrc = scB.getMongoConnectTimeout().get(StorageConstantsBean.DEFAULT); if (connectTimeoutSrc == null) { throw new Exception("¡Connection timeout not defined!"); } } if (socketTimeoutSrc == null || socketTimeoutSrc.size() != 1) { socketTimeoutSrc = scB.getMongoSocketTimeout().get(StorageConstantsBean.DEFAULT); if (socketTimeoutSrc == null) { throw new Exception("¡Socket timeout not defined!"); } } int consPerHost = Integer.parseInt(consPerHostSrc.get(0)); int connectTimeout = Integer.parseInt(connectTimeoutSrc.get(0)); int socketTimeout = Integer.parseInt(socketTimeoutSrc.get(0)); MongoClient mc = new MongoClient( addr, new MongoClientOptions.Builder() .socketKeepAlive(true) .autoConnectRetry(true) .connectionsPerHost(consPerHost) .connectTimeout(connectTimeout) .socketTimeout(socketTimeout) .writeConcern(WriteConcern.UNACKNOWLEDGED) .build() ); mcs.put(hostName, mc); }
@Override public Class<?> getObjectType() { return MongoClientOptions.Builder.class; }