本文整理汇总了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();
}
示例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);
}
示例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);
}
示例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);
}
示例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;
}
示例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;
}
示例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);
}
}
}
示例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());
}
}
示例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();
}
示例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 ) );
}
}
示例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());
}
}
}
示例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);
}
}
示例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();
}
示例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);
}
示例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());
}