當前位置: 首頁>>代碼示例>>Java>>正文


Java MongoClientOptions類代碼示例

本文整理匯總了Java中com.mongodb.MongoClientOptions的典型用法代碼示例。如果您正苦於以下問題:Java MongoClientOptions類的具體用法?Java MongoClientOptions怎麽用?Java MongoClientOptions使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


MongoClientOptions類屬於com.mongodb包,在下文中一共展示了MongoClientOptions類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: getOptions

import com.mongodb.MongoClientOptions; //導入依賴的package包/類
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();
}
 
開發者ID:lolog,項目名稱:mogodb-dao,代碼行數:25,代碼來源:MongoPoolImpl.java

示例2: main

import com.mongodb.MongoClientOptions; //導入依賴的package包/類
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);
}
 
開發者ID:axelspringer,項目名稱:polymorphia,代碼行數:22,代碼來源:Tutorial.java

示例3: create

import com.mongodb.MongoClientOptions; //導入依賴的package包/類
@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);
}
 
開發者ID:heisedebaise,項目名稱:tephra,代碼行數:27,代碼來源:MongoImpl.java

示例4: init

import com.mongodb.MongoClientOptions; //導入依賴的package包/類
@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);
}
 
開發者ID:tanhaichao,項目名稱:leopard,代碼行數:17,代碼來源:MongoImpl.java

示例5: connect

import com.mongodb.MongoClientOptions; //導入依賴的package包/類
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;
}
 
開發者ID:denkbar,項目名稱:djigger,代碼行數:19,代碼來源:MongoConnection.java

示例6: createSettingsMap

import com.mongodb.MongoClientOptions; //導入依賴的package包/類
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;
}
 
開發者ID:dadrus,項目名稱:jpa-unit,代碼行數:18,代碼來源:AbstractConfiguration.java

示例7: setOptions

import com.mongodb.MongoClientOptions; //導入依賴的package包/類
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);
            }
        }
    }
 
開發者ID:dadrus,項目名稱:jpa-unit,代碼行數:18,代碼來源:AbstractConfiguration.java

示例8: openMongoDbClient

import com.mongodb.MongoClientOptions; //導入依賴的package包/類
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());
    }
}
 
開發者ID:CenturyLinkCloud,項目名稱:mdw,代碼行數:20,代碼來源:DatabaseAccess.java

示例9: start

import com.mongodb.MongoClientOptions; //導入依賴的package包/類
@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();
}
 
開發者ID:apache,項目名稱:beam,代碼行數:22,代碼來源:MongoDbIO.java

示例10: activateService

import com.mongodb.MongoClientOptions; //導入依賴的package包/類
@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 ) );
    }
}
 
開發者ID:apache,項目名稱:polygene-java,代碼行數:27,代碼來源:MongoDBEntityStoreMixin.java

示例11: initialize

import com.mongodb.MongoClientOptions; //導入依賴的package包/類
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());
        }
    }
}
 
開發者ID:suninformation,項目名稱:ymate-platform-v2,代碼行數:26,代碼來源:MongoDataSourceAdapter.java

示例12: prepareClient

import com.mongodb.MongoClientOptions; //導入依賴的package包/類
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);
    }
}
 
開發者ID:ozlerhakan,項目名稱:mongolastic,代碼行數:17,代碼來源:MongoConfiguration.java

示例13: toMongoClientOptions

import com.mongodb.MongoClientOptions; //導入依賴的package包/類
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();
}
 
開發者ID:otto-de,項目名稱:edison-microservice,代碼行數:17,代碼來源:MongoProperties.java

示例14: startUp

import com.mongodb.MongoClientOptions; //導入依賴的package包/類
@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);
}
 
開發者ID:aureliano,項目名稱:verbum-domini,代碼行數:27,代碼來源:PersistenceManagerImpl.java

示例15: buildOptions

import com.mongodb.MongoClientOptions; //導入依賴的package包/類
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());
}
 
開發者ID:aureliano,項目名稱:verbum-domini,代碼行數:21,代碼來源:PersistenceManagerImpl.java


注:本文中的com.mongodb.MongoClientOptions類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。