如何使用 Azure Cosmos DB 的 API for MongoDB 在多个区域中分配读取操作How to multiple-regionally distribute reads using Azure Cosmos DB's API for MongoDB

本文介绍如何通过 Azure Cosmos DB 的 API for MongoDB 使用 MongoDB 读取首选项设置在多个区域中分配读取操作。This article shows how to multiple-regionally distribute read operations with MongoDB Read Preference settings using Azure Cosmos DB's API for MongoDB.

先决条件Prerequisites

如果没有 Azure 订阅,可在开始前创建一个试用帐户If you don't have an Azure subscription, create a trial account before you begin.

对于本教程,可以使用 Azure Cosmos DB 模拟器,其连接字符串为:You can use the Azure Cosmos DB Emulator for this tutorial with a connection string of:

mongodb://localhost:C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw==@localhost:10255/admin?ssl=true

请参阅此快速入门文章,了解如何使用 Azure 门户设置进行多区域分发的 Cosmos 帐户,然后连接到它。Refer to this Quickstart article for instructions on using the Azure portal to set up a Cosmos account with multiple-region distribution and then connect to it.

克隆示例应用程序Clone the sample application

打开 git 终端窗口(例如 git bash)并使用 cd 切换到工作目录。Open a git terminal window, such as git bash, and cd to a working directory.

运行以下命令克隆示例存储库。Run the following commands to clone the sample repository. 根据所需的平台,使用以下示例存储库之一:Based on your platform of interest, use one of the following sample repositories:

  1. .NET 示例应用程序.NET sample application
  2. NodeJS 示例应用程序NodeJS sample application
  3. Mongoose 示例应用程序Mongoose sample application
  4. Java 示例应用程序Java sample application
  5. SpringBoot 示例应用程序SpringBoot sample application
git clone <sample repo url>

运行应用程序Run the application

根据所用的平台,安装所需的包并启动应用程序。Depending on the platform used, install the required packages and start the application. 若要安装依赖项,请遵循示例应用程序存储库中包含的自述文件。To install dependencies, follow the README included in the sample application repository. 例如,在 NodeJS 示例应用程序中,使用以下命令安装所需的包并启动应用程序。For instance, in the NodeJS sample application, use the following commands to install the required packages and start the application.

cd mean
npm install
node index.js

应用程序会尝试连接到 MongoDB 源,但连接会失败,因为连接字符串无效。The application tries to connect to a MongoDB source and fails because the connection string is invalid. 遵循自述文件中的步骤更新连接字符串 urlFollow the steps in the README to update the connection string url. 此外,将 readFromRegion 更新为 Cosmos 帐户中的读取区域。Also, update the readFromRegion to a read region in your Cosmos account. 以下说明摘自 NodeJS 示例:The following instructions are from the NodeJS sample:

* Next, substitute the `url`, `readFromRegion` in App.Config with your Cosmos account's values. 

完成这些步骤后,示例应用程序将会运行并生成以下输出:After following these steps, the sample application runs and produces the following output:

connected!
readDefaultfunc query completed!
readFromNearestfunc query completed!
readFromRegionfunc query completed!
readDefaultfunc query completed!
readFromNearestfunc query completed!
readFromRegionfunc query completed!
readDefaultfunc query completed!
readFromSecondaryfunc query completed!

使用读取首选项模式进行读取Read using Read Preference mode

MongoDB 协议提供以下读取首选项模式供客户端使用:MongoDB protocol provides the following Read Preference modes for clients to use:

  1. PRIMARYPRIMARY
  2. PRIMARY_PREFERREDPRIMARY_PREFERRED
  3. SECONDARYSECONDARY
  4. SECONDARY_PREFERREDSECONDARY_PREFERRED
  5. NEARESTNEAREST

请参阅详细的 MongoDB 读取首选项行为文档,详细了解其中每种读取首选项模式的行为。Refer to the detailed MongoDB Read Preference behavior documentation for details on the behavior of each of these read preference modes. 在 Cosmos DB 中,primary 映射到 WRITE 区域,secondary 映射到 READ 区域。In Cosmos DB, primary maps to WRITE region and secondary maps to READ region.

根据常见的方案,我们建议使用以下设置:Based on common scenarios, we recommend using the following settings:

  1. 如果需要低延迟读取,可以使用 NEAREST 读取首选项模式。If low latency reads are required, use the NEAREST read preference mode. 此设置会将读取操作定向到最靠近的可用区域。This setting directs the read operations to the nearest available region. 请注意,如果最靠近的区域是 WRITE 区域,则这些操作会定向到该区域。Note that if the nearest region is the WRITE region, then these operations are directed to that region.
  2. 如果要求“读取操作高度可用且分散到不同的地区” (延迟不是约束条件),则使用“PRIMARY PREFERRED” 或“SECONDARY PREFERRED” 读取首选项模式。If high availability and geo distribution of reads are required (latency is not a constraint), then use the PRIMARY PREFERRED or SECONDARY PREFERRED read preference mode. 此设置会将读取操作分别定向到可用的 WRITE 或 READ 区域。This setting directs read operations to an available WRITE or READ region respectively. 如果该区域不可用,则根据读取首选项行为将请求定向到下一个可用区域。If the region is not available, then requests are directed to the next available region as per the read preference behavior.

示例应用程序中的以下代码片段演示如何在 NodeJS 中配置 NEAREST 读取首选项:The following snippet from the sample application shows how to configure NEAREST Read Preference in NodeJS:

  var query = {};
  var readcoll = client.db('regionDB').collection('regionTest', {readPreference: ReadPreference.NEAREST});
  readcoll.find(query).toArray(function(err, data) {
    assert.equal(null, err);
    console.log("readFromNearestfunc query completed!");
  });

同样,以下代码片段演示如何在 NodeJS 中配置 SECONDARY_PREFERRED 读取首选项:Similarly, the snippet below shows how to configure the SECONDARY_PREFERRED Read Preference in NodeJS:

  var query = {};
  var readcoll = client.db('regionDB').collection('regionTest', {readPreference: ReadPreference.SECONDARY_PREFERRED});
  readcoll.find(query).toArray(function(err, data) {
    assert.equal(null, err);
    console.log("readFromSecondaryPreferredfunc query completed!");
  });

还可以通过在连接字符串 URI 选项中将 readPreference 作为参数传递来设置读取首选项:The Read Preference can also be set by passing readPreference as a parameter in the connection string URI options:

const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');

// Connection URL
const url = 'mongodb://localhost:27017?ssl=true&replicaSet=globaldb&readPreference=nearest';

// Database Name
const dbName = 'myproject';

// Use connect method to connect to the Server
MongoClient.connect(url, function(err, client) {
  console.log("Connected correctly to server");

  const db = client.db(dbName);

  client.close();
});

请参阅其他平台(例如 .NETJava)的相应示例应用程序存储库。Refer to the corresponding sample application repos for other platforms, such as .NET and Java.

使用标记读取Read using tags

除了读取首选项模式以外,MongoDB 协议还允许使用标记来定向读取操作。In addition to the Read Preference mode, MongoDB protocol allows the use of tags to direct read operations. 在 Cosmos DB 的用于 MongoDB 的 API 中,region 标记已默认包含为 isMaster 响应的一部分:In Cosmos DB's API for MongoDB, the region tag is included by default as a part of the isMaster response:

"tags": {
         "region": "China North"
      }

因此,MongoClient 可以结合区域名称使用 region 标记将读取操作定向到特定的区域。Hence, MongoClient can use the region tag along with the region name to direct read operations to specific regions. 对于 Cosmos 帐户,可以在 Azure 门户中左侧的“设置”->“全局副本数据”下面找到区域名称。 For Cosmos accounts, region names can be found in Azure portal on the left under Settings->Replica data globally. 此设置可用于实现读取隔离 - 可让客户端应用程序将读取操作定向到特定的区域。This setting is useful for achieving read isolation - cases in which client application want to direct read operations to a specific region only. 此设置非常适合用于在后台运行的,并且不属于生产关键型服务的非生产/分析型方案。This setting is ideal for non-production/analytics type scenarios, which run in the background and are not production critical services.

示例应用程序中的以下代码片段演示如何在 NodeJS 中使用标记配置读取首选项:The following snippet from the sample application shows how to configure the Read Preference with tags in NodeJS:

 var query = {};
  var readcoll = client.db('regionDB').collection('regionTest',{readPreference: new ReadPreference(ReadPreference.SECONDARY_PREFERRED, {"region": "China North"})});
  readcoll.find(query).toArray(function(err, data) {
    assert.equal(null, err);
    console.log("readFromRegionfunc query completed!");
  });

请参阅其他平台(例如 .NETJava)的相应示例应用程序存储库。Refer to the corresponding sample application repos for other platforms, such as .NET and Java.

本文介绍了如何通过 Azure Cosmos DB 的 API for MongoDB 使用读取首选项在多个区域中分配读取操作。In this article, you've learned how to multiple-regionally distribute read operations using Read Preference with Azure Cosmos DB's API for MongoDB.

清理资源Clean up resources

如果不打算继续使用此应用,请删除本文在 Azure 门户中创建的所有资源,步骤如下:If you're not going to continue to use this app, delete all resources created by this article in the Azure portal with the following steps:

  1. 在 Azure 门户的左侧菜单中,单击“资源组”,然后单击已创建资源的名称。 From the left-hand menu in the Azure portal, click Resource groups and then click the name of the resource you created.
  2. 在资源组页上单击“删除” ,在文本框中键入要删除的资源的名称,并单击“删除” 。On your resource group page, click Delete, type the name of the resource to delete in the text box, and then click Delete.

后续步骤Next steps