你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn

使用 PowerShell 在 Azure SQL 数据库中监视和缩放弹性池

适用于:Azure SQL 数据库

此 PowerShell 脚本示例监视弹性池的性能指标,将其扩展到更高的计算大小,并基于性能指标之一创建警报规则。

如果没有 Azure 订阅,请在开始之前创建一个 Azure 免费帐户

注意

本文使用 Azure Az PowerShell 模块,这是与 Azure 交互时推荐使用的 PowerShell 模块。 若要开始使用 Az PowerShell 模块,请参阅安装 Azure PowerShell。 若要了解如何迁移到 Az PowerShell 模块,请参阅 将 Azure PowerShell 从 AzureRM 迁移到 Az

使用 Azure Cloud Shell

Azure 托管 Azure Cloud Shell(一个可通过浏览器使用的交互式 shell 环境)。 可以将 Bash 或 PowerShell 与 Cloud Shell 配合使用来使用 Azure 服务。 可以使用 Cloud Shell 预安装的命令来运行本文中的代码,而不必在本地环境中安装任何内容。

若要启动 Azure Cloud Shell,请执行以下操作:

选项 示例/链接
在代码块右上角选择试用。 选择“试用”不会自动将代码复制到 Cloud Shell。 显示 Azure Cloud Shell 的“试用”示例的屏幕截图。
转到 https://shell.azure.com 或选择“启动 Cloud Shell”按钮可在浏览器中打开 Cloud Shell。 显示如何在新窗口中启动 Cloud Shell 的屏幕截图。
选择 Azure 门户右上角菜单栏上的 Cloud Shell 按钮。 显示 Azure 门户中的 Cloud Shell 按钮的屏幕截图

若要在 Azure Cloud Shell 中运行本文中的代码,请执行以下操作:

  1. 启动 Cloud Shell。

  2. 选择代码块上的复制按钮以复制代码。

  3. 在 Windows 和 Linux 上选择 Ctrl+Shift+V,或在 macOS 上选择 Cmd+Shift+V 将代码粘贴到 Cloud Shell 会话中。

  4. 选择 Enter 运行此代码。

如果选择在本地安装并使用 PowerShell,则本教程需要 Az PowerShell 1.4.0 或更高版本。 如果需要升级,请参阅安装 Azure PowerShell 模块。 如果在本地运行 PowerShell,则还需运行 Connect-AzAccount 来创建与 Azure 的连接。

示例脚本

# This script requires the following
# - Az.Resources
# - Az.Accounts
# - Az.Monitor
# - Az.Sql

# First, run Connect-AzAccount

# Set the subscription in which to create these objects. This is displayed on objects in the Azure portal.
$subscriptionId = "<Subscription-ID>"
# Set the resource group name and location for your server
$resourceGroupName = "myResourceGroup-$(Get-Random)"
$location = "westus2"
# Set elastic pool name
$poolName = "MySamplePool"
# Set an admin login and password for your database
$adminSqlLogin = "<admin>"
$password = "<password>"
# Set server name - the logical server name has to be unique in the system
$serverName = "server-$(Get-Random)"
# The sample database names
$firstDatabaseName = "myFirstSampleDatabase"
$secondDatabaseName = "mySecondSampleDatabase"
# The IP address range that you want to allow to access your server via the firewall rule
$startIp = "0.0.0.0"
$endIp = "0.0.0.0"

# Set subscription
Set-AzContext -SubscriptionId $subscriptionId

# Create a new resource group
$resourceGroup = New-AzResourceGroup -Name $resourceGroupName -Location $location

$adminCredential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $adminSqlLogin, $(ConvertTo-SecureString -String $password -AsPlainText -Force)

# Create a new server with a system-wide unique server name
$serverParams = @{
    ResourceGroupName           = $resourceGroupName
    ServerName                  = $serverName
    Location                    = $location
    SqlAdministratorCredentials = $adminCredential
}
$server = New-AzSqlServer @serverParams

# Create elastic database pool
$elasticPoolParams = @{
    ResourceGroupName = $resourceGroupName
    ServerName        = $serverName
    ElasticPoolName   = $poolName
    Edition           = "Standard"
    Dtu               = 50
    DatabaseDtuMin    = 10
    DatabaseDtuMax    = 50
}
$elasticPool = New-AzSqlElasticPool @elasticPoolParams

# Create a server firewall rule that allows access from the specified IP range
$firewallParams = @{
    ResourceGroupName = $resourceGroupName
    ServerName        = $serverName
    FirewallRuleName  = "AllowedIPs"
    StartIpAddress    = $startIp
    EndIpAddress      = $endIp
}
$serverFirewallRule = New-AzSqlServerFirewallRule @firewallParams

# Create two blank databases in the pool
$firstDatabaseParams = @{
    ResourceGroupName = $resourceGroupName
    ServerName        = $serverName
    DatabaseName      = $firstDatabaseName
    ElasticPoolName   = $poolName
}
$firstDatabase = New-AzSqlDatabase @firstDatabaseParams
$secondDatabaseParams = @{
    ResourceGroupName = $resourceGroupName
    ServerName        = $serverName
    DatabaseName      = $secondDatabaseName
    ElasticPoolName   = $poolName
}
$secondDatabase = New-AzSqlDatabase @secondDatabaseParams

# Monitor the DTU consumption of the pool in 5-minute intervals
$monitorParameters = @{
    ResourceId  = "/subscriptions/$($(Get-AzContext).Subscription.Id)/resourceGroups/$resourceGroupName/providers/Microsoft.Sql/servers/$serverName/elasticPools/$poolName"
    TimeGrain   = [TimeSpan]::Parse("00:05:00")
    MetricNames = "dtu_consumption_percent"
}
$metric = Get-AzMetric @monitorParameters
$metric.Data

# Scale the pool
$scaleParams = @{
    ResourceGroupName = $resourceGroupName
    ServerName        = $serverName
    ElasticPoolName   = $poolName
    Edition           = "Standard"
    Dtu               = 100
    DatabaseDtuMin    = 20
    DatabaseDtuMax    = 100
}
$elasticPool = Set-AzSqlElasticPool @scaleParams

# Set up an Alert rule using Azure Monitor for the database
# Add an Alert that fires when the pool utilization reaches 90%
# Objects needed: an Action Group Receiver, an Action Group, Alert Criteria, and finally an Alert Rule.

# Creates a new action group receiver object with a target email address.
$receiver = New-AzActionGroupReceiver -Name "my Sample Azure Admins" -EmailAddress "azure-admins-group@contoso.com"

# Creates a new or updates an existing action group.
$actionGroupParams = @{
    Name              = "mysample-email-the-azure-admins"
    ShortName         = "AzAdminsGrp"
    ResourceGroupName = $resourceGroupName
    Receiver          = $receiver
}
$actionGroup = Set-AzActionGroup @actionGroupParams

# Fetch the created AzActionGroup into an object of type Microsoft.Azure.Management.Monitor.Models.ActivityLogAlertActionGroup
$actionGroupObject = New-AzActionGroup -ActionGroupId $actionGroup.Id

# Create a criteria for the Alert to monitor.
$criteriaParams = @{
    MetricName      = "dtu_consumption_percent"
    TimeAggregation = "Average"
    Operator        = "GreaterThan"
    Threshold       = 90
}
$criteria = New-AzMetricAlertRuleV2Criteria @criteriaParams

# Create the Alert rule.
# Add-AzMetricAlertRuleV2 adds or updates a V2 (non-classic) metric-based alert rule.
$alertRuleParams = @{
    Name              = "mySample_Alert_DTU_consumption_pct"
    ResourceGroupName = $resourceGroupName
    WindowSize        = (New-TimeSpan -Minutes 1)
    Frequency         = (New-TimeSpan -Minutes 1)
    TargetResourceId  = "/subscriptions/$($(Get-AzContext).Subscription.Id)/resourceGroups/$resourceGroupName/providers/Microsoft.Sql/servers/$serverName/elasticPools/$poolName"
    Condition         = $criteria
    ActionGroup       = $actionGroupObject
    Severity          = 3 #Informational
}
Add-AzMetricAlertRuleV2 @alertRuleParams

<#
# Set up an alert rule using Azure Monitor for the database
# Add a classic alert that fires when the pool utilization reaches 90%
# Note that Add-AzMetricAlertRule is deprecated. Use Add-AzMetricAlertRuleV2 instead.
$deprecatedAlertParams = @{
    ResourceGroup           = $resourceGroupName
    Name                    = "mySampleAlertRule"
    Location                = $location
    TargetResourceId        = "/subscriptions/$($(Get-AzContext).Subscription.Id)/resourceGroups/$resourceGroupName/providers/Microsoft.Sql/servers/$serverName/elasticPools/$poolName"
    MetricName              = "dtu_consumption_percent"
    Operator                = "GreaterThan"
    Threshold               = 90
    WindowSize              = $([TimeSpan]::Parse("00:05:00"))
    TimeAggregationOperator = "Average"
    Action                  = $(New-AzAlertRuleEmail -SendToServiceOwner)
}
Add-AzMetricAlertRule @deprecatedAlertParams
#>

# Clean up deployment
# Remove-AzResourceGroup -ResourceGroupName $resourceGroupName

清理部署

使用以下命令删除资源组及其相关的所有资源。

Remove-AzResourceGroup -ResourceGroupName $resourcegroupname

脚本说明

此脚本使用以下命令。 表中的每条命令链接到特定于命令的文档。

命令 注释
New-AzResourceGroup 创建用于存储所有资源的资源组。
New-AzSqlServer 创建托管数据库或弹性池的服务器。
New-AzSqlElasticPool 创建弹性池。
New-AzSqlDatabase 在服务器中创建数据库。
Get-AzMetric 显示数据库的使用大小信息。
Set-AzSqlElasticPool 更新弹性池属性。
Add-AzMetricAlertRule (DeprecateD) 添加或更新预警规则,以便在将来自动监视指标。 仅适用于经典的基于指标的警报规则。
Add-AzMetricAlertRuleV2 添加或更新警报规则,以便在将来自动监视指标。 仅适用于非经典的基于指标的警报规则。
Remove-AzResourceGroup 删除资源组,包括所有嵌套的资源。