You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过Azure.ResourceManager缩放Azure AppService/WebApp实例数?

解决方案

缩放App Service实例数本质是调整其所属App Service Plan的实例容量,因为Web App的运行实例数由关联的Plan控制。以下是具体实现步骤:

1. 获取目标Web App资源

通过已有的ResourceGroupResource实例,获取对应的WebSiteResource(即你的App Service):

// 替换为你的Web App名称
string webAppName = "your-web-app-name";
WebSiteResource webApp = await resourceGroup.GetWebSiteAsync(webAppName);

2. 获取关联的App Service Plan

从Web App的属性中提取Plan的资源ID,再通过ArmClient获取对应的AppServicePlanResource:

// 获取App Service Plan的资源ID
string planId = webApp.Data.ServerFarmId;
// 解析并获取AppServicePlanResource
AppServicePlanResource appServicePlan = client.GetAppServicePlanResource(new ResourceIdentifier(planId));

3. 调整实例容量

创建更新参数,修改Sku.Capacity值后提交更新:

// 替换为你根据数据库数据量计算出的目标实例数
int targetInstanceCount = 3;

// 获取当前Plan的配置数据
AppServicePlanData planData = appServicePlan.Data;
// 修改实例容量
planData.Sku.Capacity = targetInstanceCount;

// 提交更新并等待完成
await appServicePlan.UpdateAsync(WaitUntil.Completed, planData);

完整代码示例

结合你已有的代码,完整实现如下:

using Azure;
using Azure.Identity;
using Azure.ResourceManager;
using Azure.ResourceManager.AppService;

// 初始化ArmClient
ArmClient client = new ArmClient(new DefaultAzureCredential());
string resourceGroupName = "your-resource-group-name";
string webAppName = "your-web-app-name";

// 获取资源组
ResourceGroupResource resourceGroup = await client.GetDefaultSubscriptionAsync().Result.GetResourceGroupAsync(resourceGroupName);

// 获取目标Web App
WebSiteResource webApp = await resourceGroup.GetWebSiteAsync(webAppName);

// 获取关联的App Service Plan
string planId = webApp.Data.ServerFarmId;
AppServicePlanResource appServicePlan = client.GetAppServicePlanResource(new ResourceIdentifier(planId));

// 根据数据库数据量计算目标实例数(此处为示例值,替换为你的业务逻辑)
int targetInstanceCount = 2;

// 更新实例容量
AppServicePlanData updateData = appServicePlan.Data;
updateData.Sku.Capacity = targetInstanceCount;
await appServicePlan.UpdateAsync(WaitUntil.Completed, updateData);

注意事项

  • 确保Azure函数拥有Microsoft.Web/serverfarms/write权限,可通过RBAC角色(如「网站参与者」)或自定义角色分配。
  • 消耗计划无法手动调整实例数,仅专用/弹性计划支持手动缩放操作。
  • 建议添加异常处理,覆盖资源不存在、权限不足等场景。

内容的提问来源于stack exchange,提问作者Camil-P

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 14:54:56