mongodb AWS DocumentDB|关于文档数据库中的读取首选项选项

cunj1qz1  于 2023-06-05  发布在  Go
关注(0)|答案(1)|浏览(228)

我的DOCDB集群中有两个示例,主示例和读副本示例。我想使用读取复制副本示例执行大多数读取操作,但也想使用主示例执行少数选定查询。我计划创建一个Documentdb客户端,使用下面的连接URI:
mongodb://staging_docdb:@/?replicaSet=rs0&readPreference=secondaryPreferred&ssl=true&tlsCAFile=rds-combined-ca-bundle.pem&retryWrites=false
Above连接字符串允许我在副本集模式下创建一个documentdb客户端,并将Read replica用于所有读取操作,这是一条通用规则。现在我看到有几种情况下,我需要在插入任何资源或更新任何资源后触发读取操作,在这种情况下,因为读取请求转到立即读取副本示例,并且在读取副本中有一些滞后,以便从主示例获得最新更新,读取有时会给予不一致的数据,特别是对于立即创建或更新的资源。
我想配置一个readPreference=PrimaryPreferred的几个读查询后,立即创建或更新资源被触发。
我是否可以在创建客户端时使用readPreference=secondaryPreferred配置客户端,并覆盖少数特定读取查询的readPreference?我从AWS文档中得到这个想法,因为它说:* 您可以为特定查询设置读取首选项选项,或作为MongoDB驱动程序中的常规选项。(有关如何设置读取首选项选项的说明,请参阅客户端或驱动程序的文档。

参考:https://docs.aws.amazon.com/documentdb/latest/developerguide/how-it-works.html#durability-consistency-isolation
我浏览了AWS documentdb的文档:https://docs.aws.amazon.com/documentdb/latest/developerguide/how-it-works.html#durability-consistency-isolation,https://docs.aws.amazon.com/documentdb/latest/developerguide/connect-to-replica-set.html

k97glaaz

k97glaaz1#

您没有指定要使用的驱动程序。对于PyMongo,文档解释得很好。
Python3的一个简单例子来理解它是如何工作的,你需要安装pymongo库:

from pymongo import MongoClient, ReadPreference

##Create a MongoDB client object and specify the read preference as secondary preferred
client = MongoClient('mongodb://docdb.amazonaws.com:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')

##Specify the database to be used
db = client.sample_database

##Specify the collection to be used
col = db.sample_collection

##Insert a single document
col.insert_one({'hello':'Amazon DocumentDB'})

##Create another collection object and specify preference using with_options method
col_primary = col.with_options(read_preference=ReadPreference.PRIMARY)

##Get doc reading from Primary
doc = col_primary.find_one({'hello':'Amazon DocumentDB'})
print("doc: ", doc, "Using preference:", col_primary.read_preference)

##Get doc reading from Secondary
doc = col.find_one({'hello':'Amazon DocumentDB'})
print("doc: ", doc, "Using preference:", col.read_preference)

##Close the connection
client.close()

相关问题