如何在ARM模板中配置Cosmos DB的PreferredLocations属性
在ARM模板中配置Cosmos DB的PreferredLocations属性
我来帮你搞定这个问题!要在ARM模板里设置Cosmos DB的PreferredLocations属性,你只需要修改Microsoft.DocumentDB/databaseAccounts资源的配置部分,具体操作和示例如下:
1. 定位Cosmos DB账户资源
首先找到模板里定义Cosmos DB账户的节点,它的type为Microsoft.DocumentDB/databaseAccounts,建议使用较新的apiVersion(比如2023-04-15)以获得完整的配置支持。
2. 添加PreferredLocations配置
在该资源的properties节点下,新增preferredLocations数组,数组元素是你要指定的优先读取区域的官方名称(必须和locations数组里的locationName完全一致,比如East US、West Europe这类标准区域名)。
完整配置示例
{ "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#", "contentVersion": "1.0.0.0", "parameters": { "accountName": { "type": "string", "metadata": { "description": "Cosmos DB账户名称" } }, "primaryLocation": { "type": "string", "metadata": { "description": "写入区域A的位置" } }, "secondaryLocation": { "type": "string", "metadata": { "description": "备用区域B的位置" } } }, "resources": [ { "type": "Microsoft.DocumentDB/databaseAccounts", "apiVersion": "2023-04-15", "name": "[parameters('accountName')]", "location": "[parameters('primaryLocation')]", "properties": { "databaseAccountOfferType": "Standard", // 已有的多区域部署配置 "locations": [ { "locationName": "[parameters('primaryLocation')]", "failoverPriority": 0, "isZoneRedundant": false }, { "locationName": "[parameters('secondaryLocation')]", "failoverPriority": 1, "isZoneRedundant": false } ], // 新增的PreferredLocations配置 "preferredLocations": [ "[parameters('secondaryLocation')]", // 优先尝试读取区域B "[parameters('primaryLocation')]" // 区域B不可用时 fallback到区域A ], // 其他现有配置(如一致性策略等) "consistencyPolicy": { "defaultConsistencyLevel": "Session" } } } ] }
关键注意事项
- 区域名称一致性:
preferredLocations里的区域名称必须和locations数组中的locationName完全匹配,否则配置不会生效。 - 优先级顺序:数组的顺序就是客户端读取的优先级,当第一个区域不可用时,SDK会自动尝试下一个可用区域。针对你的场景,把区域B放在第一位,就能保证A故障时客户端优先读取B的可用数据。
- SDK自动适配:使用最新版本的Cosmos DB SDK(比如.NET SDK v3+、Java SDK v4+等)时,客户端会自动从账户配置中获取
preferredLocations,完全不需要在代码里手动设置ConnectionPolicy.PreferredLocations,完美契合你的需求。
最后操作
修改完ARM模板后,重新部署模板更新Cosmos DB账户配置即可。部署完成后,当区域A再次故障时,客户端会自动切换到区域B提供正常的读取服务。
内容的提问来源于stack exchange,提问作者Natalie Polishuk
相关产品推荐
相关产品推荐

