List of usage examples for com.mongodb ReadPreference secondaryPreferred
public static ReadPreference secondaryPreferred()
From source file:brooklyn.entity.nosql.mongodb.MongoDBTestHelper.java
License:Apache License
/** @return The {@link DBObject} representing the object with the given id */ public static DBObject getById(AbstractMongoDBServer entity, String id) { LOG.info("Getting {} from {}", new Object[] { id, entity }); MongoClient mongoClient = clientForServer(entity); // Secondary preferred means the driver will let us read from secondaries too. mongoClient.setReadPreference(ReadPreference.secondaryPreferred()); try {//from w ww .j a v a 2 s . c om DB db = mongoClient.getDB(TEST_DB); DBCollection testCollection = db.getCollection(TEST_COLLECTION); return testCollection.findOne(new BasicDBObject("_id", new ObjectId(id))); } finally { mongoClient.close(); } }
From source file:cloud.simple.RuleEngineApplication.java
@Bean public MongoDatabase dataSource() { String servers = env.getProperty("spring.data.mongodb.custom.service"); String databaseName = env.getProperty("spring.data.mongodb.database"); List<ServerAddress> seeds = new ArrayList<ServerAddress>(); String[] servers1 = servers.split(","); for (String server : servers1) { String[] server1 = server.split(":"); seeds.add(new ServerAddress(server1[0], Integer.parseInt(server1[1]))); }// w ww.j av a2s . c o m Builder builder = MongoClientOptions.builder(); builder.socketKeepAlive(true); builder.readPreference(ReadPreference.secondaryPreferred()); MongoClientOptions options = builder.build(); @SuppressWarnings("resource") MongoClient mongoClient = new MongoClient(seeds, options); return mongoClient.getDatabase(databaseName); }
From source file:com.bacic5i5j.framework.database.MongoContext.java
License:Open Source License
public void init(String db, String username, String password, List servers) { this.dbname = db; MongoCredential mc = MongoCredential.createMongoCRCredential(username, dbname, password.toCharArray()); List mcs = new ArrayList(); mcs.add(mc);//from ww w . j a v a 2 s . c o m MongoClientOptions options = MongoClientOptions.builder().connectionsPerHost(100).connectTimeout(10 * 1000) .readPreference(ReadPreference.secondaryPreferred()).build(); this.mongoClient = new MongoClient(servers, mcs, options); this.threadLocal = new ThreadLocal<DB>(); }
From source file:com.bluedragon.mongo.MongoDSN.java
License:Open Source License
public static MongoClient newClient(String server, String user, String pass, String db) throws UnknownHostException { MongoClientOptions options = MongoClientOptions.builder() .readPreference(ReadPreference.secondaryPreferred()).build(); List<InetSocketAddress> serverList = AddrUtil.getAddresses(server); List<ServerAddress> addrs = new ArrayList<ServerAddress>(); Iterator<InetSocketAddress> it = serverList.iterator(); while (it.hasNext()) { InetSocketAddress isa = it.next(); addrs.add(new ServerAddress(isa.getAddress(), isa.getPort())); }/*from w ww .j a v a 2 s.c o m*/ if (user != null) { MongoCredential cred = MongoCredential.createCredential(user, db, pass.toCharArray()); List<MongoCredential> creds = new ArrayList<MongoCredential>(); creds.add(cred); return new MongoClient(addrs, creds, options); } else { return new MongoClient(addrs, options); } }
From source file:com.dawsonsystems.session.MongoManager.java
License:Apache License
private void initDbConnection(String path) throws LifecycleException { try {/*w ww . ja v a 2 s .c o m*/ String[] hosts = getHost().split(","); List<ServerAddress> addrs = new ArrayList<>(); for (String host : hosts) { addrs.add(new ServerAddress(host, getPort())); } mongo = new MongoClient(addrs, MongoClientOptions.builder().description("TomcatMongoSession[path=" + path + "]") .alwaysUseMBeans(true).connectionsPerHost(connectionsPerHost).build()); db = mongo.getDatabase(getDatabase()); if (slaveOk) { db.withReadPreference(ReadPreference.secondaryPreferred()); } db.withWriteConcern(WriteConcern.ACKNOWLEDGED); getCollection().createIndex(new BasicDBObject("lastmodified", 1)); log.info("Connected to Mongo " + host + "/" + database + " for session storage, slaveOk=" + slaveOk + ", " + (getMaxInactiveInterval() * 1000) + " session live time"); } catch (RuntimeException e) { e.printStackTrace(); throw new LifecycleException("Error Connecting to Mongo", e); } }
From source file:com.edgytech.umongo.ConnectDialog.java
License:Apache License
MongoClientOptions getMongoClientOptions() { MongoClientOptions.Builder builder = MongoClientOptions.builder(); // moptions.connectionsPerHost = getIntFieldValue(Item.connectionsPerHost); // moptions.threadsAllowedToBlockForConnectionMultiplier = getIntFieldValue(Item.blockingThreadMultiplier); // moptions.maxWaitTime = getIntFieldValue(Item.maxWaitTime); builder.connectTimeout(getIntFieldValue(Item.connectTimeout)); builder.socketTimeout(getIntFieldValue(Item.socketTimeout)); // moptions.autoConnectRetry = getBooleanFieldValue(Item.autoConnectRetry); if (!getBooleanFieldValue(Item.safeWrites)) { builder.writeConcern(WriteConcern.NONE); }/* w w w. j ava2s. c o m*/ // moptions.slaveOk = getBooleanFieldValue(Item.secondaryReads); if (getBooleanFieldValue(Item.secondaryReads)) { builder.readPreference(ReadPreference.secondaryPreferred()); } int stype = getIntFieldValue(Item.socketType); int proxy = getIntFieldValue(Item.proxyType); if (proxy == 1) { // SOCKS proxy final String host = getStringFieldValue(Item.proxyHost); final int port = getIntFieldValue(Item.proxyPort); builder.socketFactory(new SocketFactory() { @Override public Socket createSocket() throws IOException { SocketAddress addr = new InetSocketAddress(host, port); Proxy proxy = new Proxy(Proxy.Type.SOCKS, addr); Socket socket = new Socket(proxy); return socket; } @Override public Socket createSocket(String string, int i) throws IOException, UnknownHostException { SocketAddress addr = new InetSocketAddress(host, port); Proxy proxy = new Proxy(Proxy.Type.SOCKS, addr); Socket socket = new Socket(proxy); InetSocketAddress dest = new InetSocketAddress(string, i); socket.connect(dest); return socket; } @Override public Socket createSocket(String string, int i, InetAddress ia, int i1) throws IOException, UnknownHostException { throw new UnsupportedOperationException("Not supported yet."); } @Override public Socket createSocket(InetAddress ia, int i) throws IOException { SocketAddress addr = new InetSocketAddress(host, port); Proxy proxy = new Proxy(Proxy.Type.SOCKS, addr); Socket socket = new Socket(proxy); InetSocketAddress dest = new InetSocketAddress(ia, i); socket.connect(dest); return socket; } @Override public Socket createSocket(InetAddress ia, int i, InetAddress ia1, int i1) throws IOException { throw new UnsupportedOperationException("Not supported yet."); } }); // // authentication.. only supports 1 global for all proxies :( // final String user = getStringFieldValue(Item.proxyUser); // final String pwd = getStringFieldValue(Item.proxyPassword); // if (!user.isEmpty()) { // Authenticator.setDefault(new Authenticator() { // @Override // protected PasswordAuthentication getPasswordAuthentication() { // PasswordAuthentication p = new PasswordAuthentication(user, pwd.toCharArray()); // return p; // } // }); // } } if (stype == 1) { builder.socketFactory(SSLSocketFactory.getDefault()); } else if (stype == 2) { // Create a trust manager that does not validate certificate chains TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; } public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) { } public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) { } } }; try { SSLContext sc = SSLContext.getInstance("SSL"); sc.init(null, trustAllCerts, new java.security.SecureRandom()); builder.socketFactory(sc.getSocketFactory()); } catch (Exception e) { } } return builder.build(); }
From source file:com.ikanow.infinit.e.api.knowledge.QueryHandler.java
License:Open Source License
private DBCursor getDocIds(DBCollection docDb, ObjectId[] ids, int nFromServerLimit, AdvancedQueryPojo.QueryOutputPojo output, AdvancedQueryPojo.QueryScorePojo score) { DBCursor docdCursor = null;/*from www . j av a 2 s . c o m*/ try { BasicDBObject query = new BasicDBObject(); query.put("_id", new BasicDBObject("$in", ids)); BasicDBObject fields = new BasicDBObject(DocumentPojo.fullText_, 0); // (used to discard community ids -plus legacy versions-, now need it) if (!output.docs.metadata) { fields.put(DocumentPojo.metadata_, 0); } boolean bNotAggEnts = ((output.aggregation == null) || (output.aggregation.entsNumReturn == null) || (output.aggregation.entsNumReturn == 0)); if (bNotAggEnts && (null != score) && (null != score.sigWeight) && (score.sigWeight > 0.0)) { bNotAggEnts = false; // (special case, use agg entities to score docs) } if (!output.docs.ents && bNotAggEnts) { fields.put(DocumentPojo.entities_, 0); } boolean bNotAggEvents = ((output.aggregation == null) || (output.aggregation.eventsNumReturn == null) || (output.aggregation.eventsNumReturn == 0)); boolean bNotAggFacts = ((output.aggregation == null) || (output.aggregation.factsNumReturn == null) || (output.aggregation.factsNumReturn == 0)); boolean bNoStandaloneEvents = (null == output.docs.eventsTimeline) || (null == output.docs.numEventsTimelineReturn) || (output.docs.numEventsTimelineReturn == 0); if (!output.docs.events && !output.docs.facts && !output.docs.summaries && bNoStandaloneEvents && bNotAggEvents && bNotAggFacts) { fields.put(DocumentPojo.associations_, 0); } //TESTED //cm = new CollectionManager(); boolean bPrimary = true; if (_replicaSetDistributionRatio > 0) { if (0 != (new Date().getTime() % _replicaSetDistributionRatio)) { bPrimary = false; } } if (bPrimary) { // Get from the primary docdCursor = docDb.find(query, fields).batchSize(nFromServerLimit); } else { // Try and get from the secondary if possible docdCursor = docDb.find(query, fields).batchSize(nFromServerLimit) .setReadPreference(ReadPreference.secondaryPreferred()); } } catch (Exception e) { // If an exception occurs log the error _logger.error("Address Exception Message: " + e.getMessage(), e); } return docdCursor; }
From source file:com.ikanow.infinit.e.data_model.store.MongoDbConnection.java
License:Apache License
/** * Class Constructor used to establish the mongo object * //from w w w . j a v a2s .c om * @param server the server location ( example localhost ) * @param port the port number ( example 27017 * @throws MongoException * @throws UnknownHostException */ public MongoDbConnection(PropertiesManager properties) throws UnknownHostException, MongoException { if (null != properties) { this.server = properties.getDatabaseServer(); this.port = properties.getDatabasePort(); } mongo = new Mongo(this.server, this.port); if (null != properties) { if (properties.getDistributeAllDbReadsAcrossSlaves()) { mongo.setReadPreference(ReadPreference.secondaryPreferred()); } } }
From source file:com.ikanow.infinit.e.harvest.extraction.document.DuplicateManager_Integrated.java
License:Open Source License
private LinkedList<String> getCandidateDuplicates(BasicDBObject query, String parentSourceKey, boolean bUpdate) { _modifiedTimeOfActualDuplicate = null; _duplicateId = null;//from w w w . j a v a 2 s . c om LinkedList<String> returnVal = new LinkedList<String>(); DBCollection collection = DbManager.getDocument().getMetadata(); BasicDBObject fields = new BasicDBObject(DocumentPojo.sourceKey_, 1); if (bUpdate) { fields.put(DocumentPojo.modified_, 1); fields.put(DocumentPojo.updateId_, 1); } //TESTED boolean bPrimary = true; if (_replicaSetDistributionRatio > 0) { // (distribute based on source key, should ensure some reasonable cache grouping...) if (0 != (parentSourceKey.hashCode() % _replicaSetDistributionRatio)) { bPrimary = false; } } DBCursor dbc = null; if (bPrimary) { dbc = collection.find(query, fields); } else { dbc = collection.find(query, fields).setReadPreference(ReadPreference.secondaryPreferred()); } while (dbc.hasNext()) { DBObject dbo = dbc.next(); String sourceKey = DocumentPojo.getSourceKey((String) dbo.get(DocumentPojo.sourceKey_)); if (null != sourceKey) { // Check for exact duplicates, in which case can bypass horrible functional duplicate logic: boolean bFoundExactDuplicate = sourceKey.equals(parentSourceKey); // Update logic: if (bUpdate && bFoundExactDuplicate) { _modifiedTimeOfActualDuplicate = (Date) dbo.get(DocumentPojo.modified_); _duplicateId = (ObjectId) dbo.get(DocumentPojo.updateId_); if (null == _duplicateId) { // first time, use the _id _duplicateId = (ObjectId) dbo.get(DocumentPojo._id_); } } //TESTED if (bFoundExactDuplicate) { // Found exact duplicate, so return just that for performance returnVal.clear(); } returnVal.add(sourceKey); if (bFoundExactDuplicate) { // Found exact duplicate, we're done here return returnVal; } } //(if doc has source key, else is malformed, ignore) } //(end loop over URL-duplicates) return returnVal; }
From source file:com.navercorp.pinpoint.plugin.mongodb.MongoDBIT_3_0_x_IT.java
License:Apache License
@Override public void setClient() { mongoClient = new com.mongodb.MongoClient("localhost", 27018); database = mongoClient.getDatabase("myMongoDbFake").withReadPreference(ReadPreference.secondaryPreferred()) .withWriteConcern(WriteConcern.MAJORITY); }