本文整理匯總了Java中com.mongodb.ReadPreference類的典型用法代碼示例。如果您正苦於以下問題:Java ReadPreference類的具體用法?Java ReadPreference怎麽用?Java ReadPreference使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。
ReadPreference類屬於com.mongodb包,在下文中一共展示了ReadPreference類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。
示例1: readPreference
import com.mongodb.ReadPreference; //導入依賴的package包/類
/**
* Prepares {@link ReadPreference} from given {@link ReadPreferenceEnum}
*
* @param readPreferenceEnum Read preference enum value provided in config
* @return Read preference for mongo client options
*/
public static ReadPreference readPreference(ReadPreferenceEnum readPreferenceEnum) {
switch (readPreferenceEnum) {
case NEAREST:
return ReadPreference.nearest();
case PRIMARY:
return ReadPreference.primary();
case SECONDARY:
return ReadPreference.secondary();
case PRIMARY_PREFERRED:
return ReadPreference.primaryPreferred();
case SECONDARY_PREFERRED:
return ReadPreference.secondaryPreferred();
default:
return null;
}
}
示例2: prepareClient
import com.mongodb.ReadPreference; //導入依賴的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);
}
}
示例3: toMongoClientOptions
import com.mongodb.ReadPreference; //導入依賴的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();
}
示例4: init
import com.mongodb.ReadPreference; //導入依賴的package包/類
public void init(
Stage.Context context,
List<Stage.ConfigIssue> issues,
ReadPreference readPreference,
WriteConcern writeConcern
) {
mongoClient = createClient(context, issues, readPreference, writeConcern);
if (!issues.isEmpty()) {
return;
}
mongoDatabase = createMongoDatabase(context, issues, readPreference, writeConcern);
if (!issues.isEmpty()) {
return;
}
mongoCollection = createMongoCollection(context, issues, readPreference, writeConcern);
}
示例5: createMongoDatabase
import com.mongodb.ReadPreference; //導入依賴的package包/類
private MongoDatabase createMongoDatabase(
Stage.Context context,
List<Stage.ConfigIssue> issues,
ReadPreference readPreference,
WriteConcern writeConcern
) {
MongoDatabase mongoDatabase = null;
try {
if (readPreference != null) {
mongoDatabase = mongoClient.getDatabase(database).withReadPreference(readPreference);
} else if (writeConcern != null) {
mongoDatabase = mongoClient.getDatabase(database).withWriteConcern(writeConcern);
}
} catch (MongoClientException e) {
issues.add(context.createConfigIssue(
Groups.MONGODB.name(),
MONGO_CONFIG_PREFIX + "database",
Errors.MONGODB_02,
database,
e.toString()
));
}
return mongoDatabase;
}
示例6: createMongoCollection
import com.mongodb.ReadPreference; //導入依賴的package包/類
private MongoCollection createMongoCollection(
Stage.Context context,
List<Stage.ConfigIssue> issues,
ReadPreference readPreference,
WriteConcern writeConcern
) {
MongoCollection mongoCollection = null;
try {
if (readPreference != null) {
mongoCollection = mongoDatabase.getCollection(collection).withReadPreference(readPreference);
} else if (writeConcern != null) {
mongoCollection = mongoDatabase.getCollection(collection).withWriteConcern(writeConcern);
}
} catch (MongoClientException e) {
issues.add(context.createConfigIssue(
Groups.MONGODB.name(),
MONGO_CONFIG_PREFIX + "collection",
Errors.MONGODB_03,
collection,
e.toString()
));
}
return mongoCollection;
}
示例7: checkCapped
import com.mongodb.ReadPreference; //導入依賴的package包/類
public static void checkCapped(MongoDatabase database, String collectionName, int size, int maxDocuments, boolean delete) {
if (Lists.newArrayList(database.listCollectionNames()).contains(collectionName)) {
log.debug("'{}' collection already exists...", collectionName);
// Check if already capped
Document command = new Document("collStats", collectionName);
boolean isCapped = database.runCommand(command, ReadPreference.primary()).getBoolean("capped").booleanValue();
if (!isCapped) {
if (delete) {
database.getCollection(collectionName).drop();
database.createCollection(collectionName, new CreateCollectionOptions().capped(true).maxDocuments(maxDocuments).sizeInBytes(size));
} else {
log.info("'{}' is not capped, converting it...", collectionName);
command = new Document("convertToCapped", collectionName).append("size", size).append("max", maxDocuments);
database.runCommand(command, ReadPreference.primary());
}
} else {
log.debug("'{}' collection already capped!", collectionName);
}
} else {
database.createCollection(collectionName, new CreateCollectionOptions().capped(true).maxDocuments(maxDocuments).sizeInBytes(size));
}
}
示例8: getBlob
import com.mongodb.ReadPreference; //導入依賴的package包/類
private MongoBlob getBlob(String id, long lastMod) {
DBObject query = getBlobQuery(id, lastMod);
// try the secondary first
// TODO add a configuration option for whether to try reading from secondary
ReadPreference pref = ReadPreference.secondaryPreferred();
DBObject fields = new BasicDBObject();
fields.put(MongoBlob.KEY_DATA, 1);
MongoBlob blob = (MongoBlob) getBlobCollection().findOne(query, fields, pref);
if (blob == null) {
// not found in the secondary: try the primary
pref = ReadPreference.primary();
blob = (MongoBlob) getBlobCollection().findOne(query, fields, pref);
}
return blob;
}
示例9: getCandidates
import com.mongodb.ReadPreference; //導入依賴的package包/類
@Override
public CloseableIterable<NodeDocument> getCandidates(final long startTime) {
DBObject query =
start(NodeDocument.MODIFIED_IN_SECS).greaterThanEquals(
NodeDocument.getModifiedInSecs(startTime))
.get();
DBObject sortFields = new BasicDBObject(NodeDocument.MODIFIED_IN_SECS, -1);
DBCursor cursor =
getNodeCollection().find(query)
.sort(sortFields)
.setReadPreference(ReadPreference.primary());
return CloseableIterable.wrap(transform(cursor, new Function<DBObject, NodeDocument>() {
@Override
public NodeDocument apply(DBObject input) {
return store.convertFromDBObject(Collection.NODES, input);
}
}), cursor);
}
示例10: setReadWriteMode
import com.mongodb.ReadPreference; //導入依賴的package包/類
@Override
public void setReadWriteMode(String readWriteMode) {
if (readWriteMode == null || readWriteMode.equals(lastReadWriteMode)) {
return;
}
lastReadWriteMode = readWriteMode;
try {
Map<String, String> map = Splitter.on(", ").withKeyValueSeparator(":").split(readWriteMode);
String read = map.get("read");
if (read != null) {
ReadPreference readPref = ReadPreference.valueOf(read);
if (!readPref.equals(this.readPreference)) {
this.readPreference = readPref;
}
}
String write = map.get("write");
if (write != null) {
WriteConcern writeConcern = WriteConcern.valueOf(write);
if (!writeConcern.equals(this.writeConcern)) {
this.writeConcern = writeConcern;
}
}
} catch (Exception e) {
// unsupported or parse error - ignore
}
}
示例11: testMongoReadPreferencesDefault
import com.mongodb.ReadPreference; //導入依賴的package包/類
@Test
public void testMongoReadPreferencesDefault() throws Exception{
assertEquals(ReadPreference.primary(),
mongoDS.getMongoReadPreference(NODES,"foo", DocumentReadPreference.PRIMARY));
assertEquals(ReadPreference.primaryPreferred(),
mongoDS.getMongoReadPreference(NODES,"foo", DocumentReadPreference.PREFER_PRIMARY));
//By default Mongo read preference is primary
assertEquals(ReadPreference.primary(),
mongoDS.getMongoReadPreference(NODES,"foo", DocumentReadPreference.PREFER_SECONDARY));
//Change the default and assert again
mongoDS.getDBCollection(NODES).getDB().setReadPreference(ReadPreference.secondary());
assertEquals(ReadPreference.secondary(),
mongoDS.getMongoReadPreference(NODES,"foo", DocumentReadPreference.PREFER_SECONDARY));
//for case where parent age cannot be determined the preference should be primaryPreferred
assertEquals(ReadPreference.primaryPreferred(),
mongoDS.getMongoReadPreference(NODES,"foo", DocumentReadPreference.PREFER_SECONDARY_IF_OLD_ENOUGH));
//For collection other than NODES always primary
assertEquals(ReadPreference.primary(),
mongoDS.getMongoReadPreference(SETTINGS,"foo", DocumentReadPreference.PREFER_SECONDARY_IF_OLD_ENOUGH));
}
示例12: testMongoReadPreferencesWithAge
import com.mongodb.ReadPreference; //導入依賴的package包/類
@Test
public void testMongoReadPreferencesWithAge() throws Exception{
//Change the default
ReadPreference testPref = ReadPreference.secondary();
mongoDS.getDBCollection(NODES).getDB().setReadPreference(testPref);
NodeBuilder b1 = nodeStore.getRoot().builder();
b1.child("x").child("y");
nodeStore.merge(b1, EmptyHook.INSTANCE, CommitInfo.EMPTY);
String id = Utils.getIdFromPath("/x/y");
String parentId = Utils.getParentId(id);
mongoDS.invalidateCache(NODES,id);
//For modifiedTime < replicationLag primary should be preferred
assertEquals(ReadPreference.primaryPreferred(),
mongoDS.getMongoReadPreference(NODES,parentId, DocumentReadPreference.PREFER_SECONDARY_IF_OLD_ENOUGH));
//Going into future to make parent /x old enough
clock.waitUntil(Revision.getCurrentTimestamp() + replicationLag);
mongoDS.setClock(clock);
//For old modified nodes secondaries should be preferred
assertEquals(testPref,
mongoDS.getMongoReadPreference(NODES, parentId, DocumentReadPreference.PREFER_SECONDARY_IF_OLD_ENOUGH));
}
示例13: getLockCount
import com.mongodb.ReadPreference; //導入依賴的package包/類
public int getLockCount(String callerId, String resourceId) {
Date now = new Date();
BasicDBObject q = new BasicDBObject().
append(CALLERID, callerId).
append(RESOURCEID, resourceId).
append(EXPIRATION, new BasicDBObject("$gt", now)).
append(COUNT, new BasicDBObject("$gt", 0));
BasicDBObject field = new BasicDBObject(COUNT, 1);
DBObject lock = coll.findOne(q, field,ReadPreference.primary());
if (lock != null) {
int cnt = ((Number) lock.get(COUNT)).intValue();
LOGGER.debug("{}/{} lockCount={}", callerId, resourceId, cnt);
return cnt;
} else {
throw new InvalidLockException(resourceId);
}
}
示例14: ping
import com.mongodb.ReadPreference; //導入依賴的package包/類
public void ping(String callerId, String resourceId) {
Date now = new Date();
BasicDBObject q = new BasicDBObject().
append(CALLERID, callerId).
append(RESOURCEID, resourceId).
append(EXPIRATION, new BasicDBObject("$gt", now)).
append(COUNT, new BasicDBObject("$gt", 0));
DBObject lock = coll.findOne(q,null,ReadPreference.primary());
if (lock != null) {
Date expiration = new Date(now.getTime() + ((Number) lock.get(TTL)).longValue());
int ver = ((Number) lock.get(VERSION)).intValue();
BasicDBObject update = new BasicDBObject().
append("$set", new BasicDBObject(TIMESTAMP, now).
append(EXPIRATION, expiration)).
append("$inc", new BasicDBObject(VERSION, 1));
q = q.append(VERSION, ver);
WriteResult wr = coll.update(q, update, false, false, WriteConcern.ACKNOWLEDGED);
if (wr.getN() != 1) {
throw new InvalidLockException(resourceId);
}
LOGGER.debug("{}/{} pinged", callerId, resourceId);
} else {
throw new InvalidLockException(resourceId);
}
}
示例15: getFailedUpdates
import com.mongodb.ReadPreference; //導入依賴的package包/類
/**
* Returns the set of document ids that were not updated with docver
*
* @param docver The current document version
* @param documentIds The document ids to scan
*
* @return The set of document ids that were not updated with docver
*/
public static Set<Object> getFailedUpdates(DBCollection collection,
ObjectId docver,
List<Object> documentIds) {
Set<Object> failedIds=new HashSet<>();
if(!documentIds.isEmpty()) {
// documents with the given _ids and whose docver contains our docVer are the ones we managed to update
// others are failures
BasicDBObject query=new BasicDBObject(DOCVER_FLD,new BasicDBObject("$ne",docver));
query.append("_id",new BasicDBObject("$in",documentIds));
try (DBCursor cursor = collection.find(query,new BasicDBObject("_id",1))
.setReadPreference(ReadPreference.primary())) {
while(cursor.hasNext()) {
failedIds.add(cursor.next().get("_id"));
}
}
}
return failedIds;
}