List of usage examples for com.mongodb ReadPreference secondaryPreferred
public static ReadPreference secondaryPreferred()
From source file:org.codinjutsu.tools.mongo.view.ServerConfigurationPanel.java
License:Apache License
public ServerConfigurationPanel(Project project, MongoManager mongoManager) { this.project = project; setLayout(new BorderLayout()); add(rootPanel, BorderLayout.CENTER); this.mongoManager = mongoManager; labelField.setName("labelField"); feedbackLabel.setName("feedbackLabel"); sslConnectionField.setName("sslConnectionField"); readPreferenceComboBox.setName("readPreferenceComboBox"); authenticationPanel.setBorder(IdeBorderFactory.createTitledBorder("Authentication settings", true)); serverUrlsField.setName("serverUrlsField"); usernameField.setName("usernameField"); passwordField.setName("passwordField"); mongoCRAuthRadioButton.setName("mongoCRAuthField"); scramSHA1AuthRadioButton.setName("scramSHA1AuthField"); defaultAuthMethodRadioButton.setName("defaultAuthMethod"); userDatabaseField.setName("userDatabaseField"); userDatabaseField.setToolTipText(//from w w w . j a v a2 s.c o m "If your access is restricted to a specific database (e.g.: MongoLab), you can set it right here"); autoConnectCheckBox.setName("autoConnectField"); mongoShellOptionsPanel.setBorder(IdeBorderFactory.createTitledBorder("Mongo shell options", true)); shellArgumentsLineField.setDialogCaption("Mongo arguments"); testConnectionButton.setName("testConnection"); connectionOptionPanel.setBorder(IdeBorderFactory.createTitledBorder("Connection Settings", true)); readPreferenceComboBox.setModel(new DefaultComboBoxModel<>(new ReadPreference[] { ReadPreference.primary(), ReadPreference.primaryPreferred(), ReadPreference.secondary(), ReadPreference.secondaryPreferred(), ReadPreference.nearest() })); readPreferenceComboBox.setRenderer(new ColoredListCellRenderer() { @Override protected void customizeCellRenderer(JList list, Object value, int index, boolean selected, boolean hasFocus) { ReadPreference readPreference = (ReadPreference) value; append(readPreference.getName()); } }); readPreferenceComboBox.setSelectedItem(ReadPreference.primary()); authMethodGroup = new ButtonGroup(); authMethodGroup.add(mongoCRAuthRadioButton); authMethodGroup.add(scramSHA1AuthRadioButton); authMethodGroup.add(defaultAuthMethodRadioButton); defaultAuthMethodRadioButton.setSelected(true); defaultAuthMethodRadioButton.setToolTipText("Let the driver resolves the auth. mechanism"); shellWorkingDirField.setText(null); initListeners(); }
From source file:org.datanucleus.store.mongodb.MongoDBUtils.java
License:Open Source License
/** * Convenience method to return all objects of the candidate type (optionally allowing subclasses). * @param q Query//ww w. ja v a2 s. c o m * @param db Mongo DB * @param filterObject Optional filter object * @param orderingObject Optional ordering object * @param options Set of options for controlling this query * @param skip Number of records to skip * @param limit Max number of records to return * @return List of all candidate objects (implements QueryResult) */ public static List getObjectsOfCandidateType(Query q, DB db, BasicDBObject filterObject, BasicDBObject orderingObject, Map<String, Object> options, Integer skip, Integer limit) { LazyLoadQueryResult qr = new LazyLoadQueryResult(q); // Find the DBCollections we need to query ExecutionContext ec = q.getExecutionContext(); StoreManager storeMgr = ec.getStoreManager(); ClassLoaderResolver clr = ec.getClassLoaderResolver(); List<AbstractClassMetaData> cmds = MetaDataUtils.getMetaDataForCandidates(q.getCandidateClass(), q.isSubclasses(), ec); Map<String, List<AbstractClassMetaData>> classesByCollectionName = new HashMap(); for (AbstractClassMetaData cmd : cmds) { if (cmd instanceof ClassMetaData && ((ClassMetaData) cmd).isAbstract()) { // Omit any classes that are not instantiable (e.g abstract) } else { String collectionName = storeMgr.getNamingFactory().getTableName(cmd); List<AbstractClassMetaData> cmdsForCollection = classesByCollectionName.get(collectionName); if (cmdsForCollection == null) { cmdsForCollection = new ArrayList(); classesByCollectionName.put(collectionName, cmdsForCollection); } cmdsForCollection.add(cmd); } } // Add a query for each DBCollection we need Iterator<Map.Entry<String, List<AbstractClassMetaData>>> iter = classesByCollectionName.entrySet() .iterator(); while (iter.hasNext()) { Map.Entry<String, List<AbstractClassMetaData>> entry = iter.next(); String collectionName = entry.getKey(); List<AbstractClassMetaData> cmdsForCollection = entry.getValue(); AbstractClassMetaData rootCmd = cmdsForCollection.get(0); int[] fpMembers = q.getFetchPlan().getFetchPlanForClass(rootCmd).getMemberNumbers(); BasicDBObject fieldsSelection = new BasicDBObject(); if (fpMembers != null && fpMembers.length > 0) { fieldsSelection = new BasicDBObject(); for (int i = 0; i < fpMembers.length; i++) { AbstractMemberMetaData mmd = rootCmd .getMetaDataForManagedMemberAtAbsolutePosition(fpMembers[i]); RelationType relationType = mmd.getRelationType(clr); if (mmd.isEmbedded() && RelationType.isRelationSingleValued(relationType)) { boolean nested = true; String nestedStr = mmd.getValueForExtension("nested"); if (nestedStr != null && nestedStr.equalsIgnoreCase("false")) { nested = false; } if (nested) { // Nested Embedded field, so include field String fieldName = storeMgr.getNamingFactory().getColumnName(mmd, ColumnType.COLUMN); fieldsSelection.append(fieldName, 1); } else { // Flat Embedded field, so add all fields of sub-objects selectAllFieldsOfEmbeddedObject(mmd, fieldsSelection, ec, clr); } } else { String fieldName = storeMgr.getNamingFactory().getColumnName(mmd, ColumnType.COLUMN); fieldsSelection.append(fieldName, 1); } } } if (rootCmd.getIdentityType() == IdentityType.DATASTORE) { fieldsSelection.append( storeMgr.getNamingFactory().getColumnName(rootCmd, ColumnType.DATASTOREID_COLUMN), 1); } if (rootCmd.isVersioned()) { VersionMetaData vermd = rootCmd.getVersionMetaDataForClass(); if (vermd.getFieldName() != null) { AbstractMemberMetaData verMmd = rootCmd.getMetaDataForMember(vermd.getFieldName()); String fieldName = storeMgr.getNamingFactory().getColumnName(verMmd, ColumnType.COLUMN); fieldsSelection.append(fieldName, 1); } else { fieldsSelection.append( storeMgr.getNamingFactory().getColumnName(rootCmd, ColumnType.VERSION_COLUMN), 1); } } if (rootCmd.hasDiscriminatorStrategy()) { fieldsSelection.append( storeMgr.getNamingFactory().getColumnName(rootCmd, ColumnType.DISCRIMINATOR_COLUMN), 1); } BasicDBObject query = new BasicDBObject(); if (filterObject != null) { Iterator<Map.Entry<String, Object>> filterEntryIter = filterObject.entrySet().iterator(); while (filterEntryIter.hasNext()) { Map.Entry<String, Object> filterEntry = filterEntryIter.next(); query.put(filterEntry.getKey(), filterEntry.getValue()); } } if (rootCmd.hasDiscriminatorStrategy() && cmdsForCollection.size() == 1) { // TODO Add this restriction on *all* possible cmds for this DBCollection // Discriminator present : Add restriction on the discriminator value for this class query.put(storeMgr.getNamingFactory().getColumnName(rootCmd, ColumnType.DISCRIMINATOR_COLUMN), rootCmd.getDiscriminatorValue()); } if (storeMgr.getStringProperty(PropertyNames.PROPERTY_TENANT_ID) != null) { // Multitenancy discriminator present : Add restriction for this tenant if ("true".equalsIgnoreCase(rootCmd.getValueForExtension("multitenancy-disable"))) { // Don't bother with multitenancy for this class } else { String fieldName = storeMgr.getNamingFactory().getColumnName(rootCmd, ColumnType.MULTITENANCY_COLUMN); String value = storeMgr.getStringProperty(PropertyNames.PROPERTY_TENANT_ID); query.put(fieldName, value); } } DBCollection dbColl = db.getCollection(collectionName); Object val = (options != null ? options.get("slave-ok") : Boolean.FALSE); if (val == Boolean.TRUE) { dbColl.setReadPreference(ReadPreference.secondaryPreferred()); } if (NucleusLogger.DATASTORE_NATIVE.isDebugEnabled()) { NucleusLogger.DATASTORE_NATIVE .debug("Performing find() using query on collection " + collectionName + " for fields=" + fieldsSelection + " with filter=" + query + " and ordering=" + orderingObject); } DBCursor curs = dbColl.find(query, fieldsSelection); if (ec.getStatistics() != null) { // Add to statistics ec.getStatistics().incrementNumReads(); } if (classesByCollectionName.size() == 1) { if (orderingObject != null) { curs = curs.sort(orderingObject); qr.setOrderProcessed(true); } // We have a single DBCursor so apply the range specification directly to this DBCursor if (skip != null && skip > 0) { curs = curs.skip(skip); qr.setRangeProcessed(true); } if (limit != null && limit > 0) { curs = curs.limit(limit); qr.setRangeProcessed(true); } } qr.addCandidateResult(rootCmd, curs, fpMembers); } return qr; }
From source file:org.eclipse.ditto.services.thingsearch.persistence.read.MongoThingsSearchPersistence.java
License:Open Source License
/** * Initializes the things search persistence with a passed in {@code persistence}. * * @param mongoClient the mongoDB persistence wrapper. * @param actorSystem the Akka ActorSystem. *//* w ww. ja v a2 s.com*/ public MongoThingsSearchPersistence(final DittoMongoClient mongoClient, final ActorSystem actorSystem) { final MongoDatabase database = mongoClient.getDefaultDatabase(); // configure search persistence to stress the primary as little as possible and tolerate inconsistency collection = database.getCollection(PersistenceConstants.THINGS_COLLECTION_NAME) .withReadPreference(ReadPreference.secondaryPreferred()); log = Logging.getLogger(actorSystem, getClass()); final ActorMaterializer materializer = ActorMaterializer.create(actorSystem); indexInitializer = IndexInitializer.of(database, materializer); maxQueryTime = mongoClient.getDittoSettings().getMaxQueryTime(); hints = MongoHints.empty(); }
From source file:org.elasticsearch.river.mongodb.RiverMongoDBTestAbstract.java
License:Apache License
private void initMongoInstances(ExecutableType type) throws Exception { logger.debug("*** initMongoInstances(" + type + ") ***"); CommandResult cr;/*from w ww. j av a 2 s.co m*/ Settings rsSettings = settings.getByPrefix(type.configKey + '.'); int[] ports; if (rsSettings.getAsBoolean("useDynamicPorts", false)) { ports = new int[] { Network.getFreeServerPort(), Network.getFreeServerPort(), Network.getFreeServerPort() }; } else { int start = 37017 + 10 * type.ordinal(); ports = new int[] { start, start + 1, start + 2 }; } String replicaSetName = "es-test-" + type.configKey; // Create 3 mongod processes Starter<IMongodConfig, MongodExecutable, MongodProcess> starter = type.newStarter(); ImmutableList.Builder<MongoReplicaSet.Member> builder = ImmutableList.builder(); for (int i = 1; i <= 3; ++i) { Storage storage = new Storage("target/" + replicaSetName + '/' + i, replicaSetName, 20); MongoReplicaSet.Member member = new MongoReplicaSet.Member(); member.config = new MongodConfigBuilder() .version(Versions.withFeatures(new GenericVersion(rsSettings.get("version")))) .net(new de.flapdoodle.embed.mongo.config.Net(ports[i - 1], Network.localhostIsIPv6())) .replication(storage).build(); logger.trace("replSetName in config: {}", member.config.replication().getReplSetName()); member.executable = starter.prepare(member.config); member.process = member.executable.start(); member.address = new ServerAddress(Network.getLocalHost().getHostName(), member.config.net().getPort()); logger.debug("Server #" + i + ": {}", member.address); builder.add(member); } ImmutableList<MongoReplicaSet.Member> members = builder.build(); Thread.sleep(2000); MongoClientOptions mco = MongoClientOptions.builder().autoConnectRetry(true).connectTimeout(15000) .socketTimeout(60000).build(); Mongo mongo = new MongoClient(new ServerAddress(Network.getLocalHost().getHostName(), ports[0]), mco); DB mongoAdminDB = mongo.getDB(ADMIN_DATABASE_NAME); cr = mongoAdminDB.command(new BasicDBObject("isMaster", 1)); logger.debug("isMaster: " + cr); // Initialize replica set cr = mongoAdminDB.command(new BasicDBObject("replSetInitiate", (DBObject) JSON.parse("{'_id': '" + replicaSetName + "', 'members': [" + "{'_id': 0, 'host': '" + members.get(0).address.getHost() + ':' + members.get(0).address.getPort() + "'}, " + "{'_id': 1, 'host': '" + members.get(1).address.getHost() + ':' + members.get(1).address.getPort() + "'}, " + "{'_id': 2, 'host': '" + members.get(2).address.getHost() + ':' + members.get(2).address.getPort() + "', 'arbiterOnly' : true}]} }"))); logger.debug("replSetInitiate result: " + cr); Thread.sleep(5000); cr = mongoAdminDB.command(new BasicDBObject("replSetGetStatus", 1)); logger.trace("replSetGetStatus result: {}", cr); // Check replica set status before to proceed while (!isReplicaSetStarted(cr)) { logger.debug("Waiting 3 seconds for replicaset to change status..."); Thread.sleep(3000); cr = mongoAdminDB.command(new BasicDBObject("replSetGetStatus", 1)); // logger.debug("replSetGetStatus: " + cr); } mongo.close(); mongo = null; // Initialize a new client using all instances. List<ServerAddress> mongoServers = new ArrayList<ServerAddress>(); for (MongoReplicaSet.Member member : members) { mongoServers.add(member.address); } mongo = new MongoClient(mongoServers, mco); Assert.assertNotNull(mongo); mongo.setReadPreference(ReadPreference.secondaryPreferred()); mongo.setWriteConcern(WriteConcern.REPLICAS_SAFE); replicaSets.put(type, new MongoReplicaSet(type, rsSettings.get("version"), mongo, mongoAdminDB, members)); }
From source file:org.hbr.session.store.MongoStore.java
License:Apache License
/** * Create the {@link MongoClient}.// ww w . ja v a 2s . c om * @throws LifecycleException */ private void getConnection() throws LifecycleException { try { /* create our MongoClient */ if (this.connectionUri != null) { manager.getContainer().getLogger().info(getStoreName() + "[" + this.getName() + "]: Connecting to MongoDB [" + this.connectionUri + "]"); this.mongoClient = new MongoClient(this.connectionUri); } else { /* create the client using the Mongo options */ ReadPreference readPreference = ReadPreference.primaryPreferred(); if (this.useSlaves) { readPreference = ReadPreference.secondaryPreferred(); } MongoClientOptions options = MongoClientOptions.builder().connectTimeout(connectionTimeoutMs) .maxWaitTime(connectionWaitTimeoutMs).connectionsPerHost(maxPoolSize) .writeConcern(writeConcern).readPreference(readPreference).build(); /* build up the host list */ List<ServerAddress> hosts = new ArrayList<ServerAddress>(); String[] dbHosts = this.hosts.split(","); for (String dbHost : dbHosts) { String[] hostInfo = dbHost.split(":"); ServerAddress address = new ServerAddress(hostInfo[0], Integer.parseInt(hostInfo[1])); hosts.add(address); } this.manager.getContainer().getLogger().info( getStoreName() + "[" + this.getName() + "]: Connecting to MongoDB [" + this.hosts + "]"); /* connect */ this.mongoClient = new MongoClient(hosts, options); } /* get a connection to our db */ this.manager.getContainer().getLogger() .info(getStoreName() + "[" + this.getName() + "]: Using Database [" + this.dbName + "]"); this.db = this.mongoClient.getDB(this.dbName); /* see if we need to authenticate */ if (this.username != null || this.password != null) { this.manager.getContainer().getLogger().info( getStoreName() + "[" + this.getName() + "]: Authenticating using [" + this.username + "]"); if (!this.db.authenticate(this.username, this.password.toCharArray())) { throw new RuntimeException("MongoDB Authentication Failed"); } } /* get a reference to the collection */ this.collection = this.db.getCollection(this.collectionName); this.manager.getContainer().getLogger() .info(getStoreName() + "[" + this.getName() + "]: Preparing indexes"); /* drop any existing indexes */ try { this.collection.dropIndex(new BasicDBObject(lastModifiedProperty, 1)); this.collection.dropIndex(new BasicDBObject(appContextProperty, 1)); } catch (Exception e) { /* these indexes may not exist, so ignore */ } /* make sure the last modified and app name indexes exists */ this.collection.ensureIndex(new BasicDBObject(appContextProperty, 1)); /* determine if we need to expire our db sessions */ if (this.timeToLive != -1) { /* use the time to live set */ this.collection.ensureIndex(new BasicDBObject(lastModifiedProperty, 1), new BasicDBObject("lastModifiedProperty", this.timeToLive)); } else { /* no custom time to live specified, use the manager's settings */ if (this.manager.getMaxInactiveInterval() != -1) { /* create a ttl index on the app property */ this.collection.ensureIndex(new BasicDBObject(lastModifiedProperty, 1), new BasicDBObject("lastModifiedProperty", this.manager.getMaxInactiveInterval())); } else { /* create a regular index */ this.collection.ensureIndex(new BasicDBObject(lastModifiedProperty, 1)); } } this.manager.getContainer().getLogger().info(getStoreName() + "[" + this.getName() + "]: Store ready."); } catch (UnknownHostException uhe) { this.manager.getContainer().getLogger().error("Unable to Connect to MongoDB", uhe); throw new LifecycleException(uhe); } catch (MongoException me) { this.manager.getContainer().getLogger().error("Unable to Connect to MongoDB", me); throw new LifecycleException(me); } }
From source file:org.mongodb.tse.tests.RunQueryThreadPool.java
public static MongoCollection getCollection(CommandLine cline, MongoDatabase database, String collectionParameter) { MongoCollection collection = null;/*from w w w.java2 s.c o m*/ if (cline.hasOption("readPreference")) { String p = cline.getOptionValue("readPreference"); collection = database.getCollection(collectionParameter).withReadPreference(ReadPreference.valueOf(p)); } else collection = database.getCollection(collectionParameter) .withReadPreference(ReadPreference.secondaryPreferred()); return collection; }
From source file:org.mongodb.tse.tests.Timings.java
public static void main(String[] args) throws ParseException { Option help = Option.builder("help").argName("help").desc("get help").build(); Option test = Option.builder("test").argName("test").desc("quick test").build(); Option ouri = Option.builder("uri").argName("uri").desc("mongodb uri, required").hasArg().type(String.class) .build();//from w w w. j ava2 s .com Option odatabase = Option.builder("database").argName("database") .desc("mongodb database, default productpersistdb").hasArg().type(String.class).build(); Option ocollection = Option.builder("collection").argName("collection") .desc("mongodb collection, default product").hasArg().type(String.class).build(); Option osleep = Option.builder("sleep").argName("sleep").desc("sleep between runs, default 10 seconds") .hasArg().type(Integer.class).build(); Option otimes = Option.builder("times").argName("times").desc("number of times to run, default 100") .hasArg().type(Integer.class).build(); Option readPreference = Option.builder("readPreference").argName("readPreference") .desc("read preference, default is secondaryPreferred").hasArg().type(String.class).build(); Option oids = Option.builder("ids").argName("ids").desc("list of comma separated ids").hasArg() .type(String.class).build(); Option oidFile = Option.builder("idFile").argName("idFile").desc("file containing ids per line").hasArg() .type(String.class).build(); Option odoc = Option.builder("doc").argName("doc") .desc("get a Document instead of RawBsonDocument, no size output with this option").build(); Options options = new Options(); options.addOption(help); options.addOption(test); options.addOption(ouri); options.addOption(odatabase); options.addOption(ocollection); options.addOption(osleep); options.addOption(otimes); options.addOption(readPreference); options.addOption(oids); options.addOption(oidFile); options.addOption(odoc); CommandLineParser parser = new DefaultParser(); CommandLine cline = null; try { // parse the command line arguments cline = parser.parse(options, args); } catch (ParseException exp) { // oops, something went wrong System.err.println("Parsing failed. Reason: " + exp.getMessage()); } if (args.length == 0 || cline.hasOption("help") || !cline.hasOption("uri")) { printHelp(options); } if (cline.hasOption("test")) { List<Double> testList = new ArrayList<Double>(); for (int i = 0; i < 100; i++) { testList.add(new Double(i)); } Collections.sort(testList); System.out.println(String.format("P50: %.2f, P75: %.2f, P90: %.2f, P95: %.2f, P99: %.2f", percentile(testList, 0.50), percentile(testList, 0.75), percentile(testList, 0.90), percentile(testList, 0.95), percentile(testList, 0.99))); System.exit(0); } String[] ids = null; if (cline.hasOption("idFile")) { ids = parseIdFile(new File(cline.getOptionValue("idFile"))); } else ids = cline.getOptionValue("ids", "517886481000").split(","); List<Double> timeList = new ArrayList<>(); String uriParameter = cline.getOptionValue("uri"); String databaseParameter = cline.getOptionValue("database", "productpersistdb"); String collectionParameter = cline.getOptionValue("collection", "product"); System.out.println("Using database: " + databaseParameter + " and collection: " + collectionParameter); MongoClientURI uri = new MongoClientURI(uriParameter); MongoClient mongoClient = new MongoClient(uri); MongoDatabase database = mongoClient.getDatabase(databaseParameter); MongoCollection<Document> collection = null; MongoCollection<RawBsonDocument> rawCollection = null; boolean doDoc = cline.hasOption("doc"); if (doDoc) { if (cline.hasOption("readPreference")) { String p = cline.getOptionValue("readPreference"); collection = database.getCollection(collectionParameter) .withReadPreference(ReadPreference.valueOf(p)); } else collection = database.getCollection(collectionParameter) .withReadPreference(ReadPreference.secondaryPreferred()); } else { if (cline.hasOption("readPreference")) { String p = cline.getOptionValue("readPreference"); rawCollection = database.getCollection(collectionParameter, RawBsonDocument.class) .withReadPreference(ReadPreference.valueOf(p)); } else rawCollection = database.getCollection(collectionParameter, RawBsonDocument.class) .withReadPreference(ReadPreference.secondaryPreferred()); } long sleep = 10000; if (cline.hasOption("sleep")) sleep = Integer.parseInt(cline.getOptionValue("sleep")) * 1000; int times = 100; if (cline.hasOption("times")) times = Integer.parseInt(cline.getOptionValue("times")); int count = 0; int max = ids.length; while (count < times) { String id = ids[(count % max)]; Document doc = null; RawBsonDocument raw = null; Date date = new Date(); long end = 0L; long start = System.nanoTime(); if (doDoc) { doc = collection.find(eq("_id", id)).first(); end = System.nanoTime(); if (doc == null) System.out.println("Could not find " + id); } else { raw = rawCollection.find(eq("_id", id)).first(); end = System.nanoTime(); if (raw == null) System.out.println("Could not find " + id); } int size = 0; if (raw != null) size = raw.getByteBuffer().capacity(); if (raw != null) { System.out.println(String.format("id: %s, start: %s, elasped: %s ns, docSize: %s", id, date, (end - start), size)); } else { System.out.println(String.format("id: %s, start: %s, elasped: %s ns", id, date, (end - start))); } timeList.add(new Double(end - start)); try { Thread.sleep(sleep); } catch (InterruptedException e) { } count++; } Collections.sort(timeList); System.out.println(String.format("P50: %.2f, P75: %.2f, P90: %.2f, P95: %.2f, P99: %.2f", percentile(timeList, 0.50), percentile(timeList, 0.75), percentile(timeList, 0.90), percentile(timeList, 0.95), percentile(timeList, 0.99))); }
From source file:org.slc.sli.bulk.extract.SecondaryReadRepository.java
License:Apache License
/** * Method to set read preference of the mongo template. * * @param firstTag/*from ww w .j a va 2 s . c om*/ * map representing the first tag * @param remainingTags * map representing the remaining tags */ private void setReadPreference(DBObject firstTag, DBObject... remainingTags) { ReadPreference readPreference; if (firstTag == null) { LOG.info("Setting up database preferences to read from secondary"); readPreference = failOnPrimary ? ReadPreference.secondary() : ReadPreference.secondaryPreferred(); } else if (remainingTags == null) { LOG.info("Setting up database preferences to read from secondary with respect to the tag set provided"); readPreference = failOnPrimary ? ReadPreference.secondary(firstTag) : ReadPreference.secondaryPreferred(firstTag); } else { LOG.info( "Setting up database preferences to read from secondary with respect to the tag sets provided"); readPreference = failOnPrimary ? ReadPreference.secondary(firstTag, remainingTags) : ReadPreference.secondaryPreferred(firstTag, remainingTags); } template.setReadPreference(readPreference); }
From source file:org.springframework.data.mongodb.config.ReadPreferencePropertyEditor.java
License:Apache License
@Override public void setAsText(String readPreferenceString) throws IllegalArgumentException { if (readPreferenceString == null) { return;//from w ww.j a v a 2 s . c o m } ReadPreference preference = null; try { preference = ReadPreference.valueOf(readPreferenceString); } catch (IllegalArgumentException ex) { // ignore this one and try to map it differently } if (preference != null) { setValue(preference); } else if ("PRIMARY".equalsIgnoreCase(readPreferenceString)) { setValue(ReadPreference.primary()); } else if ("PRIMARY_PREFERRED".equalsIgnoreCase(readPreferenceString)) { setValue(ReadPreference.primaryPreferred()); } else if ("SECONDARY".equalsIgnoreCase(readPreferenceString)) { setValue(ReadPreference.secondary()); } else if ("SECONDARY_PREFERRED".equalsIgnoreCase(readPreferenceString)) { setValue(ReadPreference.secondaryPreferred()); } else if ("NEAREST".equalsIgnoreCase(readPreferenceString)) { setValue(ReadPreference.nearest()); } else { throw new IllegalArgumentException( String.format("Cannot find matching ReadPreference for %s", readPreferenceString)); } }
From source file:org.springframework.data.mongodb.core.MongoTemplate.java
License:Apache License
@Deprecated public CommandResult executeCommand(final DBObject command, final int options) { return executeCommand(command, (options & Bytes.QUERYOPTION_SLAVEOK) != 0 ? ReadPreference.secondaryPreferred() : ReadPreference.primary()); }