[英]Jongo MongoDB: How to specify a default ReadPreference
I am aware that I can set the readPreference for each query using <collection>.withReadPreference(primaryPreferred()).find(...)
. 我知道我可以使用
<collection>.withReadPreference(primaryPreferred()).find(...)
为每个查询设置readPreference。 However, I would prefer to set a global default readPreference to use "nearest" if possible, and then be able to override this for individual queries if necessary. 但是,我希望将全局默认readPreference设置为在可能的情况下使用“ nearest”,然后在必要时能够为单个查询覆盖此默认值。 Is there a possible/preferred way to do this using Jongo?
有没有可能/首选的方法来使用Jongo?
Edit: Since Jongo is initialized using MongoClient().getDB()
, would it therefor be suitable to initialize my MongoClient with options specifying the ReadPreference? 编辑:由于
MongoClient().getDB()
是使用MongoClient().getDB()
初始化的,因此是否适合使用指定ReadPreference的选项来初始化我的MongoClient? I guess what I'm asking is - if I do it this way, will these settings carry over and be applied inside of Jongo, or is there a different way to handle it in Jongo directly? 我想我要问的是-如果我这样做,这些设置是否会延续并应用到Jongo中,或者是否有其他方法可以直接在Jongo中进行处理?
Thanks ahead of time. 提前谢谢。
Probably should have just tried it before asking, but I will provide an answer for anyone who may have this question in the future. 可能在提出问题之前应该已经尝试过,但是我将为以后可能遇到此问题的任何人提供答案。 The short answer is - Yes, setting it via the MongoClient using the MongoClientOptions object will carry over to Jongo.
简短的答案是-是的,通过使用MongoClientOptions对象的MongoClient进行设置将继承到Jongo。
Specifically, I had something like this in a method to build the options (made it more verbose than I had to for clarity for this example): 具体来说,我在构建选项的方法中有这样的东西(使该示例比为清晰起见而更加冗长):
protected MongoClientOptions getOptions(){
MongoClientOptions mClientOpts;
Builder mClientOptionsBuilder = new MongoClientOptions.Builder();
mClientOptionsBuilder.readPreference(ReadPreference.nearest());
mClientOpts = mClientOptionsBuilder.build();
System.out.println("[MongoConfig]: " + mClientOpts.toString());
return mClientOpts;
}
Then you can just instantiate a new MongoClient(new ServerAddress(...), this.getOptions());
然后,您可以实例化一个
new MongoClient(new ServerAddress(...), this.getOptions());
and use that client instance to get your database reference which is finally used as an argument to instantiate Jongo. 并使用该客户端实例获取您的数据库引用,该引用最终用作实例化Jongo的参数。
To be clear, the reason I was doing this was to be able to read from Secondary members of a MongoDB ReplicaSet if/when those were available with the lowest latency. 需要明确的是,我这样做的原因是,如果/当延迟最小时,它们可以从MongoDB ReplicaSet的次要成员中读取。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.