當我使用 PowerShell 啟動多個 Amazon Elastic Compute Cloud (Amazon EC2) 執行個體時,收到 "RequestLimitExceeded" 錯誤。
解決方法
您用來啟動 EC2 執行個體的指令碼必須遵循 API 請求速率配額以及 API 資源速率配額。如果超出這些配額,就會收到 "RequestLimitExceeded" 錯誤。
若要解決此問題,請實作重試邏輯和指數退避策略。
注意: 根據預設,適用於 .NET 的 AWS SDK 內建重試機制。
先決條件:
如果您的請求速率可預測,且您可以事先加以控制,請使用延遲調用來從發生的限流中復原。
指令碼範例:
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: MIT-0
# Example Code to launch 50 EC2 instances of type 'm5a.large'.
try {
$params = @{
ImageId = 'AMI_ID'
InstanceType = 'm5a.large'
AssociatePublicIp = $false
SubnetId = 'Subnet_ID'
MinCount = 10
MaxCount = 15
}
for ($i=0;$i<5;$i++){
$instance = New-EC2Instance @params
Start-Sleep 5000 #Sleep for 5 seconds to allow Request bucket to refill at the rate of 2 requests per second
}
} catch {
Write-Error "An Exception Occurred!"
}
注意: 請將 AMI_ID 替換為您的 Amazon Machine Image (AMI) ID,Subnet_ID 替換為您的子網路 ID,並將 m5a.large 替換為您的執行個體類型。此外,請將 10 替換為要啟動的最少執行個體數量,並將 15 替換為要啟動的最大執行個體數量。
如果您的請求速率無法預測,請在指令碼中包含重試邏輯。
指令碼範例:
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: MIT-0
#Example Code to launch 50 EC2 instances of type 'm5a.large'.
$Stoploop = $false
[int] $Retrycount = "0"
do {
try {
$params = @{
ImageId = 'AMI_ID'
InstanceType = 'm5a.large'
AssociatePublicIp = $false
SubnetId = 'Subnet_ID'
MinCount = 40
MaxCount = 50
}
$instance = New-EC2Instance @params
$Stoploop = $true
} catch {
if ($Retrycount -gt 3) {
Write - Host "Could not complete request after 3 retries."
$Stoploop = $true
} else {
Write-Host "Could not complete request retrying in 5 seconds."
Start-Sleep -Seconds 25
#25 seconds of sleep allows for 50 request tokens to be refilled at the rate of 2/sec
$Retrycount = $Retrycount + 1
}
}
} While($Stoploop -eq $false)
注意: 請將 AMI_ID 替換為您的 AMI ID,Subnet_ID 替換為您的子網路 ID,並將 m5a.large 替換為您的執行個體類型。此外,請將 40 替換為要啟動的最少執行個體數量,並將 50 替換為要啟動的最大執行個體數量。
相關資訊
Request throttling for the Amazon EC2 API (要求適用於 Amazon EC2 API 的限流)
Retry behavior (重試行為)